Repository navigation
Enable Activity Embeds (aka FxEmbed 2.0) - #1203
Conversation
|
Warning Rate limit exceeded@dangeredwolf has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 15 seconds before requesting another review. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. 📒 Files selected for processing (3)
📝 WalkthroughWalkthroughThis pull request implements a comprehensive rebranding of the project from "FxTwitter / FixupX" to "FxEmbed." It removes outdated branding-related environment variables and URL constants, updates documentation and configuration files, and bumps the project version. New helper functions and type definitions are introduced to centralize branding logic and enhance type safety, while API routes and experimental flags are refactored to support the new branding and improved control flow. Additional changes include dependency upgrades and modifications in build configurations and testing files. Changes
Sequence Diagram(s)sequenceDiagram
participant C as Client
participant R as Router
participant BG as getBranding
participant HA as handleActivity
participant EXP as Experiment Check
participant SC as encodeSnowcode
C->>R: Send request (e.g., GET /api/v1/statuses/:id)
R->>BG: Retrieve branding info
BG-->>R: Return Branding Object
R->>EXP: Check experiment flags (e.g., ACTIVITY_EMBED)
EXP-->>R: Experiment flag result
R->>HA: Invoke handleActivity with branding & flags
HA->>SC: (If applicable) Encode snowcode for header
SC-->>HA: Return encoded snowflake
HA-->>R: Return embed data or redirect URL
R-->>C: Respond with dynamic content based on branding
sequenceDiagram
participant U as User
participant EC as encodeSnowcode
participant DC as decodeSnowcode
U->>EC: Provide JSON object for encoding
EC-->>U: Return encoded snowcode string
U->>DC: Provide snowcode string for decoding
DC-->>U: Return decoded JSON object
Poem
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
| response['media_attachments'] = media.map((media) => { | ||
| switch (media.type) { | ||
| case 'photo': | ||
| const image = media as APIPhoto; |
Check failure
Code scanning / ESLint
Disallow lexical declarations in case clauses
| }; | ||
| case 'video': | ||
| case 'gif': | ||
| const video = media as APIVideo; |
Check failure
Code scanning / ESLint
Disallow lexical declarations in case clauses
| import { handleActivity } from '../../../embed/activity'; | ||
|
|
||
| /* Handler for activity request */ | ||
| export const activityRequest = async (c: Context) => { |
Check warning
Code scanning / ESLint
Cognitive Complexity of functions should not be too high
| const appBody = await app.text(); | ||
| if (appBody.includes('<!doctype html>')) { | ||
| return c.html(appBody, 200); | ||
| } else if (baseUrl.startsWith('twitter://')) { |
Check failure
Code scanning / ESLint
String literals should not be duplicated
| if (appBody.includes('<!doctype html>')) { | ||
| return c.html(appBody, 200); | ||
| } else if (baseUrl.startsWith('twitter://')) { | ||
| console.log('twitter:// redirect'); |
Check failure
Code scanning / ESLint
String literals should not be duplicated
| console.log('twitter:// redirect'); | ||
| return c.redirect(`${baseUrl}/status?id=${id}`, 302); | ||
| } else { | ||
| console.log('normal redirect'); |
Check failure
Code scanning / ESLint
String literals should not be duplicated
There was a problem hiding this comment.
Actionable comments posted: 3
♻️ Duplicate comments (2)
src/helpers/branding.ts (1)
22-22:⚠️ Potential issueRemove unused variable warning
The unused variable
_eis triggering linter warnings.- } catch (_e) { + } catch {Since you're not using the error variable, use an empty catch block instead.
🧰 Tools
🪛 ESLint
[error] 22-22: '_e' is defined but never used.
(@typescript-eslint/no-unused-vars)
🪛 GitHub Check: ESLint
[failure] 22-22: Disallow unused variables
'_e' is defined but never used.src/embed/activity.ts (1)
206-405:⚠️ Potential issueMain
handleActivityfunction is well-structured.
- Uses
decodeSnowcodeeffectively for multi-field extraction (ID, language, handle).- Fetches and constructs relevant threads from Twitter or Bluesky.
- Implements i18n initialization for user-facing text.
- Produces a Mastodon-compatible JSON response, beneficial for bridging with external apps.
However, there's a lint warning on lexical declarations within switch cases near lines 322-324, 343-346:
You declareconst imageandconst videoinsidecaseblocks. To avoid variable leakage or hoisting hazards, wrap eachcaseblock in its own braces:switch (media.type) { case 'photo': { - const image = media as APIPhoto; - return { + const image = media as APIPhoto; + return { ... } } case 'video': case 'gif': { - const video = media as APIVideo; + const video = media as APIVideo; ... } }Addressing this improves maintainability and fixes lint errors related to lexical declarations in case clauses.
🧰 Tools
🪛 Biome (1.9.4)
[error] 322-324: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 343-344: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 346-346: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
🪛 GitHub Check: ESLint
[failure] 322-322: Disallow lexical declarations in case clauses
Unexpected lexical declaration in case block.
[failure] 343-343: Disallow lexical declarations in case clauses
Unexpected lexical declaration in case block.
[failure] 344-344: Disallow lexical declarations in case clauses
Unexpected lexical declaration in case block.
🧹 Nitpick comments (17)
src/caches.ts (1)
45-45: Cache exclusion added for status API endpoints.This change prevents caching of requests to
/api/v1/statusesendpoints, which is a good practice since status data is typically dynamic and should always be fresh.Consider adding a brief comment explaining why status endpoints are excluded from caching for better code documentation:
if ( !Constants.API_HOST_LIST.includes(cacheUrl.hostname) && + // Status endpoints contain dynamic data that should not be cached !cacheUrl.pathname.startsWith('/api/v1/statuses') && !request.header('Cookie')?.includes('base_redirect') ) {src/helpers/utils.ts (1)
70-74: Snowflake ID generation function implemented.The
generateSnowflakefunction creates unique IDs based on Twitter's snowflake algorithm, combining timestamps with random values. This implementation correctly uses BigInt to handle the bit operations.For better maintainability, consider extracting the magic number 696969 into a named constant:
export const generateSnowflake = () => { const epoch = 1288834974657n; /* Twitter snowflake epoch */ + const MAX_RANDOM_ID = 696969; const timestamp = BigInt(Date.now()) - epoch; - return String((timestamp << 22n) | BigInt(Math.floor(Math.random() * 696969))); + return String((timestamp << 22n) | BigInt(Math.floor(Math.random() * MAX_RANDOM_ID))); };src/helpers/linkFixer.ts (1)
30-32: Added semicolons to console.log statements.Adding semicolons to the console.log statements improves code consistency. While these logs are helpful for debugging, consider implementing a proper logging system for production code or adding logic to disable these logs in production environments.
src/realms/api/routes/oembed.ts (1)
31-31: Consider using c.json() for consistency.While line 29 sets the content-type header to 'application/json', consider using c.json(data, 200) instead of c.text(JSON.stringify(data), 200) for consistency with the bluesky version and to simplify the code.
- return c.text(JSON.stringify(data), 200); + return c.json(data, 200);src/helpers/branding.ts (1)
18-21: Consider handling subdomain-based brandingThe current domain extraction logic only considers the last two parts of the hostname.
- // get domain name, without subdomains - const domain = url.hostname.split('.').slice(-2).join('.'); + // Try exact hostname first, then fallback to domain without subdomains + const hostname = url.hostname; + const domain = hostname.split('.').slice(-2).join('.'); + return zones.find(zone => zone.domains.includes(hostname) || zone.domains.includes(domain)) ?? defaultBranding;This change would allow both exact hostname matches (including subdomains) and domain-only matches, providing more flexibility in your branding configuration.
src/realms/bluesky/routes/status.ts (2)
83-83: Consider moving the traffic control URL to constantsThe hardcoded URL could be moved to a constant for better maintainability.
+// In constants.ts +export const TRAFFIC_CONTROL_URL = 'https://app.fxembed.com'; // In this file - const app = await fetch(`https://app.fxembed.com/profile/${handle}/post/${actualId}`); + const app = await fetch(`${Constants.TRAFFIC_CONTROL_URL}/profile/${handle}/post/${actualId}`);This would make it easier to update the URL in the future and keep URLs consistent across the codebase.
85-85: Use more reliable HTML detectionThe current check for HTML content is simplistic and might be prone to false positives.
- if (appBody.includes('<!doctype html>')) { + const contentType = app.headers.get('content-type'); + if (contentType?.includes('text/html') && appBody.includes('<!doctype html>')) {This change checks both the Content-Type header and the document content, providing a more reliable way to determine if the response is valid HTML.
src/embed/activity.ts (3)
17-36: Refactor poll rendering for localization clarity.The
generatePollfunction appends a text-based bar and uses i18n for vote counts. Consider adding localized or accessible text for screen readers, or customizing the bar’s length if dealing with variable-locale text expansions.
75-92: Mention linking logic.
linkifyMentionsproperly transforms mentions into clickable links. The approach of deduplicating matches before replacement is efficient. Just ensure you handle edge cases like underscores in handles or domain-level collisions (e.g., partial user matches).
112-123: URL detection withstatusLinkWrapper.Regex-based URL detection with
escapeRegexhelps avoid link collisions. For more robust coverage of unusual TLDs or non-English domains, consider a more advanced URL parser library. Otherwise, approach looks practical.src/realms/twitter/routes/profile.ts (2)
57-60: Check for safety around baseUrl usage.
Consider validating or sanitizingbaseUrlbefore concatenating with/${handle}to mitigate unexpected edge cases.
83-93: Refactor duplicate code path.
The logic of fetching and rendering HTML is repeated here; consider extracting it into a helper function to reduce redundancy and improve maintainability.src/realms/twitter/routes/activity.ts (2)
14-41: Consolidate domain checks.
Multiple domain and path checks contribute to complexity. Consider extracting some logic into a helper function to simplify and improve readability.
89-91: Fallback error path.
Returning a 500 with a descriptive error message handles unexpected null responses. Consider adding logs to help diagnose rare failures.src/realms/twitter/router.ts (1)
35-46: Consider handling fetch failures more gracefully and remove unused variable.
- If
fetch(branding.favicon)fails, redirecting to the samefaviconURL may cause repeated failures in certain scenarios. Consider a fallback solution (e.g., serving a local icon).- The caught error variable
eis unused. You can safely remove it or log it for debugging.try { const response = await fetch(branding.favicon); ... } catch { - } catch (e) { return c.redirect(branding.favicon, 302); }🧰 Tools
🪛 ESLint
[error] 43-43: 'e' is defined but never used.
(@typescript-eslint/no-unused-vars)
README.md (1)
124-126: Missing image alt text throughout the document.Several images in the document are missing alt text, which affects accessibility for users with screen readers.
Consider adding descriptive alt text to all images in the document, for example:
- +🧰 Tools
🪛 LanguageTool
[style] ~124-~124: ‘off of’ might be wordy. Consider a shorter alternative.
Context: ... have any ads or tracking to make money off of, nor do we sell data. Temporary real-t...(EN_WORDINESS_PREMIUM_OFF_OF)
[typographical] ~126-~126: The word “however” is an adverb that can’t be used like a conjunction, and therefore needs to be separated from the sentence.
Context: ...to make sure things work as they should), however these logs are only shown in the termin...(HOWEVER_SENTENCE)
src/types/vendor/twitter.d.ts (1)
475-475: Consider adding JSDoc comments to type definitions.The newly added types would benefit from JSDoc comments explaining their purpose and usage, especially since this file serves as a reference for Twitter's API objects.
Consider adding JSDoc comments to the new type definitions, for example:
+/** + * Represents a tag entity like a hashtag or symbol in a tweet + */ type TagEntity = { indices: [number, number]; text: string; }; +/** + * Represents a user mention entity in a tweet + */ type MentionEntity = { indices: [number, number]; name: string; screen_name: string; id_str: string; }; +/** + * Represents an inline media attachment in a tweet + */ type InlineMedia = { index: number; media_id: string; };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (14)
.github/logos/fixupx.svgis excluded by!**/*.svg.github/logos/fixupx32.pngis excluded by!**/*.png.github/logos/fxbluesky32.pngis excluded by!**/*.png.github/logos/fxembed.svgis excluded by!**/*.svg.github/logos/fxembedpfp.pngis excluded by!**/*.png.github/logos/fxembedpfp.svgis excluded by!**/*.svg.github/logos/fxtwitter32.pngis excluded by!**/*.png.github/readme/directmedia.pngis excluded by!**/*.png.github/readme/iv.pngis excluded by!**/*.png.github/readme/poll.pngis excluded by!**/*.png.github/readme/quote.pngis excluded by!**/*.png.github/readme/tco.pngis excluded by!**/*.png.github/readme/videos.pngis excluded by!**/*.pngpackage-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (43)
.env.example(1 hunks).gitignore(1 hunks)README.md(3 hunks)branding.default.json(1 hunks)esbuild.config.mjs(0 hunks)jestconfig.json(0 hunks)motd.json(0 hunks)package.json(2 hunks)src/caches.ts(1 hunks)src/constants.ts(2 hunks)src/embed/activity.ts(1 hunks)src/embed/status.ts(15 hunks)src/experiments.ts(2 hunks)src/fetch.ts(3 hunks)src/helpers/branding.ts(1 hunks)src/helpers/linkFixer.ts(2 hunks)src/helpers/snowcode.ts(1 hunks)src/helpers/unicodestring.ts(1 hunks)src/helpers/utils.ts(1 hunks)src/providers/bsky/processor.ts(3 hunks)src/providers/twitter/processor.ts(6 hunks)src/realms/api/routes/oembed.ts(2 hunks)src/realms/bluesky/router.ts(1 hunks)src/realms/bluesky/routes/activity.ts(1 hunks)src/realms/bluesky/routes/oembed.ts(2 hunks)src/realms/bluesky/routes/status.ts(1 hunks)src/realms/common/version.ts(2 hunks)src/realms/twitter/router.ts(4 hunks)src/realms/twitter/routes/activity.ts(1 hunks)src/realms/twitter/routes/profile.ts(4 hunks)src/realms/twitter/routes/redirects.ts(3 hunks)src/realms/twitter/routes/status.ts(3 hunks)src/render/instantview.ts(2 hunks)src/render/photo.ts(2 hunks)src/render/video.ts(3 hunks)src/strings.ts(2 hunks)src/types/env.d.ts(0 hunks)src/types/types.d.ts(5 hunks)src/types/vendor/bsky.d.ts(1 hunks)src/types/vendor/twitter.d.ts(3 hunks)src/user.ts(2 hunks)src/worker.ts(4 hunks)tsconfig.json(1 hunks)
💤 Files with no reviewable changes (4)
- motd.json
- esbuild.config.mjs
- src/types/env.d.ts
- jestconfig.json
🧰 Additional context used
🧬 Code Definitions (14)
src/providers/bsky/processor.ts (1)
src/helpers/linkFixer.ts (1) (1)
linkFixerBsky(27-49)
src/realms/common/version.ts (1)
src/helpers/branding.ts (1) (1)
getBranding(14-25)
src/embed/activity.ts (6)
src/embed/status.ts (2) (2)
DataProvider(678-678)returnError(31-43)src/constants.ts (1) (1)
Constants(1-78)src/helpers/utils.ts (1) (1)
escapeRegex(76-78)src/helpers/snowcode.ts (1) (1)
decodeSnowcode(19-37)src/strings.ts (1) (1)
Strings(18-264)src/experiments.ts (1) (1)
experimentCheck(67-72)
src/render/instantview.ts (1)
src/helpers/branding.ts (1) (1)
getBranding(14-25)
src/realms/bluesky/routes/activity.ts (2)
src/embed/activity.ts (1) (1)
handleActivity(206-406)src/embed/status.ts (1) (1)
DataProvider(678-678)
src/realms/twitter/routes/redirects.ts (2)
src/constants.ts (1) (1)
Constants(1-78)src/helpers/branding.ts (1) (1)
getBranding(14-25)
src/realms/twitter/routes/activity.ts (3)
src/constants.ts (1) (1)
Constants(1-78)src/realms/twitter/router.ts (1) (1)
getBaseRedirectUrl(18-32)src/embed/activity.ts (1) (1)
handleActivity(206-406)
src/realms/bluesky/router.ts (4)
src/realms/bluesky/routes/activity.ts (1) (1)
activityRequest(8-52)src/realms/bluesky/routes/redirects.ts (1) (1)
genericBlueskyRedirect(4-7)src/realms/common/version.ts (1) (1)
versionRoute(6-24)src/helpers/branding.ts (1) (1)
getBranding(14-25)
src/helpers/linkFixer.ts (1)
src/helpers/unicodestring.ts (1) (1)
UnicodeString(9-33)
src/realms/twitter/routes/profile.ts (1)
src/experiments.ts (1) (1)
experimentCheck(67-72)
src/realms/twitter/routes/status.ts (3)
src/experiments.ts (1) (1)
experimentCheck(67-72)src/constants.ts (1) (1)
Constants(1-78)src/worker.ts (2) (2)
app(28-59)fetch(159-191)
src/render/photo.ts (1)
src/helpers/branding.ts (1) (1)
getBranding(14-25)
src/render/video.ts (1)
src/helpers/branding.ts (1) (1)
getBranding(14-25)
src/realms/twitter/router.ts (5)
src/helpers/branding.ts (1) (1)
getBranding(14-25)src/realms/twitter/routes/status.ts (1) (1)
statusRequest(10-208)src/realms/twitter/routes/profile.ts (1) (1)
profileRequest(9-95)src/realms/twitter/routes/activity.ts (1) (1)
activityRequest(9-92)src/realms/common/version.ts (1) (1)
versionRoute(6-24)
🪛 Biome (1.9.4)
src/embed/activity.ts
[error] 322-324: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 343-344: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 346-346: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
src/realms/twitter/routes/activity.ts
[error] 56-56: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🪛 GitHub Check: ESLint
src/embed/activity.ts
[failure] 322-322: Disallow lexical declarations in case clauses
Unexpected lexical declaration in case block.
[failure] 343-343: Disallow lexical declarations in case clauses
Unexpected lexical declaration in case block.
[failure] 344-344: Disallow lexical declarations in case clauses
Unexpected lexical declaration in case block.
src/helpers/branding.ts
[failure] 22-22: Disallow unused variables
'_e' is defined but never used.
src/realms/twitter/routes/activity.ts
[warning] 9-9: Cognitive Complexity of functions should not be too high
Refactor this function to reduce its Cognitive Complexity from 22 to the 20 allowed.
src/realms/twitter/routes/status.ts
[failure] 151-151: String literals should not be duplicated
Define a constant instead of duplicating this literal 4 times.
[failure] 152-152: String literals should not be duplicated
Define a constant instead of duplicating this literal 4 times.
[failure] 155-155: String literals should not be duplicated
Define a constant instead of duplicating this literal 4 times.
🪛 ESLint
src/helpers/branding.ts
[error] 22-22: '_e' is defined but never used.
(@typescript-eslint/no-unused-vars)
src/realms/twitter/routes/status.ts
[error] 151-151: Define a constant instead of duplicating this literal 4 times.
(sonarjs/no-duplicate-string)
[error] 152-152: Define a constant instead of duplicating this literal 4 times.
(sonarjs/no-duplicate-string)
[error] 155-155: Define a constant instead of duplicating this literal 4 times.
(sonarjs/no-duplicate-string)
src/realms/twitter/router.ts
[error] 43-43: 'e' is defined but never used.
(@typescript-eslint/no-unused-vars)
🪛 GitHub Actions: Build
src/helpers/branding.ts
[error] 2-2: ERROR: Could not resolve '../../branding.json'
🪛 GitHub Actions: Tests
src/helpers/branding.ts
[error] 2-2: Build failed: Could not resolve '../../branding.json'.
🪛 markdownlint-cli2 (0.17.2)
README.md
1-1: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
29-29: Trailing punctuation in heading
Punctuation: '.'
(MD026, no-trailing-punctuation)
41-41: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
49-49: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
55-55: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
65-65: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
94-94: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
100-100: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
106-106: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
112-112: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
155-155: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
155-155: Images should have alternate text (alt text)
null
(MD045, no-alt-text)
🪛 LanguageTool
README.md
[uncategorized] ~31-~31: Loose punctuation mark.
Context: ...ith-privacy-in-mind). ### twitter.com: Add fx before your twitter.com link...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~33-~33: Loose punctuation mark.
Context: ...ore your twitter.com link ### x.com: Add fixup before your x.com link #...
(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~35-~35: Loose punctuation mark.
Context: ...before your x.com link ### bsky.app: Add fx before your bsky.app link #...
(UNLIKELY_OPENING_PUNCTUATION)
[typographical] ~97-~97: Consider adding a comma after ‘Basically’ for more clarity.
Context: ...readme/gallery.png) ## Text-only view Basically the opposite of gallery view, use `t.fx...
(RB_LY_COMMA)
[grammar] ~104-~104: Did you mean “until” or “up to”?
Context: ...ep track of any posts being replied to, up until the start of a conversation. 
[style] ~124-~124: ‘off of’ might be wordy. Consider a shorter alternative.
Context: ... have any ads or tracking to make money off of, nor do we sell data. Temporary real-t...
(EN_WORDINESS_PREMIUM_OFF_OF)
[typographical] ~126-~126: The word “however” is an adverb that can’t be used like a conjunction, and therefore needs to be separated from the sentence.
Context: ...to make sure things work as they should), however these logs are only shown in the termin...
(HOWEVER_SENTENCE)
[uncategorized] ~134-~134: Possible missing comma found.
Context: ...Embed? Let's compare using FxTwitter / FixupX since it's the most feature-complete. H...
(AI_HYDRA_LEO_MISSING_COMMA)
[style] ~210-~210: The phrase ‘feel free to’ is used quite frequently. Consider using a less frequent alternative to set your writing apart from others and make it sound more professional.
Context: ...ensed under the permissive MIT license. Feel free to send a pull request!** ## Star History...
(FEEL_FREE_TO_STYLE_ME)
[style] ~223-~223: The phrase ‘feel free to’ is used quite frequently. Consider using a less frequent alternative to set your writing apart from others and make it sound more professional.
Context: ... ## Bugs or issues? Feel free to [open an issue](https://github.com/FxEm...
(FEEL_FREE_TO_STYLE_ME)
🔇 Additional comments (124)
.gitignore (1)
6-7: Additional files correctly excluded from version control.Adding
.wranglerandbranding.jsonto the gitignore file aligns with the rebranding effort by ensuring that local branding configurations aren't accidentally committed.src/types/vendor/bsky.d.ts (1)
121-126: Minor formatting improvements to TypeScript interface.The changes here are purely stylistic, adding semicolons after properties in the
BlueskyFacetinterface to maintain consistent formatting with the rest of the codebase.src/providers/bsky/processor.ts (3)
15-18: Code reformatting for better readability.Breaking the function call into multiple lines improves readability of the code without changing its functionality.
134-134: TODO comment indentation fixed.The comment indentation has been corrected to be consistent with the codebase style.
144-147: Multi-line expression improves readability.The complex aspectRatio assignment has been reformatted into multiple lines, making it easier to read and maintain.
src/strings.ts (2)
62-62: Updated error message to reflect platform-agnostic branding.Changed from mentioning a "Twitter outage" to an "upstream outage" to align with the rebranding from FxTwitter to FxEmbed, making the error message more generic and applicable to multiple platforms.
108-108: Updated theme color for brand consistency.The theme color has been changed from
#1E98F0(Twitter blue) to#6363ffto match the new FxEmbed branding palette. This ensures visual consistency across the application.src/helpers/unicodestring.ts (1)
6-7: Code style standardization: Added semicolons for consistency.These changes are purely stylistic, adding semicolons to variable declarations, property declarations, and statement endings. This helps maintain consistent code style throughout the project.
Also applies to: 10-11, 14-15, 19-19, 23-23, 27-27, 31-31, 33-33
src/helpers/utils.ts (1)
76-78: Added regex escape utility function.This function safely escapes special regex characters, which is a useful utility to prevent regex injection issues when constructing dynamic patterns.
tsconfig.json (1)
15-15:Details
✅ Verification successful
Updated Cloudflare Workers types reference.
The version-specific reference to Cloudflare Workers types has been removed, which means the project will now use the version installed in node_modules instead of pinning to a specific API version.
This change could potentially lead to inconsistency if different developers have different versions installed. Please verify:
🏁 Script executed:
#!/bin/bash # Check the version of @cloudflare/workers-types specified in package.json grep -A 2 "@cloudflare/workers-types" package.json || echo "No fixed version found in package.json"Length of output: 191
Cloudflare Workers types are now correctly referenced from node_modules
I've verified that the package.json specifies the dependency for
@cloudflare/workers-typeswith version^4.20250319.0, so the change intsconfig.json(removing the version-specific reference) is in line with using the installed package. This means we're relying on the version defined in package.json, and as long as the lock file is maintained for consistent installations across environments, there shouldn’t be unexpected inconsistencies.src/helpers/linkFixer.ts (3)
1-1: Consistent import quotation style.The import statement has been updated to use single quotes instead of double quotes, which is a good consistency improvement.
38-41: Improved string concatenation readability.The string concatenation has been reformatted to span multiple lines, which improves code readability while maintaining the same functionality.
49-49: Added semicolon for consistency.Adding the semicolon at the end of the function improves code style consistency.
src/realms/bluesky/routes/oembed.ts (5)
4-4: Added centralized branding helper import.Adding the import for the getBranding helper aligns with the project's rebranding effort and centralizes branding logic.
16-16: Centralized branding configuration.Getting branding information from a centralized helper improves maintainability by encapsulating branding logic in one place.
21-23: Updated provider information to use centralized branding.The provider_name and provider_url now use the branding object, which ensures consistent branding across the application.
24-24: Changed OEmbed type from 'link' to 'rich'.Changing the OEmbed type from 'link' to 'rich' allows for more complex embedded content rendering on client platforms.
29-29: Improved response handling with c.json().Replacing c.text(JSON.stringify(data), 200) with c.json(data, 200) is a cleaner approach that automatically sets the correct content-type header and handles JSON serialization.
src/realms/api/routes/oembed.ts (4)
4-5: Added type definition and centralized branding helper.Adding the OEmbed type import improves type safety, and the getBranding helper centralizes branding logic.
17-17: Centralized branding configuration.Getting branding information from a centralized helper improves maintainability by encapsulating branding logic in one place.
22-23: Updated provider information to use centralized branding.The provider_name and provider_url now correctly use the branding object with appropriate fallbacks.
25-25: Changed OEmbed type from 'link' to 'rich'.Changing the OEmbed type from 'link' to 'rich' allows for more complex embedded content rendering on client platforms.
src/helpers/snowcode.ts (2)
1-2: Limited character set for encoding.The character set includes alphanumeric characters and some special characters needed for JSON structure, but be aware that this limits what can be encoded. If future data includes other characters, the encoder will throw an error.
3-17: Encoding function for JSON objects.The encodeSnowcode function successfully translates a JSON object into a numeric representation by:
- Converting the object to a string (removing outer braces)
- Mapping each character to its index in the allowedChars string
- Padding each index to ensure consistent two-digit representation
This approach works well for encoding simple objects for transport or storage in a specific format.
Two considerations:
- The slicing
slice(1, -1)removes the outer braces, which means the decoder must re-add them- Error handling is appropriate for invalid characters
branding.default.json (1)
1-25: Branding zones configuration looks complete, but FxBluesky is missing a faviconThe configuration defines three branding zones with most necessary properties. However, unlike FxTwitter and FixupX zones, the FxBluesky zone is missing a "favicon" property.
Is the missing favicon for FxBluesky intentional? If it's required, consider adding it to maintain consistency across all branding zones.
src/realms/common/version.ts (2)
6-6: LGTM: Simplified function signatureRemoving the provider parameter streamlines the function and eliminates unnecessary complexity.
21-21: LGTM: Using dynamic brandingUsing getBranding(c).name centralizes branding logic and ensures consistent branding across the application.
src/realms/twitter/routes/redirects.ts (3)
6-6: Good addition of the getBranding importThis is a good step toward centralizing branding information retrieval across the application.
18-21: Good handling for invalid twitter:// deep linksThis new condition gracefully handles cases where deep links with the twitter:// scheme are encountered, redirecting users to the web version of the URL. This improves user experience when invalid deep links are processed.
57-57: Nice replacement of static branding with dynamic brandingReplacing the static reference to
Constants.BRANDING_NAMEwith the dynamicgetBranding(c).nameallows the branding to adapt based on the request context, supporting the new centralized branding approach..env.example (1)
1-1: Updated branding name to reflect rebranding effortThe branding name has been updated from "FxTwitter / FixupX" to "FxEmbed", which aligns with the PR's rebranding objectives.
src/providers/twitter/processor.ts (7)
64-67: Good initialization of raw_text structure with facetsThis addition initializes the
apiStatus.raw_textobject with the original text and an empty facets array, providing a structured way to represent rich text information.
124-124: Proper handling of note tweet textGood update to assign the note tweet text to the raw_text.text property when it exists, ensuring consistency in the API response.
138-165: Well-implemented rich text formatting supportThis code adds comprehensive support for rich text formatting (bold, italic, underline, strikethrough) by processing the richtext tags from note tweets and converting them to facets. The approach is thorough and well-structured.
166-173: Good handling of inline media in notesThe addition properly processes inline media references in note tweets, adding them as facets with the appropriate indices, enhancing the richness of the API response.
174-206: Comprehensive entity processing for facetsThis code thoroughly processes various Twitter entities (hashtags, symbols, URLs, user mentions) and adds them as facets with their original text and indices. This provides a complete representation of the text's structured elements.
262-269: Good inclusion of media entities in facetsThe addition of media entities to the facets array provides a complete picture of all elements within the tweet text, including their indices and associated metadata.
421-424: Appropriate sorting of facets by positionSorting the facets by their starting indices ensures that consumers of the API can process them in the correct order when rendering the text, which is essential for proper text reconstruction with formatting.
src/worker.ts (4)
13-13: Good addition of the getBranding importAdding the import for the centralized branding helper function supports the PR's objective of standardizing branding across the application.
99-103: Proper implementation of dynamic branding in error handlingGood replacement of static branding with the dynamic
getBranding(c)function in the error handler, ensuring consistent branding across all error responses.
151-152: Consistent use of dynamic branding in error routesThe update properly uses
getBranding(c)in the /error route, maintaining consistency with the rest of the application.
175-180: Well-implemented fallback error handling with dynamic brandingThe changes in the catch-all error handler correctly use
getBranding(request)to determine the appropriate branding for both timeout and general error HTML templates.src/user.ts (5)
6-6: Use dynamic branding import for flexibility.By importing
getBrandingfromhelpers/branding, you centralize brand-specific logic, which improves future maintainability of theming or white-label solutions.
9-9: Retrieve branding dynamically instead of relying on static constants.Replacing hard-coded references with
getBranding(c)ensures that branding information can be easily updated and reused across multiple entry points.
14-16: Inject dynamic branding into HTML metadata.Using
branding.name,branding.color, and theerrordescription provides a consistent, brand-aligned presentation in social media previews and avoids duplicating constants throughout the code.
60-60: Re-usinggetBrandingin the profile flow.This maintains consistency with the error-handling code, ensuring the same branding is applied to user profiles and error responses.
64-64: Leverage the branding name for output formatting.Passing
branding.nameasbrandingNameremoves the need for any domain-based logic here, further centralizing brand management ingetBranding.src/fetch.ts (5)
5-5: Use the centralizedgenerateSnowflakeutility.Importing
generateSnowflakefromhelpers/utilseliminates duplicate logic, ensuring consistency in how snowflake IDs are generated across the codebase.
173-173: Ensure proper token invalidation logic.The added check
if (!useElongator && cache && c.executionCtx)helps conditionally invalidate cached guest tokens only in the correct contexts, preventing unnecessary deletions or missed purges.
177-177: Close the new invalidation block properly.This bracket finalizes the conditional cache deletion block. If you plan to add more logic within this block, ensure correct scope for local variables.
208-208: Purge token conditionally only with execution context and caching.Validating
c.executionCtx && cacheensures the environment supports asynchronous tasks (Cloudflare Workers), preventing unexpected runtime errors in contexts without available caching or background tasks.
212-212: Encapsulate cache deletion logic.This closing brace properly scopes token deletion to the conditional block. Keeping the block minimal helps avoid accidental scope creep or partial logic spills.
package.json (2)
2-4: Rebrand project and increment major version to 2.0.Renaming to
"fxembed"and updating to"2.0.0"clarifies the new product identity and signals a breaking change to consumers. The new description accurately reflects broader platform support.
38-38: Upgrade wrangler to "^4.2.0".Staying current with Wrangler ensures continued compatibility with newer Cloudflare Workers features, though you should verify any breaking changes in major version updates.
Would you like me to generate a script or direct you to the documentation to confirm whether any migration steps are required?
src/embed/activity.ts (4)
1-16: Module imports and initial setup look solid.You’re configuring i18n (
i18next&icu), reference to essential providers (DataProvider,Bluesky), and loading utility functions. This architecture enables localized embedded content with minimal repetition.
38-73: Comprehensive text formatting ingetStatusText.You handle translations, quotes, and polls thoroughly. Good use of
<blockquote>for quoted content. Keep an eye on large nested HTML strings for potential XSS risks if upstream data is untrusted. Otherwise, looks consistent.Do you have server-side sanitization or robust input validation in upstream code to ensure no malicious HTML injection through quotes or translations?
94-110: Hashtag linking logic mirrors mention approach.Similar to
linkifyMentions, you also deduplicate hashtags inlinkifyHashtags. That fosters consistency in your link transformation. Note that some languages may use different symbols for tags that might require separate handling.
125-204: Flexible text formatting with optional facets.Your fallback approach for external linkification, plus the commented-out facet types, shows readiness for expansions like italic, underline, or mention highlighting. If those styles become needed, re-enable them carefully to prevent lexical scoping issues in the switch statements below.
src/render/video.ts (3)
6-13: Clean implementation of type imports and branding helper.The introduction of proper TypeScript types improves code clarity and type safety, particularly for function parameters and return values. The addition of the getBranding import supports the centralized branding approach.
68-68: Good refactoring using centralized branding.Replacing the conditional expression with
getBranding(properties.context).namecentralizes branding logic, making it more maintainable and consistent across the codebase.
100-100: Removed unnecessary logging.Commenting out the status logging reduces noise in the logs while preserving the code for potential future debugging.
src/render/photo.ts (2)
3-10: Clean implementation of type imports and branding helper.The addition of proper TypeScript types improves code clarity and type safety. The getBranding import supports the centralized branding approach.
40-40: Good refactoring using centralized branding.Replacing hard-coded branding logic with
getBranding(properties.context).namecentralizes branding determination, making it more maintainable and consistent across the codebase.src/realms/bluesky/routes/activity.ts (3)
7-8: Clear function documentation.The comment clearly indicates the purpose of the function, making the code more maintainable.
9-39: Well-implemented request parsing and flag detection.The implementation effectively:
- Extracts parameters from request
- Detects direct media requests through multiple methods (extension, domain, path prefix)
- Identifies special embed types (text-only, gallery, native multi-image)
- Uses detailed comments to explain the logic
The comprehensive URL pattern matching and domain-based detection provide robust handling of various request formats.
41-51: Good error handling for activity responses.The implementation properly:
- Calls handleActivity with appropriate parameters
- Returns the response with status 200 on success
- Returns a 500 error with a descriptive message on failure
The error handling is thorough and provides a fallback for unexpected cases.
src/constants.ts (2)
20-22: Updated Twitter URLs to use x.com domain.The Twitter-related constants have been updated to reflect the platform's rebranding to X.
77-77: Updated user agent to reflect new branding and version.The FRIENDLY_USER_AGENT has been updated to:
- Use "FxEmbedBot" instead of "FxTwitterBot"
- Increment version from 1.0 to 2.0
- Update the crawler URL to fxembed.com
This change properly aligns with the rebranding from FxTwitter to FxEmbed.
src/render/instantview.ts (2)
7-16: Dynamic branding import looks good.
The newly added import statements forgetBrandingand the types from../types/typesare consistent and enable a more flexible, typed approach without introducing any regressions.
391-391: Effective utilization ofgetBranding.
CallinggetBranding(properties.context).namehere cleanly centralizes branding retrieval. The default fallback provided bygetBrandinghandles unexpected contexts gracefully.src/types/types.d.ts (5)
4-5: ImportingContextfrom Hono is appropriate.
Ensure you have the correct version ofhonothat supports this import path.
35-35: Addingcontextfield toRenderProperties.
This addition is helpful for passing request/response context to render functions.
145-148: Newraw_textproperty complements structured text analysis.
Storingraw_textseparately fromtextmaintains backward compatibility and allows advanced formatting or entity handling.
164-171:APIFacetinterface definition is clear.
Defining facets as a distinct interface makes the codebase more maintainable and type-safe for text entity replacement.
242-242: ExpandedOEmbedtype to include'rich'is excellent.
This change ensures compatibility with richer embed formats.src/realms/twitter/routes/status.ts (4)
7-7:InputFlagsimport is appropriate.
This improves clarity and type safety for the flag structure in the status request handler.
146-166: Repeated string literals (“twitter:// redirect” / “normal redirect”).
These lines contain duplicated string literals, which should be replaced with shared constants to improve readability and maintainability.- console.log('twitter:// redirect'); + console.log(TWITTER_REDIRECT_LOG); - console.log('normal redirect'); + console.log(NORMAL_REDIRECT_LOG); // define them once, for example: const TWITTER_REDIRECT_LOG = 'twitter:// redirect'; const NORMAL_REDIRECT_LOG = 'normal redirect';🧰 Tools
🪛 ESLint
[error] 151-151: Define a constant instead of duplicating this literal 4 times.
(sonarjs/no-duplicate-string)
[error] 152-152: Define a constant instead of duplicating this literal 4 times.
(sonarjs/no-duplicate-string)
[error] 155-155: Define a constant instead of duplicating this literal 4 times.
(sonarjs/no-duplicate-string)
🪛 GitHub Check: ESLint
[failure] 151-151: String literals should not be duplicated
Define a constant instead of duplicating this literal 4 times.
[failure] 152-152: String literals should not be duplicated
Define a constant instead of duplicating this literal 4 times.
[failure] 155-155: String literals should not be duplicated
Define a constant instead of duplicating this literal 4 times.
181-197: Repeated string literals (“twitter:// redirect” / “normal redirect”).
This is the same duplication issue identified above, recurs in these lines. Pull the strings into constants to reduce repetition.
199-205: Repeated string literals (“twitter:// redirect” / “normal redirect”).
Again, these lines repeat the same log messages. Centralizing them in constants keeps the code DRY.src/realms/twitter/routes/profile.ts (3)
5-6: Good use of experiment-based imports.
These imports align well with the new gating approach in your experiments and the branding helper. No issues spotted.
30-30: Ensure the dynamic redirect URL is valid.
Switching togetBranding(c).redirectis consistent with rebranding, but confirm that the returned URL is always properly defined and valid to avoid potential redirection errors.
64-74: Verify external content safety.
Fetching raw HTML fromhttps://app.fxembed.comand returning it might open a window for XSS if that domain is ever compromised. Consider sanitizing or verifying the fetched HTML before rendering.src/experiments.ts (3)
8-10: New experiment enum entries look consistent.
Adding these experiment enums is straightforward and doesn’t appear to break existing functionality.
54-59: ACTIVITY_EMBED experiment configuration.
The new configuration here is correct. With a 100% roll-out, confirm you want it always enabled.
60-63: USE_TRAFFIC_CONTROL experiment configuration.
Defines the experiment for traffic control with a 0% initial rollout. Looks sensible for gradual enablement and testing.src/realms/twitter/routes/activity.ts (8)
1-7: Imports are consistent with established patterns.
No issues in these new imports; they match the existing conventions in the codebase.
8-9: Clear function documentation.
Providing a descriptive comment above the handler clarifies its purpose, aiding maintainability.🧰 Tools
🪛 GitHub Check: ESLint
[warning] 9-9: Cognitive Complexity of functions should not be too high
Refactor this function to reduce its Cognitive Complexity from 22 to the 20 allowed.
9-9: Duplicate comment: Reduce cognitive complexity.
This function’s reported Cognitive Complexity is 22, which exceeds the threshold of 20. Consider refactoring into smaller functions for clarity and maintainability.🧰 Tools
🪛 GitHub Check: ESLint
[warning] 9-9: Cognitive Complexity of functions should not be too high
Refactor this function to reduce its Cognitive Complexity from 22 to the 20 allowed.
10-13: Parameter parsing logic looks fine.
Extracting the prefix and ID from request parameters is straightforward and valid.
43-61: Optional chaining caution at line 56 (static analysis).
Static analysis suggests using optional chaining, buturl.pathnameshould never be undefined. This may be a false positive unlesspathnamecan be missing in certain edge cases.🧰 Tools
🪛 Biome (1.9.4)
[error] 56-56: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
63-71: Verify the isXDomain logic.
Currently, if the URL contains “twitt,”flags.isXDomainis set tofalse; if it contains “x,” it’strue. Confirm this inversion matches your branding domain expectations.
72-78: Cache control header usage.
Applyingmax-age=0whenbaseUrldiffers fromConstants.TWITTER_ROOTfollows the existing pattern for custom redirects. No issues found.
79-88: Return the JSON activity response.
Returning the activity response with status code 200 is correct. Good job ensuring standard success flow.src/realms/bluesky/router.ts (4)
9-10: No issues with the newly introduced imports.
They correctly provide theactivityRequesthandler andgetBrandinghelper from their respective modules.
16-16: Ensure new endpoint is tested.
The newGET /api/v1/statuses/:snowcoderoute looks good. Please confirm it’s covered by tests (valid and invalid:snowcodeparameters).
22-22: Consistent version route update.
Removing theDataProvider.Bskyargument simplifies the signature, in line with the pattern for other routers.
24-24: Dynamic redirect is a good step.
Switching from a fixed URL togetBranding(c).redirectsupports more flexible branding. Ensure the fallback domain is well-defined ingetBranding.src/realms/twitter/router.ts (4)
13-14: Imports reflect the new branding and activity handling.
They align with recent changes in other realms.
53-53: Expanded Twitter route for status activities.
This addition is consistent with the Bluesky realm. Confirm you have appropriate test coverage.
86-86: Version route signature updated successfully.
This mirrors the change in the Bluesky router by removing theDataProviderargument.
106-106: Unified redirect handling.
UsinggetBranding(c).redirectmaintains a consistent, dynamic redirect strategy.src/embed/status.ts (13)
18-29: New imports for Snowcode and typed interfaces.
The additions—encodeSnowcodeand the extended type definitions—look well-structured and consistent with the existing codebase.
32-38: Leverage branding in returnError.
UsinggetBrandingto populate the error response ensures consistent naming across the app.
151-167: Conditional activity embedding feature.
EnablinguseActivityuponexperimentCheckis clear. The code properly disables the feature if no media is available.
346-346: Passingcontextto renderPhoto.
This aligns with other rendering changes. No issues spotted.
370-375: Extended arguments in renderVideo call.
AddingtextandisOverrideMediaclarifies the override context. This helps unify the rendering logic.
394-394: Consistent structure for video rendering.
Includingtextmaintains output parity with the override approach.
418-418: Passingcontextfor mosaic rendering.
Ensures uniform data is available in the rendering pipeline.
431-431: Matching context usage in photo rendering.
No logical issues. Keeps the code consistent.
445-445: Consistent approach to pass context.
No problems. Straightforward injection ofcontext: c.
597-600: Dynamic branding in GIF label.
UsinggetBrandinginsidei18next.t('gifIndicator')fosters consistent branding.
610-620: Activity embed toggle introduced.
The feature detection ensures only relevant requests serve the new embed logic. Adding the custom icon link is a creative approach, but confirm the domain is correct and stable.
626-626: canary subdomain dynamically references brand domains.
EnsuregetBranding(c).domains[0]is available and correct.
639-664:Details
❓ Verification inconclusive
Embedding ActivityPub-like data.
Building anActivity+JSONlink with a custom snowcode approach is innovative. Confirm that arrays likeConstants.STANDARD_BSKY_DOMAIN_LISTare never empty. Possibly add fallback logic to avoid runtime errors.
Below is a shell script to search for the constant definitions in the codebase. This will help verify that the arrays (
STANDARD_BSKY_DOMAIN_LISTandSTANDARD_DOMAIN_LIST) are defined and populated, ensuring that accessing their first element won’t cause runtime errors. You can run this script from the repository root:Please review the output to confirm that both arrays are non-empty. If there’s any risk of them being empty, consider adding fallback logic as suggested in the review comment.
🏁 Script executed:
#!/bin/bash echo "Searching for definitions of the activity constants..." echo "----- STANDARD_BSKY_DOMAIN_LIST -----" rg -n "export const STANDARD_BSKY_DOMAIN_LIST" . echo "----- STANDARD_DOMAIN_LIST -----" rg -n "export const STANDARD_DOMAIN_LIST" .Length of output: 497
Verify non-empty constants for ActivityPub link generation
The current implementation of the custom snowcode approach is innovative. However, to prevent potential runtime errors, please confirm that the arraysConstants.STANDARD_BSKY_DOMAIN_LISTandConstants.STANDARD_DOMAIN_LISTare always defined and non-empty. If there’s any chance they could be empty, consider adding fallback logic. For a more robust verification, please manually confirm these arrays’ definitions in the codebase or update them to include safe defaults.
- File:
src/embed/status.ts(Lines 639–664)- Concern: Ensure that accessing
[0]on the arrays will not lead to runtime errors if the arrays are empty.README.md (7)
1-5: The rebranding looks good!The switch from "FxTwitter" to "FxEmbed" provides a clear identity that encompasses all your embedding capabilities (FxTwitter, FixupX, and FxBluesky) under one umbrella brand.
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
1-1: Images should have alternate text (alt text)
null(MD045, no-alt-text)
18-23: Consistent repository links updated correctly.All the repository links have been properly updated to reflect the new organization and repository name.
31-35: Clear domain-specific instructions.The instructions are now more organized with separate sections for each domain type, making it easier for users to understand how to use the service.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~31-~31: Loose punctuation mark.
Context: ...ith-privacy-in-mind). ###twitter.com: Addfxbefore yourtwitter.comlink...(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~33-~33: Loose punctuation mark.
Context: ...ore yourtwitter.comlink ###x.com: Addfixupbefore yourx.comlink #...(UNLIKELY_OPENING_PUNCTUATION)
[uncategorized] ~35-~35: Loose punctuation mark.
Context: ...before yourx.comlink ###bsky.app: Addfxbefore yourbsky.applink #...(UNLIKELY_OPENING_PUNCTUATION)
37-44: Enhanced embedding description.The description now better explains the video and GIF embedding capabilities, including the valuable feature of automatic embedding for videos from other platforms.
🧰 Tools
🪛 markdownlint-cli2 (0.17.2)
41-41: Images should have alternate text (alt text)
null(MD045, no-alt-text)
75-82: Examples updated to match new branding.The direct media link examples have been updated to consistently use the new domain names.
134-156: Updated feature comparison table.The table now correctly presents "FxTwitter / FixupX" as a combined entity, which is consistent with the rebranding strategy.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~134-~134: Possible missing comma found.
Context: ...Embed? Let's compare using FxTwitter / FixupX since it's the most feature-complete. H...(AI_HYDRA_LEO_MISSING_COMMA)
🪛 markdownlint-cli2 (0.17.2)
155-155: Images should have alternate text (alt text)
null(MD045, no-alt-text)
155-155: Images should have alternate text (alt text)
null(MD045, no-alt-text)
214-219: Star history chart updated correctly.All references in the star history section have been updated to point to the new repository.
src/types/vendor/twitter.d.ts (3)
344-347: Improved type safety for entity properties.Replacing
unknown[]with specific types (MentionEntity[],TagEntity[]) improves type safety and makes the code more maintainable.
354-369: Well-structured entity type definitions.The new type definitions (
TagEntity,MentionEntity, andInlineMedia) are well structured and provide clear type information for Twitter's API entities.
430-437: Consistent application of new types in note_tweet_results.The changes to
note_tweet_resultscorrectly apply the newly defined entity types, ensuring consistency across the type definitions.
| export const decodeSnowcode = (numStr: string) => { | ||
| const str = numStr.match(/\d+/)?.join('') ?? ''; | ||
| console.log('original str', str); | ||
| if (str.length % 2 !== 0) { | ||
| throw new Error('Invalid encoded string length.'); | ||
| } | ||
| let result = ''; | ||
| for (let i = 0; i < str.length; i += 2) { | ||
| const codeStr = str.slice(i, i + 2); | ||
| const index = parseInt(codeStr, 10); | ||
| if (index < 0 || index >= allowedChars.length) { | ||
| throw new Error('Invalid code: ' + codeStr); | ||
| } | ||
| result += allowedChars[index]; | ||
| } | ||
| const resultStr = `{${result}}`; | ||
| console.log('str', resultStr); | ||
| return JSON.parse(resultStr); | ||
| }; |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Decoding function with adequate error handling.
The decodeSnowcode function properly handles:
- Extracting numeric portions from the input string
- Validating that the length is even (since each character is encoded as two digits)
- Mapping pairs of digits back to their original characters
- Reconstructing the complete JSON by adding back the braces
However, there are two issues:
- There's debugging information being logged to the console that should be removed or wrapped in a conditional debug flag:
- console.log('original str', str);and
- console.log('str', resultStr);- The regular expression in line 20 could reject valid input if it contains non-numeric characters. The current implementation extracts only digits and ignores other characters, which could lead to unexpected behavior.
Consider this improved implementation that removes console logs and handles input validation better:
export const decodeSnowcode = (numStr: string) => {
- const str = numStr.match(/\d+/)?.join('') ?? '';
- console.log('original str', str);
+ // Ensure input only contains digits
+ if (!/^\d+$/.test(numStr)) {
+ throw new Error('Invalid input: input must contain only digits');
+ }
+ const str = numStr;
if (str.length % 2 !== 0) {
throw new Error('Invalid encoded string length.');
}
let result = '';
for (let i = 0; i < str.length; i += 2) {
const codeStr = str.slice(i, i + 2);
const index = parseInt(codeStr, 10);
if (index < 0 || index >= allowedChars.length) {
throw new Error('Invalid code: ' + codeStr);
}
result += allowedChars[index];
}
const resultStr = `{${result}}`;
- console.log('str', resultStr);
return JSON.parse(resultStr);
};📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const decodeSnowcode = (numStr: string) => { | |
| const str = numStr.match(/\d+/)?.join('') ?? ''; | |
| console.log('original str', str); | |
| if (str.length % 2 !== 0) { | |
| throw new Error('Invalid encoded string length.'); | |
| } | |
| let result = ''; | |
| for (let i = 0; i < str.length; i += 2) { | |
| const codeStr = str.slice(i, i + 2); | |
| const index = parseInt(codeStr, 10); | |
| if (index < 0 || index >= allowedChars.length) { | |
| throw new Error('Invalid code: ' + codeStr); | |
| } | |
| result += allowedChars[index]; | |
| } | |
| const resultStr = `{${result}}`; | |
| console.log('str', resultStr); | |
| return JSON.parse(resultStr); | |
| }; | |
| export const decodeSnowcode = (numStr: string) => { | |
| // Ensure input only contains digits | |
| if (!/^\d+$/.test(numStr)) { | |
| throw new Error('Invalid input: input must contain only digits'); | |
| } | |
| const str = numStr; | |
| if (str.length % 2 !== 0) { | |
| throw new Error('Invalid encoded string length.'); | |
| } | |
| let result = ''; | |
| for (let i = 0; i < str.length; i += 2) { | |
| const codeStr = str.slice(i, i + 2); | |
| const index = parseInt(codeStr, 10); | |
| if (index < 0 || index >= allowedChars.length) { | |
| throw new Error('Invalid code: ' + codeStr); | |
| } | |
| result += allowedChars[index]; | |
| } | |
| const resultStr = `{${result}}`; | |
| return JSON.parse(resultStr); | |
| }; |
| @@ -0,0 +1,25 @@ | |||
| import { Context } from 'hono/dist/types/context'; | |||
| import branding from '../../branding.json'; | |||
There was a problem hiding this comment.
Fix import path to resolve branding.json
The pipeline is failing to resolve the branding.json file from the specified path.
-import branding from '../../branding.json';
+import branding from '../../branding.default.json';The file is named "branding.default.json" in the repository, but you're importing it as "branding.json". This mismatch is causing the build failure.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import branding from '../../branding.json'; | |
| import branding from '../../branding.default.json'; |
🧰 Tools
🪛 GitHub Actions: Build
[error] 2-2: ERROR: Could not resolve '../../branding.json'
🪛 GitHub Actions: Tests
[error] 2-2: Build failed: Could not resolve '../../branding.json'.
There was a problem hiding this comment.
If branding.json doesn't exist, like in a CI environment, it is copied by the esbuild script. branding.json is not committed to the repo but it is required to be filled in.
There was a problem hiding this comment.
@dangeredwolf I understand now - thanks for the explanation! This is a common pattern for configuration files where you have a default template committed to the repo while the actual instance-specific file is generated at build time.
Looking at the esbuild script changes, I can see the logic that copies branding.default.json to branding.json when needed, and the .gitignore confirms that branding.json is intentionally not committed. Your approach is correct here.
✏️ Learnings added
Learnt from: dangeredwolf
PR: FxEmbed/FxEmbed#1203
File: src/helpers/branding.ts:2-2
Timestamp: 2025-03-20T22:06:36.856Z
Learning: In the FxEmbed codebase, branding.json is not committed to the repository but is generated at build time by copying from branding.default.json. The import statements correctly reference branding.json as that's the file that will exist at runtime.
Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.
| if (experimentCheck(Experiment.USE_TRAFFIC_CONTROL)) { | ||
| const app = await fetch(`https://app.fxembed.com/profile/${handle}/post/${actualId}`); | ||
| const appBody = await app.text(); | ||
| if (appBody.includes('<!doctype html>')) { | ||
| return c.html(appBody, 200); | ||
| } else { | ||
| return c.redirect(url, 302); | ||
| } | ||
| } else { | ||
| return c.redirect(url, 302); | ||
| } |
There was a problem hiding this comment.
🛠️ Refactor suggestion
Add error handling for fetch operation in traffic control experiment
The current implementation doesn't handle potential fetch failures.
if (experimentCheck(Experiment.USE_TRAFFIC_CONTROL)) {
- const app = await fetch(`https://app.fxembed.com/profile/${handle}/post/${actualId}`);
- const appBody = await app.text();
- if (appBody.includes('<!doctype html>')) {
- return c.html(appBody, 200);
- } else {
+ try {
+ const app = await fetch(`https://app.fxembed.com/profile/${handle}/post/${actualId}`);
+ if (!app.ok) {
+ console.warn(`Traffic control fetch failed with status ${app.status}`);
+ return c.redirect(url, 302);
+ }
+ const appBody = await app.text();
+ if (appBody.includes('<!doctype html>')) {
+ return c.html(appBody, 200);
+ } else {
+ return c.redirect(url, 302);
+ }
+ } catch (error) {
+ console.error('Traffic control fetch failed:', error);
return c.redirect(url, 302);
}
} else {This change adds proper error handling for network failures and non-OK responses, ensuring your application gracefully degrades when the external service is unavailable.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (experimentCheck(Experiment.USE_TRAFFIC_CONTROL)) { | |
| const app = await fetch(`https://app.fxembed.com/profile/${handle}/post/${actualId}`); | |
| const appBody = await app.text(); | |
| if (appBody.includes('<!doctype html>')) { | |
| return c.html(appBody, 200); | |
| } else { | |
| return c.redirect(url, 302); | |
| } | |
| } else { | |
| return c.redirect(url, 302); | |
| } | |
| if (experimentCheck(Experiment.USE_TRAFFIC_CONTROL)) { | |
| try { | |
| const app = await fetch(`https://app.fxembed.com/profile/${handle}/post/${actualId}`); | |
| if (!app.ok) { | |
| console.warn(`Traffic control fetch failed with status ${app.status}`); | |
| return c.redirect(url, 302); | |
| } | |
| const appBody = await app.text(); | |
| if (appBody.includes('<!doctype html>')) { | |
| return c.html(appBody, 200); | |
| } else { | |
| return c.redirect(url, 302); | |
| } | |
| } catch (error) { | |
| console.error('Traffic control fetch failed:', error); | |
| return c.redirect(url, 302); | |
| } | |
| } else { | |
| return c.redirect(url, 302); | |
| } |
…e slash directives in favor of ES6-style import declarations Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
There was a problem hiding this comment.
Actionable comments posted: 2
♻️ Duplicate comments (1)
src/helpers/branding.ts (1)
2-2:⚠️ Potential issueFix import path to resolve branding.json
The pipeline is failing to resolve the branding.json file from the specified path.
-import branding from '../../branding.json'; +import branding from '../../branding.default.json';The file is named "branding.default.json" in the repository, but you're importing it as "branding.json". This mismatch is causing the build failure.
🧹 Nitpick comments (7)
src/helpers/branding.ts (1)
14-25: Consider logging errors in the catch blockThe implementation of
getBrandingis solid, but there's room for improvement in error handling.Two issues to address:
- The unused variable warning from ESLint
- Silent error handling could hide issues
Consider this refactored version:
export const getBranding = (c: Context | Request): Branding => { const zones = branding.zones as Branding[]; const defaultBranding = zones.find(zone => zone.default) ?? zones[0]; try { const url = new URL(c instanceof Request ? c.url : c.req.url); // get domain name, without subdomains const domain = url.hostname.split('.').slice(-2).join('.'); return zones.find(zone => zone.domains.includes(domain)) ?? defaultBranding; - } catch (_e) { + } catch (error) { + console.error('Error parsing URL for branding:', error); return defaultBranding; } };This change eliminates the ESLint warning and adds helpful logging for debugging potential issues.
🧰 Tools
🪛 ESLint
[error] 22-22: '_e' is defined but never used.
(@typescript-eslint/no-unused-vars)
🪛 GitHub Check: ESLint
[failure] 22-22: Disallow unused variables
'_e' is defined but never used.src/embed/activity.ts (4)
17-36: Validate poll data before rendering.
Ifpollor any of its properties are null or undefined, this function might output incorrect HTML or throw errors. Consider adding sanity checks to handle unexpected or malformed poll data.+ if (!poll || !poll.choices) { + return '<blockquote>No poll data available.</blockquote>'; + } poll.choices.forEach(choice => { ...
38-73: Avoid console.log in production code.
Repeated usage ofconsole.log(lines 42, 57) can clutter logs in production environments. Consider replacing these statements with a dedicated logging mechanism or removing them altogether.
112-123: Check compatibility of negative lookbehind in regex.
Some older browsers and environments do not support the(?<!...)negative lookbehind syntax. If broad compatibility is a requirement, consider an alternative approach to ensure correct link wrapping.
125-204: Reduce complexity in facet processing.
This function contains code paths for both default linkification and an optional “facets” parsing block, with significant commented-out branches. Consider extracting facet logic into a helper function or removing unused code to keep the function more maintainable.src/realms/twitter/routes/activity.ts (2)
10-10: Consider refactoring to reduce cognitive complexity.
The functionactivityRequestcan be broken down into smaller helper functions, improving readability and maintainability.// Example structural approach: async function activityRequest(c: Context) { // parseParams(c, flags) // handleMediaFlags(c, flags) // runMainFlow(c, flags) ... }
57-57: Use optional chaining for clarity.
Instead ofmatched && matched[1], consider using optional chaining to simplify the logic and reduce nesting.- const matched = url.pathname.match(/\/status(?:es)?\/.+:([^:]+?)$/); - const nameFromUrl = matched && matched[1]; + const nameFromUrl = url.pathname.match(/\/status(?:es)?\/.+:([^:]+?)$/)?.[1];🧰 Tools
🪛 Biome (1.9.4)
[error] 57-57: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (25)
src/embed/activity.ts(1 hunks)src/helpers/branding.ts(1 hunks)src/helpers/card.ts(1 hunks)src/helpers/media.ts(1 hunks)src/helpers/mosaic.ts(1 hunks)src/helpers/quote.ts(1 hunks)src/helpers/socialproof.ts(1 hunks)src/providers/bsky/conversation.ts(1 hunks)src/providers/bsky/processor.ts(4 hunks)src/providers/twitter/conversation.ts(1 hunks)src/providers/twitter/processor.ts(8 hunks)src/providers/twitter/profile.ts(1 hunks)src/realms/api/routes/twitter.ts(1 hunks)src/realms/bluesky/router.ts(1 hunks)src/realms/bluesky/routes/activity.ts(1 hunks)src/realms/bluesky/routes/oembed.ts(2 hunks)src/realms/bluesky/routes/status.ts(2 hunks)src/realms/twitter/router.ts(4 hunks)src/realms/twitter/routes/activity.ts(1 hunks)src/realms/twitter/routes/profile.ts(4 hunks)src/types/types.d.ts(7 hunks)src/types/vendor/bsky.d.ts(9 hunks)src/user.ts(2 hunks)test/worker.test.ts(3 hunks)tsconfig.json(1 hunks)
✅ Files skipped from review due to trivial changes (2)
- src/helpers/card.ts
- src/providers/bsky/conversation.ts
🚧 Files skipped from review as they are similar to previous changes (9)
- src/realms/bluesky/routes/oembed.ts
- src/providers/bsky/processor.ts
- src/realms/bluesky/routes/status.ts
- src/realms/bluesky/routes/activity.ts
- src/realms/twitter/routes/profile.ts
- src/providers/twitter/processor.ts
- tsconfig.json
- test/worker.test.ts
- src/types/vendor/bsky.d.ts
🧰 Additional context used
🧬 Code Definitions (5)
src/user.ts (3)
src/embed/status.ts (1) (1)
returnError(31-43)src/helpers/branding.ts (1) (1)
getBranding(14-25)src/strings.ts (1) (1)
Strings(18-264)
src/embed/activity.ts (7)
src/helpers/socialproof.ts (1) (1)
getSocialProof(6-33)src/embed/status.ts (2) (2)
DataProvider(678-678)returnError(31-43)src/helpers/utils.ts (1) (1)
escapeRegex(76-78)src/helpers/snowcode.ts (1) (1)
decodeSnowcode(19-37)src/providers/twitter/conversation.ts (1) (1)
constructTwitterThread(311-577)src/providers/bsky/conversation.ts (1) (1)
constructBlueskyThread(58-134)src/experiments.ts (1) (1)
experimentCheck(67-72)
src/realms/twitter/router.ts (5)
src/helpers/branding.ts (1) (1)
getBranding(14-25)src/realms/twitter/routes/status.ts (1) (1)
statusRequest(10-208)src/realms/twitter/routes/profile.ts (1) (1)
profileRequest(10-96)src/realms/twitter/routes/activity.ts (1) (1)
activityRequest(10-93)src/realms/common/version.ts (1) (1)
versionRoute(6-24)
src/types/types.d.ts (1)
src/embed/status.ts (1) (1)
DataProvider(678-678)
src/realms/bluesky/router.ts (4)
src/realms/bluesky/routes/activity.ts (1) (1)
activityRequest(9-53)src/realms/bluesky/routes/redirects.ts (1) (1)
genericBlueskyRedirect(4-7)src/realms/common/version.ts (1) (1)
versionRoute(6-24)src/helpers/branding.ts (1) (1)
getBranding(14-25)
🪛 Biome (1.9.4)
src/embed/activity.ts
[error] 324-326: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 345-346: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
[error] 348-348: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
src/realms/twitter/routes/activity.ts
[error] 57-57: Change to an optional chain.
Unsafe fix: Change to an optional chain.
(lint/complexity/useOptionalChain)
🪛 GitHub Check: ESLint
src/embed/activity.ts
[failure] 346-346: Disallow lexical declarations in case clauses
Unexpected lexical declaration in case block.
src/helpers/branding.ts
[failure] 22-22: Disallow unused variables
'_e' is defined but never used.
🪛 ESLint
src/realms/twitter/router.ts
[error] 42-42: 'e' is defined but never used.
(@typescript-eslint/no-unused-vars)
src/helpers/branding.ts
[error] 22-22: '_e' is defined but never used.
(@typescript-eslint/no-unused-vars)
🔇 Additional comments (30)
src/helpers/media.ts (2)
2-2: Good addition of explicit type imports.This change properly imports the
APIPhotoandAPIVideotypes from the types module, enabling proper type checking for theprocessMediafunction's return type.
5-5: Great type safety improvement.Adding the explicit return type
APIPhoto | APIVideo | nullto the function signature makes the code more self-documenting and ensures proper type checking.src/helpers/quote.ts (2)
2-2: Good type system enhancement.Properly importing the
APIStatustype will ensure proper type checking for the function parameters.
5-5: Enhanced type safety for thehandleQuotefunction.Adding an explicit type for the
quoteparameter improves code readability and helps catch type-related bugs during development.src/helpers/mosaic.ts (1)
3-3: Good addition of missing type imports.This change properly imports the
APIPhotoandAPIMosaicPhototypes that were already being used in the function signature, ensuring proper type checking.src/helpers/socialproof.ts (1)
2-2: Good addition of missing type imports.This change properly imports the
APIStatusandAPITwitterStatustypes that were already being used in the function signatures, ensuring proper type checking.src/providers/twitter/conversation.ts (1)
8-8: Improved type safety with explicit importsAdding explicit imports for types that are used in the file enhances code clarity and maintainability. These types are correctly used throughout the file, and making them explicit helps in better understanding the data flow.
src/realms/api/routes/twitter.ts (1)
5-5: Simplified import path for ContextGood change to use the more canonical import path for the Context type from Hono. This simplifies imports and follows better coding practices.
src/providers/twitter/profile.ts (1)
5-5: Improved type declarations with explicit importsAdding explicit imports for
APIUserandUserAPIResponsetypes enhances code clarity. These types are appropriately used as return types in the functions within this file.src/helpers/branding.ts (1)
4-12: Well-structured type definition for brandingThe
Brandingtype is well-defined with clear required and optional properties. This provides good type safety for the branding configuration throughout the application.src/embed/activity.ts (3)
75-92: Confirm underscore and special character support for mentions.
The regex currently matches@([\w.]+), which excludes underscores in certain positions. Verify that Twitter/Bluesky handles underscores in user handles differently or confirm that underscores are consistently allowed.
94-110: Confirm underscore and multi-language support for hashtags.
Similar to mentions, the regex for hashtags (#([\w.]+)) might not capture certain characters (e.g., underscores, accented letters). Consider verifying support for hashtags in other languages or with special characters.
356-363: Handle empty or undefinedConstants.API_HOST_LIST.
IfConstants.API_HOST_LISTis empty, line 362 could attempt to reference[0]and produce a runtime error. Ensure that the array has at least one element before indexing.src/user.ts (3)
6-7: Dynamic branding import looks good.
The addition ofgetBrandingensures that branding logic is consolidated. This approach promotes maintainability and reduces hardcoding.Also applies to: 10-10
15-17: Great use of a theme color meta tag.
Including<meta property="theme-color">in the error response provides a more cohesive branded experience across supported browsers and devices.
61-61: Consistent reuse ofgetBranding.
ReferencinggetBrandingagain for profile handling ensures consistency with the error response approach. Centralizing branding retrieval is an excellent pattern for maintainability.Also applies to: 65-65
src/realms/bluesky/router.ts (4)
7-8: Appropriate imports for the new features.The new imports support the activity embedding functionality and dynamic branding that's being implemented across the application.
14-14: Added endpoint for activity embedding support.This new route adds support for the FxEmbed 2.0 functionality by handling requests for statuses identified by a snowcode.
20-20: Simplified versioning route.The
DataProvider.Bskyparameter has been removed from theversionRoutecall, aligning with changes in the common version implementation that now handles provider context internally.
22-22: Dynamic redirection based on branding.Replacing the static redirect URL with a dynamic one from
getBranding(c).redirectimproves flexibility and supports the multi-platform branding strategy.src/types/types.d.ts (6)
4-5: Added necessary type imports.These imports provide the required types for the FxEmbed functionality, enhancing type safety across the application.
8-20: Well-defined InputFlags type.This comprehensive set of optional boolean properties provides clear typing for various embedding and display options, making the code more maintainable.
37-37: Added context to RenderProperties.Including the Hono Context in RenderProperties enables access to request information during rendering, supporting the dynamic branding functionality.
147-150: Added raw_text support to APIStatus.This addition enables rich text formatting with facets, enhancing the embedding capabilities to support more complex content rendering.
166-173: New APIFacet interface for rich text support.This interface provides a structured way to represent rich text elements like links, mentions, and other formatted content within embeds.
244-244: Expanded OEmbed type options.Adding 'rich' as a possible value for the OEmbed type property enables more comprehensive embedding capabilities beyond simple links.
src/realms/twitter/router.ts (4)
12-13: Added imports for activity embedding and branding.These imports enable the activity embedding functionality and dynamic branding features being implemented across the application.
52-52: Added endpoint for activity embedding support.This new route adds support for the FxEmbed 2.0 functionality by handling requests for statuses identified by their ID.
85-85: Simplified versioning route.The
DataProvider.Twitterparameter has been removed from theversionRoutecall, aligning with changes in the common version implementation that now handles provider context internally.
105-105: Dynamic redirection based on branding.Replacing the static redirect URL with a dynamic one from
getBranding(c).redirectimproves flexibility and supports the multi-platform branding strategy.
| const image = media as APIPhoto; | ||
| return { | ||
| id: '114163769487684704', |
There was a problem hiding this comment.
Wrap lexical declarations in case clauses to avoid unexpected scope issues.
Declaring const image and const video directly in the case statements can leak variables across cases. Wrap these in blocks to prevent potential runtime errors and resolve lint warnings.
case 'photo': {
- const image = media as APIPhoto;
+ {
+ const image = media as APIPhoto;
return {
...
};
}
}
case 'video':
case 'gif': {
- const video = media as APIVideo;
+ {
+ const video = media as APIVideo;
...
if (video.width > 1920 || video.height > 1920) {
...
}
return { ... };
}
}Also applies to: 345-346, 348-348
🧰 Tools
🪛 Biome (1.9.4)
[error] 324-326: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.
The declaration is defined in this switch clause:
Unsafe fix: Wrap the declaration in a block.
(lint/correctness/noSwitchDeclarations)
| export const faviconRoute = async (c: Context) => { | ||
| const branding = getBranding(c); | ||
| try { | ||
| const url = new URL(c.req.url); | ||
| let faviconUrl = 'https://abs.twimg.com/favicons/twitter.3.ico'; | ||
| if (url.hostname.includes('twitt')) { | ||
| faviconUrl = 'https://abs.twimg.com/favicons/twitter.2.ico'; | ||
| } | ||
| const response = await fetch(faviconUrl); | ||
| const response = await fetch(branding.favicon); | ||
| const body = await response.arrayBuffer(); | ||
| return c.body(body, response.status as ContentfulStatusCode, { | ||
| 'Content-Type': response.headers.get('Content-Type') || 'image/x-icon', | ||
| 'Content-Length': response.headers.get('Content-Length') || body.byteLength.toString(), | ||
| },); | ||
| 'Content-Length': response.headers.get('Content-Length') || body.byteLength.toString() | ||
| }); | ||
| } catch (e) { | ||
| return c.redirect('https://abs.twimg.com/favicons/twitter.3.ico', 302); | ||
| return c.redirect(branding.favicon, 302); | ||
| } | ||
| } | ||
| }; |
There was a problem hiding this comment.
Refactored favicon handling to use branding helper.
The faviconRoute now uses the centralized branding system instead of hardcoded values, improving consistency across different domains.
There's an unused variable 'e' in the catch block (line 42). Consider either using it for error logging or removing the variable name:
- } catch (e) {
+ } catch (_) {📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| export const faviconRoute = async (c: Context) => { | |
| const branding = getBranding(c); | |
| try { | |
| const url = new URL(c.req.url); | |
| let faviconUrl = 'https://abs.twimg.com/favicons/twitter.3.ico'; | |
| if (url.hostname.includes('twitt')) { | |
| faviconUrl = 'https://abs.twimg.com/favicons/twitter.2.ico'; | |
| } | |
| const response = await fetch(faviconUrl); | |
| const response = await fetch(branding.favicon); | |
| const body = await response.arrayBuffer(); | |
| return c.body(body, response.status as ContentfulStatusCode, { | |
| 'Content-Type': response.headers.get('Content-Type') || 'image/x-icon', | |
| 'Content-Length': response.headers.get('Content-Length') || body.byteLength.toString(), | |
| },); | |
| 'Content-Length': response.headers.get('Content-Length') || body.byteLength.toString() | |
| }); | |
| } catch (e) { | |
| return c.redirect('https://abs.twimg.com/favicons/twitter.3.ico', 302); | |
| return c.redirect(branding.favicon, 302); | |
| } | |
| } | |
| }; | |
| export const faviconRoute = async (c: Context) => { | |
| const branding = getBranding(c); | |
| try { | |
| const response = await fetch(branding.favicon); | |
| const body = await response.arrayBuffer(); | |
| return c.body(body, response.status as ContentfulStatusCode, { | |
| 'Content-Type': response.headers.get('Content-Type') || 'image/x-icon', | |
| 'Content-Length': response.headers.get('Content-Length') || body.byteLength.toString() | |
| }); | |
| } catch (_) { | |
| return c.redirect(branding.favicon, 302); | |
| } | |
| }; |
🧰 Tools
🪛 ESLint
[error] 42-42: 'e' is defined but never used.
(@typescript-eslint/no-unused-vars)
Summary by CodeRabbit
Rebranding
New Features
Improvements