Merge pull request #44 from jsholmes/feat/likes-pagination

feat: add full pagination support to likes (parity with bookmarks)
This commit is contained in:
Peter Steinberger
2026-01-12 07:09:02 +00:00
committed by GitHub
6 changed files with 168 additions and 42 deletions
+1
View File
@@ -11,6 +11,7 @@
- Long-form article tweets now render rich Draft.js content blocks/entities (#36) — thanks @crcatala. - Long-form article tweets now render rich Draft.js content blocks/entities (#36) — thanks @crcatala.
- `news`/`trending` command for Explore tabs with AI-curated headlines (#39) — thanks @aavetis. - `news`/`trending` command for Explore tabs with AI-curated headlines (#39) — thanks @aavetis.
- `search` now supports pagination (`--all`, `--max-pages`, `--cursor`) (#42) — thanks @pjtf93. - `search` now supports pagination (`--all`, `--max-pages`, `--cursor`) (#42) — thanks @pjtf93.
- `likes` now supports pagination (`--all`, `--max-pages`, `--cursor`) (#44) — thanks @jsholmes.
### Changed ### Changed
- Library typing: `SearchResult` is now a discriminated union (so `error` only exists when `success: false`). - Library typing: `SearchResult` is now a discriminated union (so `error` only exists when `success: false`).
+38 -5
View File
@@ -328,13 +328,25 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
.command('likes') .command('likes')
.description('Get your liked tweets') .description('Get your liked tweets')
.option('-n, --count <number>', 'Number of likes to fetch', '20') .option('-n, --count <number>', 'Number of likes to fetch', '20')
.option('--all', 'Fetch all likes (paged)')
.option('--max-pages <number>', 'Stop after N pages when using --all')
.option('--cursor <string>', 'Resume pagination from a cursor')
.option('--json', 'Output as JSON') .option('--json', 'Output as JSON')
.option('--json-full', 'Output as JSON with full raw API response in _raw field') .option('--json-full', 'Output as JSON with full raw API response in _raw field')
.action(async (cmdOpts: { count?: string; json?: boolean; jsonFull?: boolean }) => { .action(
async (cmdOpts: {
count?: string;
json?: boolean;
jsonFull?: boolean;
all?: boolean;
maxPages?: string;
cursor?: string;
}) => {
const opts = program.opts(); const opts = program.opts();
const timeoutMs = ctx.resolveTimeoutFromOptions(opts); const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts); const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
const count = Number.parseInt(cmdOpts.count || '20', 10); const count = Number.parseInt(cmdOpts.count || '20', 10);
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts); const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
@@ -347,20 +359,41 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
process.exit(1); process.exit(1);
} }
const usePagination = cmdOpts.all || cmdOpts.cursor;
if (maxPages !== undefined && !usePagination) {
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
process.exit(1);
}
if (!usePagination && (!Number.isFinite(count) || count <= 0)) {
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
process.exit(1);
}
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
process.exit(1);
}
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth }); const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
const includeRaw = cmdOpts.jsonFull ?? false; const includeRaw = cmdOpts.jsonFull ?? false;
const result = await client.getLikes(count, { includeRaw }); const timelineOptions = { includeRaw };
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
const result = usePagination
? await client.getAllLikes(paginationOptions)
: await client.getLikes(count, timelineOptions);
if (result.success) { if (result.success) {
ctx.printTweets(result.tweets, { const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
json: cmdOpts.json || cmdOpts.jsonFull, ctx.printTweetsResult(result, {
json: isJson,
usePagination: Boolean(usePagination),
emptyMessage: 'No liked tweets found.', emptyMessage: 'No liked tweets found.',
}); });
} else { } else {
console.error(`${ctx.p('err')}Failed to fetch likes: ${result.error}`); console.error(`${ctx.p('err')}Failed to fetch likes: ${result.error}`);
process.exit(1); process.exit(1);
} }
}); },
);
program program
.command('whoami') .command('whoami')
+1 -1
View File
@@ -449,7 +449,7 @@ export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
return { success: false as const, error: firstAttempt.error }; return { success: false as const, error: firstAttempt.error };
}; };
const unlimited = !Number.isFinite(limit); const unlimited = limit === Number.POSITIVE_INFINITY;
while (unlimited || tweets.length < limit) { while (unlimited || tweets.length < limit) {
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length); const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
const page = await fetchWithRefresh(pageCount, cursor); const page = await fetchWithRefresh(pageCount, cursor);
+1 -1
View File
@@ -209,7 +209,7 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
return { success: false as const, error: firstAttempt.error }; return { success: false as const, error: firstAttempt.error };
}; };
const unlimited = !Number.isFinite(limit); const unlimited = limit === Number.POSITIVE_INFINITY;
while (unlimited || tweets.length < limit) { while (unlimited || tweets.length < limit) {
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length); const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
const page = await fetchWithRefresh(pageCount, cursor); const page = await fetchWithRefresh(pageCount, cursor);
+33 -14
View File
@@ -21,6 +21,7 @@ export interface TwitterClientTimelineMethods {
getBookmarks(count?: number, options?: TimelineFetchOptions): Promise<SearchResult>; getBookmarks(count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
getAllBookmarks(options?: TimelinePaginationOptions): Promise<SearchResult>; getAllBookmarks(options?: TimelinePaginationOptions): Promise<SearchResult>;
getLikes(count?: number, options?: TimelineFetchOptions): Promise<SearchResult>; getLikes(count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
getAllLikes(options?: TimelinePaginationOptions): Promise<SearchResult>;
getBookmarkFolderTimeline(folderId: string, count?: number, options?: TimelineFetchOptions): Promise<SearchResult>; getBookmarkFolderTimeline(folderId: string, count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
getAllBookmarkFolderTimeline(folderId: string, options?: TimelinePaginationOptions): Promise<SearchResult>; getAllBookmarkFolderTimeline(folderId: string, options?: TimelinePaginationOptions): Promise<SearchResult>;
} }
@@ -75,18 +76,27 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
* Get the authenticated user's liked tweets * Get the authenticated user's liked tweets
*/ */
async getLikes(count = 20, options: TimelineFetchOptions = {}): Promise<SearchResult> { async getLikes(count = 20, options: TimelineFetchOptions = {}): Promise<SearchResult> {
const { includeRaw = false } = options; return this.getLikesPaged(count, options);
}
async getAllLikes(options?: TimelinePaginationOptions): Promise<SearchResult> {
return this.getLikesPaged(Number.POSITIVE_INFINITY, options);
}
private async getLikesPaged(limit: number, options: TimelinePaginationOptions = {}): Promise<SearchResult> {
const userResult = await this.getCurrentUser(); const userResult = await this.getCurrentUser();
if (!userResult.success || !userResult.user) { if (!userResult.success || !userResult.user) {
return { success: false, error: userResult.error ?? 'Could not determine current user' }; return { success: false, error: userResult.error ?? 'Could not determine current user' };
} }
const userId = userResult.user.id; const userId = userResult.user.id;
const features = buildLikesFeatures();
const pageSize = 20; const pageSize = 20;
const seen = new Set<string>(); const seen = new Set<string>();
const tweets: TweetData[] = []; const tweets: TweetData[] = [];
let cursor: string | undefined; let cursor: string | undefined = options.cursor;
const features = buildLikesFeatures(); let nextCursor: string | undefined;
let pagesFetched = 0;
const { includeRaw = false, maxPages } = options;
const fetchPage = async (pageCount: number, pageCursor?: string) => { const fetchPage = async (pageCount: number, pageCursor?: string) => {
let lastError: string | undefined; let lastError: string | undefined;
@@ -164,9 +174,9 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
} }
} }
const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw }); const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
const nextCursor = extractCursorFromInstructions(instructions); const extractedCursor = extractCursorFromInstructions(instructions);
return { success: true as const, tweets: pageTweets, cursor: nextCursor, had404 }; return { success: true as const, tweets: pageTweets, cursor: extractedCursor, had404 };
} catch (error) { } catch (error) {
lastError = error instanceof Error ? error.message : String(error); lastError = error instanceof Error ? error.message : String(error);
} }
@@ -194,12 +204,14 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
return { success: false as const, error: firstAttempt.error }; return { success: false as const, error: firstAttempt.error };
}; };
while (tweets.length < count) { const unlimited = limit === Number.POSITIVE_INFINITY;
const pageCount = Math.min(pageSize, count - tweets.length); while (unlimited || tweets.length < limit) {
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
const page = await fetchWithRefresh(pageCount, cursor); const page = await fetchWithRefresh(pageCount, cursor);
if (!page.success) { if (!page.success) {
return { success: false, error: page.error }; return { success: false, error: page.error };
} }
pagesFetched += 1;
let added = 0; let added = 0;
for (const tweet of page.tweets) { for (const tweet of page.tweets) {
@@ -209,18 +221,25 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
seen.add(tweet.id); seen.add(tweet.id);
tweets.push(tweet); tweets.push(tweet);
added += 1; added += 1;
if (tweets.length >= count) { if (!unlimited && tweets.length >= limit) {
break; break;
} }
} }
if (!page.cursor || page.cursor === cursor || page.tweets.length === 0 || added === 0) { const pageCursor = page.cursor;
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0 || added === 0) {
nextCursor = undefined;
break; break;
} }
cursor = page.cursor; if (maxPages && pagesFetched >= maxPages) {
nextCursor = pageCursor;
break;
}
cursor = pageCursor;
nextCursor = pageCursor;
} }
return { success: true, tweets }; return { success: true, tweets, nextCursor };
} }
/** /**
@@ -363,7 +382,7 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
return { success: false as const, error: firstAttempt.error }; return { success: false as const, error: firstAttempt.error };
}; };
const unlimited = !Number.isFinite(limit); const unlimited = limit === Number.POSITIVE_INFINITY;
while (unlimited || tweets.length < limit) { while (unlimited || tweets.length < limit) {
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length); const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
const page = await fetchWithRefresh(pageCount, cursor); const page = await fetchWithRefresh(pageCount, cursor);
@@ -546,7 +565,7 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
return { success: false as const, error: firstAttempt.error }; return { success: false as const, error: firstAttempt.error };
}; };
const unlimited = !Number.isFinite(limit); const unlimited = limit === Number.POSITIVE_INFINITY;
while (unlimited || tweets.length < limit) { while (unlimited || tweets.length < limit) {
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length); const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
const page = await fetchWithRefresh(pageCount, cursor); const page = await fetchWithRefresh(pageCount, cursor);
+73
View File
@@ -218,6 +218,79 @@ describe('TwitterClient likes', () => {
expect(secondVars.cursor).toBe('cursor-1'); expect(secondVars.cursor).toBe('cursor-1');
}); });
it('respects maxPages when fetching all likes', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
data: {
user: {
result: {
timeline: {
timeline: {
instructions: [
{
entries: [
{
content: {
itemContent: {
tweet_results: {
result: {
rest_id: '1',
legacy: {
full_text: 'liked page 1',
created_at: '2024-01-01T00:00:00Z',
reply_count: 0,
retweet_count: 0,
favorite_count: 0,
conversation_id_str: '1',
},
core: {
user_results: {
result: {
rest_id: 'u1',
legacy: { screen_name: 'root', name: 'Root' },
},
},
},
},
},
},
},
},
{
content: {
cursorType: 'Bottom',
value: 'cursor-1',
},
},
],
},
],
},
},
},
},
},
}),
});
const client = new TwitterClient({ cookies: validCookies });
const clientPrivate = client as unknown as TwitterClientPrivate;
clientPrivate.getCurrentUser = async () => ({
success: true,
user: { id: '42', username: 'tester', name: 'Tester' },
});
clientPrivate.getLikesQueryIds = async () => ['test'];
const result = await client.getAllLikes({ maxPages: 1 });
expect(result.success).toBe(true);
expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1']);
expect(result.nextCursor).toBe('cursor-1');
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it('returns an error when current user is unavailable', async () => { it('returns an error when current user is unavailable', async () => {
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ cookies: validCookies });
const clientPrivate = client as unknown as TwitterClientPrivate; const clientPrivate = client as unknown as TwitterClientPrivate;