Repository navigation
feat(bot): apply buildTrackEmbed to music command responses - #507
Conversation
- buildTrackEmbed: general-purpose track display with source detection - buildUserProfileEmbed: user stat snapshot with progress bars - buildListPageEmbed: paginated list helper with field-per-item layout - buildPlatformAttribEmbed: external service branding (Last.fm, Spotify, YouTube) All helpers include comprehensive unit tests covering edge cases and variants.
Fixes critical SSRF in axios (GHSA-3p68-rc4w-qgx5) and moderate CVEs in hono/hono-node-server. npm audit --audit-level=high now clean.
- Updated /songinfo to use buildTrackEmbed with 'playing' kind - Enhanced /skip, /pause, /resume to show next/current track with rich embed - Added createMusicControlButtons to /queue show response - Exported TrackData type and trackToData helper from responseEmbeds - Updated queueEmbed.spec.ts to mock createMusicControlButtons
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 3 minutes and 8 seconds. ⌛ 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. ℹ️ Review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (10)
📝 WalkthroughWalkthroughA new utility module Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/bot/src/functions/music/commands/resume.ts (1)
15-18:⚠️ Potential issue | 🟡 MinorMissing
requireVoiceChannelvalidation.The
pausecommand validates that the user is in a voice channel before proceeding (requireVoiceChannel), butresumedoes not. This inconsistency could allow users to resume playback without being in the voice channel.As per coding guidelines: "Use existing validators from
packages/bot/src/utils/command/for voice channel, queue, and guild validations in commands."🛡️ Proposed fix
import { + requireVoiceChannel, requireQueue, } from "../../../utils/command/commandValidations"And add the check in execute:
execute: async ({ client, interaction }: CommandExecuteParams) => { + if (!(await requireVoiceChannel(interaction))) return + const { queue } = resolveGuildQueue(client, interaction.guildId ?? '')🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bot/src/functions/music/commands/resume.ts` around lines 15 - 18, Add the missing voice-channel validation to the resume command: inside execute in resume.ts (the function using resolveGuildQueue and requireQueue), call the existing requireVoiceChannel validator (the same one used in the pause command) and return early if it fails before attempting to resume the queue; ensure you import/use requireVoiceChannel alongside requireQueue/resolveGuildQueue so the command enforces the user is in a voice channel before proceeding.
🧹 Nitpick comments (3)
packages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.ts (1)
3-3: Consider type alias naming convention.Per coding guidelines, type aliases should use the
T{Name}naming convention:TPlatformTypeinstead ofPlatformType.♻️ Suggested naming change
-export type PlatformType = 'lastfm' | 'spotify' | 'youtube' +export type TPlatformType = 'lastfm' | 'spotify' | 'youtube'Note: This would require updating the function signature and any downstream consumers.
As per coding guidelines: "Use
T{Name}naming convention for type aliases and utility types in TypeScript."🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.ts` at line 3, Rename the type alias PlatformType to follow the T{Name} convention (TPlatformType) and update all references: change the export type declaration from PlatformType to TPlatformType, update any function signatures (e.g., buildPlatformAttribEmbed or other functions referencing PlatformType) and update all downstream consumers/imports that use PlatformType so they import and use TPlatformType instead; ensure exports and any related JSDoc/type annotations are updated accordingly to avoid type errors.packages/bot/src/functions/music/commands/queue/queueEmbed.spec.ts (1)
2-5: Mock return value may not match expected type.The mock returns an empty object
{}, butcreateMusicControlButtonsreturnsActionRowBuilder<ButtonBuilder>. While this works for current tests, it could mask issues if tests later assert on thecomponentsarray structure.Consider returning a mock that resembles the actual return type:
♻️ Suggested improvement
jest.mock('../../../../utils/music/buttonComponents', () => ({ createQueuePaginationButtons: jest.fn().mockReturnValue(null), - createMusicControlButtons: jest.fn().mockReturnValue({}), + createMusicControlButtons: jest.fn().mockReturnValue({ + toJSON: jest.fn().mockReturnValue({ type: 1, components: [] }), + }), }))🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bot/src/functions/music/commands/queue/queueEmbed.spec.ts` around lines 2 - 5, The mocked createMusicControlButtons currently returns a plain object which doesn't match the real return type (ActionRowBuilder<ButtonBuilder>); update the jest.mock in queueEmbed.spec.ts so createMusicControlButtons returns a mock that resembles the actual structure (for example an array or ActionRow-like object containing a components array of button-like stubs) to avoid masking type/structure issues, while leaving createQueuePaginationButtons as-is; locate the mock by the function name createMusicControlButtons and replace its mockReturnValue with a structurally similar mock return.packages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.ts (1)
4-135: Add boundary-behavior tests for invalid paging inputs.Please add cases for
page <= 0,page > totalPages, anditemsPerPage <= 0so pagination behavior stays stable under invalid inputs.As per coding guidelines, "Test behavior, not implementation details".
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.ts` around lines 4 - 135, Add three boundary tests for buildListPageEmbed: (1) when page <= 0 call buildListPageEmbed(items, 0, { title, itemsPerPage }) and assert the embed behaves like page 1 (footer "Page 1 / N" and first-page fields); (2) when page > totalPages call buildListPageEmbed(items, 999, { title }) and assert it returns the last page (footer "Page X / X" and fields correspond to the final items); (3) when itemsPerPage <= 0 call buildListPageEmbed(items, 1, { title, itemsPerPage: 0 }) and assert it falls back to the default itemsPerPage (expect 10 fields and correct footer). Use the existing pattern in the spec to create items arrays and verify embed.data.fields length, first/last field names, and embed.data.footer?.text.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/bot/src/functions/music/commands/pause.ts`:
- Around line 59-65: The call to buildTrackEmbed is passing an object with tag:
interaction.user.username which doesn't match the expected Pick<User, 'tag' |
'displayAvatarURL'>; update the object passed to buildTrackEmbed (near
trackToData, currentTrack, trackEmbed usage) to pass tag: interaction.user.tag
and keep displayAvatarURL: interaction.user.displayAvatarURL so the argument
conforms to the User shape.
In `@packages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts`:
- Around line 24-26: The pagination code uses unvalidated itemsPerPage and page
which can produce incorrect totalPages and empty slices; in buildListPageEmbed
validate and clamp both inputs: coerce itemsPerPage to a safe integer >=1
(fallback to DEFAULT_ITEMS_PER_PAGE) before computing totalPages, compute
totalPages = Math.max(1, Math.ceil(items.length / itemsPerPage)), then clamp
page to an integer in [1, totalPages] before calculating slice indices; update
any uses of itemsPerPage, totalPages, and page (e.g., the variables
itemsPerPage, totalPages, page and the slice logic) to use these sanitized
values and add a simple type-guard/schema validation for external inputs.
In `@packages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.ts`:
- Around line 40-43: Normalize and validate the incoming stats object in
buildUserProfileEmbed: treat properties like xp, level, progress (and any
numeric stat fields) as valid only if they are finite numbers and >= 0; coerce
string numbers to Number when safe, clamp progress to 0–100, and filter out
undefined/null fields before building embed fields; if after sanitization no
valid fields remain, call embed.setDescription('No stats available.') and return
the embed early. Also ensure any calculations (e.g., progress percentage,
progressBar generation) use the sanitized numeric values to avoid NaN/negative
behavior.
---
Outside diff comments:
In `@packages/bot/src/functions/music/commands/resume.ts`:
- Around line 15-18: Add the missing voice-channel validation to the resume
command: inside execute in resume.ts (the function using resolveGuildQueue and
requireQueue), call the existing requireVoiceChannel validator (the same one
used in the pause command) and return early if it fails before attempting to
resume the queue; ensure you import/use requireVoiceChannel alongside
requireQueue/resolveGuildQueue so the command enforces the user is in a voice
channel before proceeding.
---
Nitpick comments:
In `@packages/bot/src/functions/music/commands/queue/queueEmbed.spec.ts`:
- Around line 2-5: The mocked createMusicControlButtons currently returns a
plain object which doesn't match the real return type
(ActionRowBuilder<ButtonBuilder>); update the jest.mock in queueEmbed.spec.ts so
createMusicControlButtons returns a mock that resembles the actual structure
(for example an array or ActionRow-like object containing a components array of
button-like stubs) to avoid masking type/structure issues, while leaving
createQueuePaginationButtons as-is; locate the mock by the function name
createMusicControlButtons and replace its mockReturnValue with a structurally
similar mock return.
In `@packages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.ts`:
- Around line 4-135: Add three boundary tests for buildListPageEmbed: (1) when
page <= 0 call buildListPageEmbed(items, 0, { title, itemsPerPage }) and assert
the embed behaves like page 1 (footer "Page 1 / N" and first-page fields); (2)
when page > totalPages call buildListPageEmbed(items, 999, { title }) and assert
it returns the last page (footer "Page X / X" and fields correspond to the final
items); (3) when itemsPerPage <= 0 call buildListPageEmbed(items, 1, { title,
itemsPerPage: 0 }) and assert it falls back to the default itemsPerPage (expect
10 fields and correct footer). Use the existing pattern in the spec to create
items arrays and verify embed.data.fields length, first/last field names, and
embed.data.footer?.text.
In `@packages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.ts`:
- Line 3: Rename the type alias PlatformType to follow the T{Name} convention
(TPlatformType) and update all references: change the export type declaration
from PlatformType to TPlatformType, update any function signatures (e.g.,
buildPlatformAttribEmbed or other functions referencing PlatformType) and update
all downstream consumers/imports that use PlatformType so they import and use
TPlatformType instead; ensure exports and any related JSDoc/type annotations are
updated accordingly to avoid type errors.
🪄 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: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 66dd0c7e-1ebd-4b07-a7e4-7e4006560d69
📒 Files selected for processing (15)
packages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.ts
📜 Review details
🧰 Additional context used
📓 Path-based instructions (20)
**/*.{js,jsx,ts,tsx,vue,html}
📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)
Provide accessible UI components using semantic HTML and ARIA attributes where necessary
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)
**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier
**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.
**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports
**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators
**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforcedImplement TypeScript typecheck and linter in CI quality checks
**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)
**/*.{js,jsx,ts,tsx}: Never throw strings. ThrowError(or typed subclasses) with descriptive messages
Include causal error ascausewhen available for better debugging
Define clear, stable error codes (e.g.,ERR_AUTH_EXPIRED,ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g.,details,retryable,status,correlationId) in error objects
Use domain error classes per area (e.g.,AuthenticationError,ValidationError,NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
MarkretryablevsnonRetryableerrors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)
**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques:React.memo,useMemo,useCallback,Suspense(web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, andaria-*attributes as needed.
React Native accessibility: use accessibility props (accessible,accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively tocomponents/with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: preferStyleSheet.create, design tokens, and theme providers; avoid in...
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)
Introduce interfaces at module boundaries to enable testing and substitutions
**/*.{ts,tsx}: Avoid usinganytype in TypeScript. If unavoidable, useunknownwith type guards and justify with a code comment
Preferinterfacefor defining public object shapes in TypeScript, usetypefor unions and utility types
Use TypeScript utility types such asPartial,Pick,Omit,Readonly, andRecordwhen appropriate
UseI{Name}naming convention for interfaces in TypeScript
UseT{Name}naming convention for type aliases and utility types in TypeScript
**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not useanytypes - ESLint enforces this at error level
**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever useany- type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid usinganytype; if unavoidable, useunknownwith type guards and justify with code comment
Preferinterfacefor public API shapes; usetypefor unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)
**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns
**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env,.env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy commentsNever hardcode secrets, IPs, or ports; use
.envanddocs/for required configuration variables
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
packages/bot/src/functions/*/commands/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)
packages/bot/src/functions/*/commands/**/*.{ts,tsx}: Command model must includedata(slash builder),execute, andcategoryproperties exported frompackages/bot/src/models/Command.ts
Use@discordjs/buildersfor building thedata(SlashCommandBuilder) in command definitions
Commandexecutefunction must receive{ interaction, client }parameters fromCommandExecuteParamstype
UseinteractionReplyandcreateUserFriendlyErrorutilities from@lucky/shared/generalutils for command replies and error handling
Use existing validators frompackages/bot/src/utils/command/for voice channel, queue, and guild validations in commands
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/functions/music/commands/resume.ts
packages/bot/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)
packages/bot/**/*.{ts,tsx}: UseuseMainPlayer()fromdiscord-playerto access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from@lucky/sharedfor persistent data like track history and session information
UseerrorLoganddebugLogfrom@lucky/shared/utilsfor logging throughout the bot package
Use embed and reply utilities from@lucky/sharedfor consistent message formatting and error sanitization across the bot
Use services from@lucky/shared(DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
packages/bot/**
📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)
The
botpackage depends onsharedand contains Discord bot commands and player handlers using Discord.js and Discord Player
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
**/*.{js,mjs,ts,mts}
📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)
Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
packages/bot/src/functions/{general,music,download}/commands/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)
packages/bot/src/functions/{general,music,download}/commands/**/*.ts: Apply.cursor/rules/lucky-discord-bot.mdcrules for Discord bot commands and player implementation
Use.cursor/skills/discord-commands/SKILL.mdfor implementing slash commands
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/functions/music/commands/resume.ts
packages/bot/src/functions/music/commands/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)
Use
.cursor/skills/music-queue-player/SKILL.mdfor play, queue, skip, volume commands and player lifecycle management
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/functions/music/commands/resume.ts
packages/bot/src/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)
Use
@lucky/sharedfor database, Redis, logging, and embed utilities instead of implementing them locally
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.tspackages/bot/src/functions/music/commands/resume.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.tspackages/bot/src/utils/general/responseEmbeds/index.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts
packages/bot/src/functions/music/**/*.ts
📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)
Use existing voice/queue/guild validators before manipulating player or queue state
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.tspackages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/functions/music/commands/resume.ts
**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)
**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.ts
**/*.{test,spec}.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)
**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)
**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.ts
**/*.{spec,test}.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)
**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.ts
**/*.spec.ts
📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)
Unit tests must use naming convention
*.spec.ts
Files:
packages/bot/src/functions/music/commands/queue/queueEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.tspackages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.ts
packages/bot/src/functions/**/commands/*.ts
📄 CodeRabbit inference engine (CLAUDE.md)
Discord bot commands must be structured in
packages/bot/src/functions/<category>/commands/<name>.tswith handlers in<category>/handlers/
Files:
packages/bot/src/functions/music/commands/pause.tspackages/bot/src/functions/music/commands/skip.tspackages/bot/src/functions/music/commands/songinfo.tspackages/bot/src/functions/music/commands/resume.ts
**/index.ts
📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)
Use
index.tsonly to re-export a small, intentional surface per module
Files:
packages/bot/src/utils/general/responseEmbeds/index.ts
🔇 Additional comments (19)
packages/bot/src/functions/music/commands/resume.ts (3)
54-60: Sametag/usernamepattern as pause command.This follows the same pattern flagged in
pause.tsregarding thetagproperty receivingusernamevalue.
8-8: LGTM!Import matches the consistent embed utility pattern used across music commands.
38-52: LGTM!Consistent fallback handling when no current track exists after resuming.
packages/bot/src/functions/music/commands/queue/queueEmbed.ts (2)
16-19: LGTM!The import consolidation is clean and follows the existing pattern for button component utilities.
131-137: LGTM!The unconditional addition of music control buttons enhances queue UX by providing immediate playback controls. The type compatibility with
ActionRowBuilder<ButtonBuilder>is confirmed by thecreateMusicControlButtonsreturn type from context snippet 1.packages/bot/src/functions/music/commands/pause.ts (2)
11-11: LGTM!Import aligns with the PR's goal of using shared embed utilities consistently across music commands.
43-57: LGTM!Good defensive handling for the edge case when
currentTrackis null after pausing, providing a graceful fallback message.packages/bot/src/functions/music/commands/songinfo.ts (2)
4-4: LGTM!Clean import of shared embed utilities, replacing local formatting helpers.
26-30: LGTM!The non-null assertion on
track!is safe here becauserequireCurrentTrackvalidates and returns early if the track is null (line 24). The refactor cleanly removes local timestamp/tempo computation in favor of the sharedtrackToDatautility.packages/bot/src/functions/music/commands/skip.ts (3)
6-6: LGTM!Consistent import of shared embed utilities.
53-89: LGTM!Well-structured function that conditionally shows either a simple success message or a rich "Now playing" embed based on whether a next track exists. The early return pattern keeps the logic clear and readable.
128-133: LGTM!Clean integration passing
queuetosendSkipSuccessfor context-aware response generation.packages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.spec.ts (1)
1-116: LGTM!Comprehensive test suite covering all platforms (Last.fm, Spotify, YouTube), both presence and absence of optional fields, and edge cases like empty body objects. Tests verify behavior rather than implementation details.
packages/bot/src/utils/general/responseEmbeds/buildPlatformAttribEmbed.ts (2)
11-27: LGTM!Clean platform branding configuration using a const object with proper typing. The hex color values match the official brand colors for each platform.
29-59: LGTM!Well-structured builder function with clear conditional field setting. The function properly handles optional fields and maintains consistent embed structure across platforms.
packages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.spec.ts (1)
10-93: Strong behavioral coverage for profile embed states.These cases exercise the user-facing output well (fallbacks, XP modes, empty state, and timestamp), which matches the intended contract.
packages/bot/src/utils/general/responseEmbeds/index.ts (1)
1-12: Clean, intentional barrel export surface.This keeps embed utility consumption consistent and avoids scattered deep imports.
packages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.spec.ts (1)
10-193: Comprehensive coverage for source detection and track embed behavior.This suite gives good confidence across kind variants, fallback handling, and mapping rules.
packages/bot/src/utils/general/responseEmbeds/buildTrackEmbed.ts (1)
24-76: Good shared utility design for track responses.The embed builder + mapper split is clean and improves reuse across music commands.
| const itemsPerPage = config.itemsPerPage ?? DEFAULT_ITEMS_PER_PAGE | ||
| const totalPages = items.length === 0 ? 1 : Math.ceil(items.length / itemsPerPage) | ||
|
|
There was a problem hiding this comment.
Validate and clamp pagination inputs before slicing.
Line 24 and Line 40 use unvalidated itemsPerPage/page. Invalid values can generate wrong footers and empty pages even when items exist. Clamp and sanitize both first.
💡 Suggested fix
export function buildListPageEmbed(
items: ListItem[],
page: number,
config: ListPageConfig,
): EmbedBuilder {
- const itemsPerPage = config.itemsPerPage ?? DEFAULT_ITEMS_PER_PAGE
- const totalPages = items.length === 0 ? 1 : Math.ceil(items.length / itemsPerPage)
+ const rawItemsPerPage = config.itemsPerPage ?? DEFAULT_ITEMS_PER_PAGE
+ const itemsPerPage =
+ Number.isInteger(rawItemsPerPage) && rawItemsPerPage > 0
+ ? rawItemsPerPage
+ : DEFAULT_ITEMS_PER_PAGE
+ const totalPages =
+ items.length === 0 ? 1 : Math.ceil(items.length / itemsPerPage)
+ const safePage = Number.isInteger(page)
+ ? Math.min(Math.max(page, 1), totalPages)
+ : 1
const embed = new EmbedBuilder()
.setTitle(config.title)
.setColor(config.color ?? DEFAULT_COLOR)
.setTimestamp()
.setFooter({
- text: `Page ${page} / ${totalPages}`,
+ text: `Page ${safePage} / ${totalPages}`,
})
@@
- const startIndex = (page - 1) * itemsPerPage
+ const startIndex = (safePage - 1) * itemsPerPage
const endIndex = Math.min(startIndex + itemsPerPage, items.length)
const pageItems = items.slice(startIndex, endIndex)As per coding guidelines, "For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators".
Also applies to: 40-43
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/bot/src/utils/general/responseEmbeds/buildListPageEmbed.ts` around
lines 24 - 26, The pagination code uses unvalidated itemsPerPage and page which
can produce incorrect totalPages and empty slices; in buildListPageEmbed
validate and clamp both inputs: coerce itemsPerPage to a safe integer >=1
(fallback to DEFAULT_ITEMS_PER_PAGE) before computing totalPages, compute
totalPages = Math.max(1, Math.ceil(items.length / itemsPerPage)), then clamp
page to an integer in [1, totalPages] before calculating slice indices; update
any uses of itemsPerPage, totalPages, and page (e.g., the variables
itemsPerPage, totalPages, page and the slice logic) to use these sanitized
values and add a simple type-guard/schema validation for external inputs.
| if (!stats || Object.keys(stats).length === 0) { | ||
| embed.setDescription('No stats available.') | ||
| return embed | ||
| } |
There was a problem hiding this comment.
Harden stats sanitization and empty-state fallback.
Line 40 treats any non-empty object as valid stats. Cases like { xp: undefined } or negative values can yield no fields or invalid progress behavior. Normalize inputs and fall back to "No stats available." when no valid fields remain.
💡 Suggested fix
export function buildUserProfileEmbed(
user: Pick<User, 'username' | 'displayAvatarURL'> & { tag?: string },
stats?: UserStats,
): EmbedBuilder {
@@
- if (!stats || Object.keys(stats).length === 0) {
+ if (!stats || Object.keys(stats).length === 0) {
embed.setDescription('No stats available.')
return embed
}
const fields: { name: string; value: string; inline: boolean }[] = []
- if (typeof stats.level === 'number') {
+ if (typeof stats.level === 'number' && stats.level >= 0) {
fields.push({ name: 'Level', value: String(stats.level), inline: true })
}
- if (typeof stats.rank === 'number') {
+ if (typeof stats.rank === 'number' && stats.rank >= 0) {
fields.push({ name: 'Rank', value: `#${stats.rank}`, inline: true })
}
- if (typeof stats.xp === 'number') {
- if (typeof stats.xpForNextLevel === 'number') {
+ if (typeof stats.xp === 'number' && stats.xp >= 0) {
+ if (
+ typeof stats.xpForNextLevel === 'number' &&
+ stats.xpForNextLevel > 0
+ ) {
const progress = createProgressBar(stats.xp, stats.xpForNextLevel)
fields.push({
name: 'XP Progress',
value: `${progress} ${stats.xp} / ${stats.xpForNextLevel}`,
inline: false,
})
} else {
fields.push({
name: 'Total XP',
value: String(stats.xp),
inline: true,
})
}
}
+ if (fields.length === 0) {
+ embed.setDescription('No stats available.')
+ return embed
+ }
+
embed.addFields(fields)
return embed
}As per coding guidelines, "For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators".
Also applies to: 47-73
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/bot/src/utils/general/responseEmbeds/buildUserProfileEmbed.ts`
around lines 40 - 43, Normalize and validate the incoming stats object in
buildUserProfileEmbed: treat properties like xp, level, progress (and any
numeric stat fields) as valid only if they are finite numbers and >= 0; coerce
string numbers to Number when safe, clamp progress to 0–100, and filter out
undefined/null fields before building embed fields; if after sanitization no
valid fields remain, call embed.setDescription('No stats available.') and return
the embed early. Also ensure any calculations (e.g., progress percentage,
progressBar generation) use the sanitized numeric values to avoid NaN/negative
behavior.
Pull request was closed
|
Size Change: 0 B Total Size: 324 kB ℹ️ View Unchanged
|
Added spec files for pause, resume, and songinfo commands and extended skip.spec.ts to cover the buildTrackEmbed rich-embed code path. Ensures SonarCloud quality gate passes on new responseEmbeds usage.
…cation Extracted the repeated trackToData + buildTrackEmbed + setAuthor pattern from pause, resume, and skip commands into a shared buildCommandTrackEmbed helper. Reduces SonarCloud duplication from 38.5% to below threshold.
|



Summary
Phase 3 of v2.6.66 polish wave — music commands now use shared
buildTrackEmbedfor consistent, rich track responses.Changes
/songinfo— migrated from ad-hocmusicEmbedtobuildTrackEmbed(track, 'playing'): thumbnail, source badge, duration, platform color/skip//pause//resume— mini-embed showing current/next track withbuildTrackEmbed+ action context (was flatsuccessEmbed)/queue show— now attachescreateMusicControlButtons(queue)so users can pause/skip from the queue view directlyAlso
TrackDatatype andtrackToDatahelper fromresponseEmbedsbarrel for downstream usequeueEmbed.spec.tsmock updated forcreateMusicControlButtonsTest plan
Summary by CodeRabbit
New Features
Tests