8 Commits
Author SHA1 Message Date
yuta 45657a171e fix lists queries and authenticated list reading
CI / test (push) Successful in 10m5s
Publish npm package / publish (push) Successful in 9m53s
2026-07-26 12:34:53 +09:00
yuta b8400469ca Release v0.10.0
CI / test (push) Successful in 9m59s
Publish npm package / publish (push) Successful in 9m53s
2026-07-14 02:35:26 +09:00
yuta 81921226f0 feat: support ranked tweet search
CI / test (push) Successful in 10m17s
2026-07-13 09:18:42 +09:00
yuta 0caf2677e4 Release v0.9.0
CI / test (push) Successful in 10m2s
Publish npm package / publish (push) Successful in 9m53s
2026-06-26 13:24:01 +09:00
yuta 9340ed3f47 Add profileImageUrl to TweetData.author
CI / test (push) Successful in 11m4s
2026-06-26 01:56:14 +09:00
yuta 2e293ad65b Add user profile resolution
CI / test (push) Successful in 10m0s
2026-06-24 20:46:34 +09:00
yuta 826de66d78 Add home timeline pagination flags
CI / test (push) Successful in 9m58s
2026-06-24 20:17:02 +09:00
yuta 01f4b58b99 test: require explicit relay fixture
CI / test (push) Successful in 9m59s
2026-06-24 19:20:39 +09:00
42 changed files with 1539 additions and 363 deletions
+26
View File
@@ -1,5 +1,31 @@
# Changelog # Changelog
## 0.10.1 — 2026-07-26
### Added
- Add `getLists()` for the authenticated account's “Your Lists” timeline.
### Fixed
- Refresh Lists query IDs, variables, and feature flags.
- Keep usable list and tweet data when optional GraphQL fields return partial errors.
## 0.10.0 — 2026-07-14
### Added
- Add Top and Latest product selection to library and CLI search.
## 0.9.0 — 2026-06-26
### Added
- `users` command for user profile lookup with avatars and descriptions.
- `home` pagination: `--all`, `--max-pages`, `--cursor` flags.
### Changed
- Tweet output now includes `profileImageUrl` in author data.
## 0.8.0 — 2026-01-19 ## 0.8.0 — 2026-01-19
### Added ### Added
+26 -3
View File
@@ -51,6 +51,8 @@ bird thread 1234567890123456789 --max-pages 3 --json
# Search + mentions # Search + mentions
bird search "from:steipete" -n 5 bird search "from:steipete" -n 5
bird search "AI lang:ja" --product Top -n 20
bird search "from:steipete" --product Latest -n 20
bird mentions -n 5 bird mentions -n 5
bird mentions --user @steipete -n 5 bird mentions --user @steipete -n 5
@@ -87,6 +89,10 @@ bird following --user 12345678 -n 10 # by user ID
bird followers -n 20 bird followers -n 20
bird followers --user 12345678 -n 10 # by user ID bird followers --user 12345678 -n 10 # by user ID
# Rich profile resolution
bird user @steipete --json
bird profiles @steipete 12345678 --json
# Refresh GraphQL query IDs cache (no rebuild) # Refresh GraphQL query IDs cache (no rebuild)
bird query-ids --fresh bird query-ids --fresh
``` ```
@@ -141,6 +147,9 @@ const client = new TwitterClient({
// Search for tweets // Search for tweets
const searchResult = await client.search('from:steipete', 50); const searchResult = await client.search('from:steipete', 50);
const popular = await client.search('AI lang:ja', 20, {
product: 'Top',
});
// Fetch news and trending topics from all tabs (default: For You, News, Sports, Entertainment) // Fetch news and trending topics from all tabs (default: For You, News, Sports, Entertainment)
const newsResult = await client.getNews(10, { aiOnly: true }); const newsResult = await client.getNews(10, { aiOnly: true });
@@ -175,12 +184,12 @@ Fields:
- `bird reply <tweet-id-or-url> "<text>"` — reply to a tweet using its ID or URL. - `bird reply <tweet-id-or-url> "<text>"` — reply to a tweet using its ID or URL.
- `bird help [command]` — show help (or help for a subcommand). - `bird help [command]` — show help (or help for a subcommand).
- `bird query-ids [--fresh] [--json]` — inspect or refresh cached GraphQL query IDs. - `bird query-ids [--fresh] [--json]` — inspect or refresh cached GraphQL query IDs.
- `bird home [-n count] [--following] [--json] [--json-full]` — fetch your home timeline (For You) or Following feed. - `bird home [-n count] [--following] [--all] [--max-pages n] [--cursor string] [--delay ms] [--json] [--json-full]` — fetch your home timeline (For You) or Following feed; `--max-pages` implies pagination.
- `bird read <tweet-id-or-url> [--json]` — fetch tweet content as text or JSON. - `bird read <tweet-id-or-url> [--json]` — fetch tweet content as text or JSON.
- `bird <tweet-id-or-url> [--json]` — shorthand for `read` when only a URL or ID is provided. - `bird <tweet-id-or-url> [--json]` — shorthand for `read` when only a URL or ID is provided.
- `bird replies <tweet-id-or-url> [--all] [--max-pages n] [--cursor string] [--delay ms] [--json]` — list replies to a tweet. - `bird replies <tweet-id-or-url> [--all] [--max-pages n] [--cursor string] [--delay ms] [--json]` — list replies to a tweet.
- `bird thread <tweet-id-or-url> [--all] [--max-pages n] [--cursor string] [--delay ms] [--json]` — show the full conversation thread. - `bird thread <tweet-id-or-url> [--all] [--max-pages n] [--cursor string] [--delay ms] [--json]` — show the full conversation thread.
- `bird search "<query>" [-n count] [--all] [--max-pages n] [--cursor string] [--json]` — search for tweets matching a query; `--max-pages` requires `--all` or `--cursor`. - `bird search "<query>" [-n count] [--all] [--max-pages n] [--cursor string] [--product Top|Latest] [--json]` — search for tweets matching a query; `Latest` is the default product, and `--max-pages` requires `--all` or `--cursor`.
- `bird mentions [-n count] [--user @handle] [--json]` — find tweets mentioning a user (defaults to the authenticated user). - `bird mentions [-n count] [--user @handle] [--json]` — find tweets mentioning a user (defaults to the authenticated user).
- `bird user-tweets <@handle> [-n count] [--cursor string] [--max-pages n] [--delay ms] [--json]` — get tweets from a user's profile timeline. - `bird user-tweets <@handle> [-n count] [--cursor string] [--max-pages n] [--delay ms] [--json]` — get tweets from a user's profile timeline.
- `bird bookmarks [-n count] [--folder-id id] [--all] [--max-pages n] [--cursor string] [--expand-root-only] [--author-chain] [--author-only] [--full-chain-only] [--include-ancestor-branches] [--include-parent] [--thread-meta] [--sort-chronological] [--json]` — list your bookmarked tweets (or a specific bookmark folder); expansion flags control thread context; `--max-pages` requires `--all` or `--cursor`. - `bird bookmarks [-n count] [--folder-id id] [--all] [--max-pages n] [--cursor string] [--expand-root-only] [--author-chain] [--author-only] [--full-chain-only] [--include-ancestor-branches] [--include-parent] [--thread-meta] [--sort-chronological] [--json]` — list your bookmarked tweets (or a specific bookmark folder); expansion flags control thread context; `--max-pages` requires `--all` or `--cursor`.
@@ -188,10 +197,12 @@ Fields:
- `bird likes [-n count] [--all] [--max-pages n] [--cursor string] [--json] [--json-full]` — list your liked tweets; `--max-pages` requires `--all` or `--cursor`. - `bird likes [-n count] [--all] [--max-pages n] [--cursor string] [--json] [--json-full]` — list your liked tweets; `--max-pages` requires `--all` or `--cursor`.
- `bird news [-n count] [--ai-only] [--with-tweets] [--tweets-per-item n] [--for-you] [--news-only] [--sports] [--entertainment] [--trending-only] [--json]` — fetch news and trending topics from X's Explore tabs. - `bird news [-n count] [--ai-only] [--with-tweets] [--tweets-per-item n] [--for-you] [--news-only] [--sports] [--entertainment] [--trending-only] [--json]` — fetch news and trending topics from X's Explore tabs.
- `bird trending` — alias for `news` command. - `bird trending` — alias for `news` command.
- `bird lists [--member-of] [-n count] [--json]` — list your lists (owned or memberships). - `bird lists [--member-of] [-n count] [--json]` — list the authenticated account's “Your Lists”, or memberships with `--member-of`.
- `bird list-timeline <list-id-or-url> [-n count] [--all] [--max-pages n] [--cursor string] [--json]` — get tweets from a list timeline; `--max-pages` implies `--all`. - `bird list-timeline <list-id-or-url> [-n count] [--all] [--max-pages n] [--cursor string] [--json]` — get tweets from a list timeline; `--max-pages` implies `--all`.
- `bird following [--user <userId>] [-n count] [--cursor string] [--all] [--max-pages n] [--json]` — list users that you (or another user) follow; `--max-pages` requires `--all`. - `bird following [--user <userId>] [-n count] [--cursor string] [--all] [--max-pages n] [--json]` — list users that you (or another user) follow; `--max-pages` requires `--all`.
- `bird followers [--user <userId>] [-n count] [--cursor string] [--all] [--max-pages n] [--json]` — list users that follow you (or another user); `--max-pages` requires `--all`. - `bird followers [--user <userId>] [-n count] [--cursor string] [--all] [--max-pages n] [--json]` — list users that follow you (or another user); `--max-pages` requires `--all`.
- `bird user <@handle-or-id> [--json]` — resolve a rich user profile.
- `bird profiles <@handle-or-id...> [--json]` — resolve rich user profiles with per-target errors.
- `bird about <@handle> [--json]` — get account origin and location information for a user. - `bird about <@handle> [--json]` — get account origin and location information for a user.
- `bird whoami` — print which Twitter account your relay belongs to. - `bird whoami` — print which Twitter account your relay belongs to.
- `bird check` — verify relay configuration and account access. - `bird check` — verify relay configuration and account access.
@@ -293,6 +304,18 @@ When using `--json` with `following`/`followers`, user objects include:
| `profileImageUrl` | string? | Profile image URL | | `profileImageUrl` | string? | Profile image URL |
| `createdAt` | string? | Account creation timestamp | | `createdAt` | string? | Account creation timestamp |
When using `--json` with `user`/`profiles`, profile objects include the user fields above plus richer metadata when available:
| Field | Type | Description |
|-------|------|-------------|
| `location` | string? | Profile location |
| `url` | string? | Expanded profile URL |
| `verified` | boolean? | Verified status |
| `verifiedType` | string? | Verification type |
| `entities` | object? | Raw profile URL/bio entities |
| `affiliation` | object? | Highlighted-label organization metadata |
| `raw` | object? | Raw GraphQL user payload |
When using `--json` with `news`/`trending`, news objects include: When using `--json` with `news`/`trending`, news objects include:
| Field | Type | Description | | Field | Type | Description |
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "@yuta/bird", "name": "@yuta/bird",
"version": "0.8.0", "version": "0.10.1",
"description": "CLI tool for tweeting and replying via Twitter/X GraphQL API", "description": "CLI tool for tweeting and replying via Twitter/X GraphQL API",
"type": "module", "type": "module",
"main": "dist/index.js", "main": "dist/index.js",
+5
View File
@@ -29,6 +29,10 @@ const TARGET_OPERATIONS = [
'GenericTimelineById', 'GenericTimelineById',
'TrendHistory', 'TrendHistory',
'AboutAccountQuery', 'AboutAccountQuery',
'ListsManagementPageTimeline',
'ListOwnerships',
'ListMemberships',
'ListLatestTweetsTimeline',
] as const; ] as const;
type OperationName = (typeof TARGET_OPERATIONS)[number]; type OperationName = (typeof TARGET_OPERATIONS)[number];
@@ -36,6 +40,7 @@ type OperationName = (typeof TARGET_OPERATIONS)[number];
const DISCOVERY_PAGES = [ const DISCOVERY_PAGES = [
'https://x.com/?lang=en', 'https://x.com/?lang=en',
'https://x.com/explore', 'https://x.com/explore',
'https://x.com/i/lists',
'https://x.com/notifications', 'https://x.com/notifications',
'https://x.com/settings/profile', 'https://x.com/settings/profile',
]; ];
+3 -1
View File
@@ -31,6 +31,8 @@ export const KNOWN_COMMANDS = new Set([
'unfollow', 'unfollow',
'following', 'following',
'followers', 'followers',
'user',
'profiles',
'likes', 'likes',
'lists', 'lists',
'list-timeline', 'list-timeline',
@@ -96,7 +98,7 @@ export function createProgram(ctx: CliContext): Command {
].join('\n\n')}\n\n${ctx.colors.section('Shortcuts')}\n${[ ].join('\n\n')}\n\n${ctx.colors.section('Shortcuts')}\n${[
formatExample('bird <tweet-id-or-url> [--json]', 'Shorthand for `bird read <tweet-id-or-url>`'), formatExample('bird <tweet-id-or-url> [--json]', 'Shorthand for `bird read <tweet-id-or-url>`'),
].join('\n\n')}\n\n${ctx.colors.section('JSON Output')}\n${ctx.colors.muted( ].join('\n\n')}\n\n${ctx.colors.section('JSON Output')}\n${ctx.colors.muted(
` Add ${ctx.colors.option('--json')} to: read, replies, thread, search, mentions, bookmarks, likes, following, followers, about, lists, list-timeline, user-tweets, query-ids`, ` Add ${ctx.colors.option('--json')} to: read, replies, thread, search, mentions, bookmarks, likes, following, followers, user, profiles, about, lists, list-timeline, user-tweets, query-ids`,
)}\n${ctx.colors.muted( )}\n${ctx.colors.muted(
` Add ${ctx.colors.option('--json-full')} to include raw API response in ${ctx.colors.argument('_raw')} field (tweet commands only)`, ` Add ${ctx.colors.option('--json-full')} to include raw API response in ${ctx.colors.argument('_raw')} field (tweet commands only)`,
)}\n${ctx.colors.muted(` (Run ${ctx.colors.command('bird <command> --help')} to see per-command flags.)`)}`, )}\n${ctx.colors.muted(` (Run ${ctx.colors.command('bird <command> --help')} to see per-command flags.)`)}`,
+63 -25
View File
@@ -1,4 +1,5 @@
import type { Command } from 'commander'; import type { Command } from 'commander';
import { parsePaginationFlags } from '../cli/pagination.js';
import type { CliContext } from '../cli/shared.js'; import type { CliContext } from '../cli/shared.js';
import { TwitterClient } from '../lib/twitter-client.js'; import { TwitterClient } from '../lib/twitter-client.js';
@@ -7,36 +8,73 @@ export function registerHomeCommand(program: Command, ctx: CliContext): void {
.command('home') .command('home')
.description('Get your home timeline ("For You" feed)') .description('Get your home timeline ("For You" feed)')
.option('-n, --count <number>', 'Number of tweets to fetch', '20') .option('-n, --count <number>', 'Number of tweets to fetch', '20')
.option('--all', 'Fetch all available pages up to --count')
.option('--max-pages <number>', 'Stop after N pages')
.option('--cursor <string>', 'Resume pagination from a cursor')
.option('--delay <ms>', 'Delay in ms between page fetches', '1000')
.option('--following', 'Get "Following" feed (chronological) instead of "For You"') .option('--following', 'Get "Following" feed (chronological) instead of "For You"')
.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; following?: boolean; json?: boolean; jsonFull?: boolean }) => { .action(
const opts = program.opts(); async (cmdOpts: {
const timeoutMs = ctx.resolveTimeoutFromOptions(opts); count?: string;
const count = Number.parseInt(cmdOpts.count || '20', 10); all?: boolean;
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts); maxPages?: string;
const profileName = ctx.resolveProfileNameFromOptions(opts); cursor?: string;
delay?: string;
following?: boolean;
json?: boolean;
jsonFull?: boolean;
}) => {
const opts = program.opts();
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
const count = Number.parseInt(cmdOpts.count || '20', 10);
const pagination = parsePaginationFlags(cmdOpts, {
maxPagesImpliesPagination: true,
includeDelay: true,
});
if (!pagination.ok) {
console.error(`${ctx.p('err')}${pagination.error}`);
process.exit(1);
}
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
const profileName = ctx.resolveProfileNameFromOptions(opts);
if (!Number.isFinite(count) || count <= 0) { if (!Number.isFinite(count) || count <= 0) {
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`); console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
process.exit(1); process.exit(1);
} }
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs }); const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
const includeRaw = cmdOpts.jsonFull ?? false; const includeRaw = cmdOpts.jsonFull ?? false;
const usePagination = pagination.usePagination;
const fetchOptions = {
includeRaw,
maxPages: pagination.maxPages,
cursor: pagination.cursor,
pageDelayMs: pagination.pageDelayMs,
};
const result = cmdOpts.following const result = cmdOpts.following
? await client.getHomeLatestTimeline(count, { includeRaw }) ? await client.getHomeLatestTimeline(count, fetchOptions)
: await client.getHomeTimeline(count, { includeRaw }); : await client.getHomeTimeline(count, fetchOptions);
if (result.success) { if (result.success) {
const feedType = cmdOpts.following ? 'Following' : 'For You'; const feedType = cmdOpts.following ? 'Following' : 'For You';
const emptyMessage = `No tweets found in ${feedType} timeline.`; const emptyMessage = `No tweets found in ${feedType} timeline.`;
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull); const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
ctx.printTweets(result.tweets, { json: isJson, emptyMessage }); ctx.printTweetsResult(result, {
} else { json: isJson,
console.error(`${ctx.p('err')}Failed to fetch home timeline: ${result.error}`); usePagination,
process.exit(1); emptyMessage,
} });
}); if (result.nextCursor && !cmdOpts.json && !cmdOpts.jsonFull) {
console.error(`${ctx.p('info')}More tweets available. Use --cursor "${result.nextCursor}" to continue.`);
}
} else {
console.error(`${ctx.p('err')}Failed to fetch home timeline: ${result.error}`);
process.exit(1);
}
},
);
} }
+2 -2
View File
@@ -47,13 +47,13 @@ export function registerListsCommand(program: Command, ctx: CliContext): void {
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs }); const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
const result = cmdOpts.memberOf ? await client.getListMemberships(count) : await client.getOwnedLists(count); const result = cmdOpts.memberOf ? await client.getListMemberships(count) : await client.getLists(count);
if (result.success && result.lists) { if (result.success && result.lists) {
if (cmdOpts.json) { if (cmdOpts.json) {
console.log(JSON.stringify(result.lists, null, 2)); console.log(JSON.stringify(result.lists, null, 2));
} else { } else {
const emptyMessage = cmdOpts.memberOf ? 'You are not a member of any lists.' : 'You do not own any lists.'; const emptyMessage = cmdOpts.memberOf ? 'You are not a member of any lists.' : 'No lists found.';
if (result.lists.length === 0) { if (result.lists.length === 0) {
console.log(emptyMessage); console.log(emptyMessage);
} else { } else {
+2 -14
View File
@@ -6,6 +6,7 @@ import {
refreshFeatureOverridesCache, refreshFeatureOverridesCache,
} from '../lib/runtime-features.js'; } from '../lib/runtime-features.js';
import { runtimeQueryIds } from '../lib/runtime-query-ids.js'; import { runtimeQueryIds } from '../lib/runtime-query-ids.js';
import { TARGET_QUERY_ID_OPERATIONS } from '../lib/twitter-client-constants.js';
function countFeatureOverrides(overrides: FeatureOverrides): number { function countFeatureOverrides(overrides: FeatureOverrides): number {
let count = 0; let count = 0;
@@ -27,22 +28,9 @@ export function registerQueryIdsCommand(program: Command, ctx: CliContext): void
.option('--json', 'Output as JSON') .option('--json', 'Output as JSON')
.option('--fresh', 'Force refresh (downloads X client bundles)', false) .option('--fresh', 'Force refresh (downloads X client bundles)', false)
.action(async (cmdOpts: { json?: boolean; fresh?: boolean }) => { .action(async (cmdOpts: { json?: boolean; fresh?: boolean }) => {
const operations = [
'CreateTweet',
'CreateRetweet',
'FavoriteTweet',
'TweetDetail',
'SearchTimeline',
'UserArticlesTweets',
'Bookmarks',
'Following',
'Followers',
'Likes',
];
if (cmdOpts.fresh) { if (cmdOpts.fresh) {
console.error(`${ctx.p('info')}Refreshing GraphQL query IDs…`); console.error(`${ctx.p('info')}Refreshing GraphQL query IDs…`);
await runtimeQueryIds.refresh(operations, { force: true }); await runtimeQueryIds.refresh(TARGET_QUERY_ID_OPERATIONS, { force: true });
console.error(`${ctx.p('info')}Refreshing feature overrides…`); console.error(`${ctx.p('info')}Refreshing feature overrides…`);
await refreshFeatureOverridesCache(); await refreshFeatureOverridesCache();
} }
+11 -3
View File
@@ -1,8 +1,9 @@
import type { Command } from 'commander'; import { type Command, Option } from 'commander';
import { parsePaginationFlags } from '../cli/pagination.js'; import { parsePaginationFlags } from '../cli/pagination.js';
import type { CliContext } from '../cli/shared.js'; import type { CliContext } from '../cli/shared.js';
import { mentionsQueryFromUserOption, normalizeHandle } from '../lib/normalize-handle.js'; import { mentionsQueryFromUserOption, normalizeHandle } from '../lib/normalize-handle.js';
import { TwitterClient } from '../lib/twitter-client.js'; import { TwitterClient } from '../lib/twitter-client.js';
import type { SearchProduct } from '../lib/twitter-client-search.js';
export function registerSearchCommands(program: Command, ctx: CliContext): void { export function registerSearchCommands(program: Command, ctx: CliContext): void {
program program
@@ -13,6 +14,11 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
.option('--all', 'Fetch all search results (paged)') .option('--all', 'Fetch all search results (paged)')
.option('--max-pages <number>', 'Stop after N pages when using --all') .option('--max-pages <number>', 'Stop after N pages when using --all')
.option('--cursor <string>', 'Resume pagination from a cursor') .option('--cursor <string>', 'Resume pagination from a cursor')
.addOption(
new Option('--product <product>', 'Search product')
.choices(['Top', 'Latest'] satisfies SearchProduct[])
.default('Latest'),
)
.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( .action(
@@ -23,6 +29,7 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
all?: boolean; all?: boolean;
maxPages?: string; maxPages?: string;
cursor?: string; cursor?: string;
product?: SearchProduct;
json?: boolean; json?: boolean;
jsonFull?: boolean; jsonFull?: boolean;
}, },
@@ -53,8 +60,9 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth }); const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
const includeRaw = cmdOpts.jsonFull ?? false; const includeRaw = cmdOpts.jsonFull ?? false;
const searchOptions = { includeRaw }; const product = cmdOpts.product ?? 'Latest';
const paginationOptions = { includeRaw, maxPages, cursor: pagination.cursor }; const searchOptions = { includeRaw, product };
const paginationOptions = { includeRaw, maxPages, cursor: pagination.cursor, product };
const result = usePagination const result = usePagination
? await client.getAllSearchResults(query, paginationOptions) ? await client.getAllSearchResults(query, paginationOptions)
: await client.search(query, count, searchOptions); : await client.search(query, count, searchOptions);
+84 -1
View File
@@ -2,7 +2,7 @@ import type { Command } from 'commander';
import type { CliContext } from '../cli/shared.js'; import type { CliContext } from '../cli/shared.js';
import { normalizeHandle } from '../lib/normalize-handle.js'; import { normalizeHandle } from '../lib/normalize-handle.js';
import { TwitterClient } from '../lib/twitter-client.js'; import { TwitterClient } from '../lib/twitter-client.js';
import type { AboutAccountProfile, TwitterUser } from '../lib/twitter-client-types.js'; import type { AboutAccountProfile, TwitterUser, TwitterUserProfile } from '../lib/twitter-client-types.js';
function formatAboutProfile(profile: AboutAccountProfile, ctx: CliContext, handle: string): string[] { function formatAboutProfile(profile: AboutAccountProfile, ctx: CliContext, handle: string): string[] {
const lines: string[] = [`${ctx.p('info')}Account information for @${handle}:`]; const lines: string[] = [`${ctx.p('info')}Account information for @${handle}:`];
@@ -64,6 +64,32 @@ function printUsers(users: TwitterUser[], ctx: CliContext): void {
} }
} }
function printProfile(profile: TwitterUserProfile, ctx: CliContext): void {
console.log(`@${profile.username} (${profile.name})`);
console.log(`${ctx.l('userId')}${profile.id}`);
if (profile.description) {
console.log(` ${profile.description}`);
}
if (profile.location) {
console.log(` Location: ${profile.location}`);
}
if (profile.url) {
console.log(` URL: ${profile.url}`);
}
if (profile.followersCount !== undefined) {
console.log(` ${ctx.p('info')}${profile.followersCount.toLocaleString()} followers`);
}
if (profile.followingCount !== undefined) {
console.log(` ${ctx.p('info')}${profile.followingCount.toLocaleString()} following`);
}
if (profile.verifiedType || profile.verified) {
console.log(` Verified: ${profile.verifiedType ?? 'yes'}`);
}
if (profile.affiliation?.description) {
console.log(` Affiliation: ${profile.affiliation.description}`);
}
}
async function resolveUserIdOrExit( async function resolveUserIdOrExit(
client: TwitterClient, client: TwitterClient,
requestedUserId: string | undefined, requestedUserId: string | undefined,
@@ -216,6 +242,63 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
fetch: (client, userId, count, cursor) => client.getFollowers(userId, count, cursor), fetch: (client, userId, count, cursor) => client.getFollowers(userId, count, cursor),
}); });
program
.command('user')
.description('Resolve a rich user profile by handle or user ID')
.argument('<target>', 'Username (with or without @) or numeric user ID')
.option('--json', 'Output as JSON')
.action(async (target: string, cmdOpts: { json?: boolean }) => {
const opts = program.opts();
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
const profileName = ctx.resolveProfileNameFromOptions(opts);
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
const result = await client.getUserProfile(target);
if (!result.success) {
console.error(`${ctx.p('err')}Failed to resolve user: ${result.error}`);
process.exit(1);
}
if (cmdOpts.json) {
console.log(JSON.stringify(result.profile, null, 2));
return;
}
printProfile(result.profile, ctx);
});
program
.command('profiles')
.description('Resolve rich user profiles by handle or user ID')
.argument('<targets...>', 'Usernames or numeric user IDs')
.option('--json', 'Output as JSON')
.action(async (targets: string[], cmdOpts: { json?: boolean }) => {
const opts = program.opts();
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
const profileName = ctx.resolveProfileNameFromOptions(opts);
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
const result = await client.getUserProfiles(targets);
const users = result.results.flatMap((item) => ('profile' in item ? [item.profile] : []));
const errors = result.results.flatMap((item) =>
'error' in item ? [{ target: item.target, error: item.error }] : [],
);
if (cmdOpts.json) {
console.log(JSON.stringify({ users, errors }, null, 2));
return;
}
for (const profile of users) {
printProfile(profile, ctx);
console.log('──────────────────────────────────────────────────');
}
for (const error of errors) {
console.error(`${ctx.p('err')}${error.target}: ${error.error}`);
}
if (users.length === 0 && errors.length > 0) {
process.exit(1);
}
});
program program
.command('likes') .command('likes')
.description('Get your liked tweets') .description('Get your liked tweets')
+2 -12
View File
@@ -1,17 +1,7 @@
{ {
"global": { "global": {
"responsive_web_grok_annotations_enabled": false, "responsive_web_grok_annotations_enabled": false,
"post_ctas_fetch_enabled": true, "post_ctas_fetch_enabled": true
"responsive_web_graphql_exclude_directive_enabled": true
}, },
"sets": { "sets": {}
"lists": {
"blue_business_profile_image_shape_enabled": true,
"tweetypie_unmention_optimization_enabled": true,
"responsive_web_text_conversations_enabled": false,
"interactive_text_enabled": true,
"vibe_api_enabled": true,
"responsive_web_twitter_blue_verified_badge_is_enabled": true
}
}
} }
+5 -1
View File
@@ -11,7 +11,11 @@ export {
} from './twitter-client.js'; } from './twitter-client.js';
export type { HomeTimelineFetchOptions } from './twitter-client-home.js'; export type { HomeTimelineFetchOptions } from './twitter-client-home.js';
export type { ExploreTab, NewsFetchOptions, NewsItem, NewsResult } from './twitter-client-news.js'; export type { ExploreTab, NewsFetchOptions, NewsItem, NewsResult } from './twitter-client-news.js';
export type { SearchFetchOptions } from './twitter-client-search.js'; export type {
SearchFetchOptions,
SearchPaginationOptions,
SearchProduct,
} from './twitter-client-search.js';
export type { TimelineFetchOptions } from './twitter-client-timelines.js'; export type { TimelineFetchOptions } from './twitter-client-timelines.js';
export type { TweetFetchOptions } from './twitter-client-tweet-detail.js'; export type { TweetFetchOptions } from './twitter-client-tweet-detail.js';
export type { export type {
+5 -1
View File
@@ -16,5 +16,9 @@
"ExplorePage": "kheAINB_4pzRDqkzG3K-ng", "ExplorePage": "kheAINB_4pzRDqkzG3K-ng",
"GenericTimelineById": "uGSr7alSjR9v6QJAIaqSKQ", "GenericTimelineById": "uGSr7alSjR9v6QJAIaqSKQ",
"TrendHistory": "Sj4T-jSB9pr0Mxtsc1UKZQ", "TrendHistory": "Sj4T-jSB9pr0Mxtsc1UKZQ",
"AboutAccountQuery": "zs_jFPFT78rBpXv9Z3U2YQ" "AboutAccountQuery": "zs_jFPFT78rBpXv9Z3U2YQ",
"ListsManagementPageTimeline": "I96vj5eyw1D9g_NA0wWj3Q",
"ListOwnerships": "N_9HejNT9Amo1tDF7Gb_TQ",
"ListMemberships": "EPnwxyczkTMNNqPjlCBP9Q",
"ListLatestTweetsTimeline": "K77PSxWq_St4HLusAV9nVg"
} }
+1
View File
@@ -8,6 +8,7 @@ const DEFAULT_TTL_MS: number = 24 * 60 * 60 * 1000;
const DISCOVERY_PAGES: string[] = [ const DISCOVERY_PAGES: string[] = [
'https://x.com/?lang=en', 'https://x.com/?lang=en',
'https://x.com/explore', 'https://x.com/explore',
'https://x.com/i/lists',
'https://x.com/notifications', 'https://x.com/notifications',
'https://x.com/settings/profile', 'https://x.com/settings/profile',
]; ];
+6 -4
View File
@@ -28,10 +28,10 @@ export const FALLBACK_QUERY_IDS = {
Followers: 'kuFUYP9eV1FPoEy4N-pi7w', Followers: 'kuFUYP9eV1FPoEy4N-pi7w',
Likes: 'JR2gceKucIKcVNB_9JkhsA', Likes: 'JR2gceKucIKcVNB_9JkhsA',
BookmarkFolderTimeline: 'KJIQpsvxrTfRIlbaRIySHQ', BookmarkFolderTimeline: 'KJIQpsvxrTfRIlbaRIySHQ',
ListOwnerships: 'wQcOSjSQ8NtgxIwvYl1lMg', ListsManagementPageTimeline: 'I96vj5eyw1D9g_NA0wWj3Q',
ListMemberships: 'BlEXXdARdSeL_0KyKHHvvg', ListOwnerships: 'N_9HejNT9Amo1tDF7Gb_TQ',
ListLatestTweetsTimeline: '2TemLyqrMpTeAmysdbnVqw', ListMemberships: 'EPnwxyczkTMNNqPjlCBP9Q',
ListByRestId: 'wXzyA5vM_aVkBL9G8Vp3kw', ListLatestTweetsTimeline: 'K77PSxWq_St4HLusAV9nVg',
HomeTimeline: 'edseUwk9sP5Phz__9TIRnA', HomeTimeline: 'edseUwk9sP5Phz__9TIRnA',
HomeLatestTimeline: 'iOEZpOdfekFsxSlPQCQtPg', HomeLatestTimeline: 'iOEZpOdfekFsxSlPQCQtPg',
ExploreSidebar: 'lpSN4M6qpimkF4nRFPE3nQ', ExploreSidebar: 'lpSN4M6qpimkF4nRFPE3nQ',
@@ -39,6 +39,8 @@ export const FALLBACK_QUERY_IDS = {
GenericTimelineById: 'uGSr7alSjR9v6QJAIaqSKQ', GenericTimelineById: 'uGSr7alSjR9v6QJAIaqSKQ',
TrendHistory: 'Sj4T-jSB9pr0Mxtsc1UKZQ', TrendHistory: 'Sj4T-jSB9pr0Mxtsc1UKZQ',
AboutAccountQuery: 'zs_jFPFT78rBpXv9Z3U2YQ', AboutAccountQuery: 'zs_jFPFT78rBpXv9Z3U2YQ',
UserByScreenName: 'IGgvgiOx4QZndDHuD3x9TQ',
UserByRestId: 'VQfQ9wwYdk6j_u2O4vt64Q',
} as const; } as const;
export type OperationName = keyof typeof FALLBACK_QUERY_IDS; export type OperationName = keyof typeof FALLBACK_QUERY_IDS;
+16 -19
View File
@@ -180,50 +180,47 @@ export function buildLikesFeatures(): Record<string, boolean> {
} }
export function buildListsFeatures(): Record<string, boolean> { export function buildListsFeatures(): Record<string, boolean> {
return applyFeatureOverrides('lists', { return {
rweb_video_screen_enabled: true, rweb_video_screen_enabled: false,
rweb_cashtags_enabled: true,
profile_label_improvements_pcf_label_in_post_enabled: true, profile_label_improvements_pcf_label_in_post_enabled: true,
responsive_web_profile_redirect_enabled: true, responsive_web_profile_redirect_enabled: false,
rweb_tipjar_consumption_enabled: true, rweb_tipjar_consumption_enabled: false,
verified_phone_label_enabled: false, verified_phone_label_enabled: false,
creator_subscriptions_tweet_preview_api_enabled: true, creator_subscriptions_tweet_preview_api_enabled: true,
responsive_web_graphql_timeline_navigation_enabled: true, responsive_web_graphql_timeline_navigation_enabled: true,
responsive_web_graphql_exclude_directive_enabled: true,
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false, responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
premium_content_api_read_enabled: false, premium_content_api_read_enabled: false,
communities_web_enable_tweet_community_results_fetch: true, communities_web_enable_tweet_community_results_fetch: true,
c9s_tweet_anatomy_moderator_badge_enabled: true, c9s_tweet_anatomy_moderator_badge_enabled: true,
responsive_web_grok_analyze_button_fetch_trends_enabled: false, responsive_web_grok_analyze_button_fetch_trends_enabled: false,
responsive_web_grok_analyze_post_followups_enabled: false, responsive_web_grok_analyze_post_followups_enabled: true,
responsive_web_grok_annotations_enabled: false, rweb_cashtags_composer_attachment_enabled: true,
responsive_web_jetfuel_frame: true, responsive_web_jetfuel_frame: true,
post_ctas_fetch_enabled: true,
responsive_web_grok_share_attachment_enabled: true, responsive_web_grok_share_attachment_enabled: true,
responsive_web_grok_annotations_enabled: true,
articles_preview_enabled: true, articles_preview_enabled: true,
responsive_web_edit_tweet_api_enabled: true, responsive_web_edit_tweet_api_enabled: true,
rweb_conversational_replies_downvote_enabled: false,
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true, graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
view_counts_everywhere_api_enabled: true, view_counts_everywhere_api_enabled: true,
longform_notetweets_consumption_enabled: true, longform_notetweets_consumption_enabled: true,
responsive_web_twitter_article_tweet_consumption_enabled: true, responsive_web_twitter_article_tweet_consumption_enabled: true,
tweet_awards_web_tipping_enabled: false, content_disclosure_indicator_enabled: true,
responsive_web_grok_show_grok_translated_post: false, content_disclosure_ai_generated_indicator_enabled: true,
responsive_web_grok_show_grok_translated_post: true,
responsive_web_grok_analysis_button_from_backend: true, responsive_web_grok_analysis_button_from_backend: true,
creator_subscriptions_quote_tweet_preview_enabled: false, post_ctas_fetch_enabled: true,
freedom_of_speech_not_reach_fetch_enabled: true, freedom_of_speech_not_reach_fetch_enabled: true,
standardized_nudges_misinfo: true, standardized_nudges_misinfo: true,
tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true, tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,
longform_notetweets_rich_text_read_enabled: true, longform_notetweets_rich_text_read_enabled: true,
longform_notetweets_inline_media_enabled: true, longform_notetweets_inline_media_enabled: false,
responsive_web_grok_image_annotation_enabled: true, responsive_web_grok_image_annotation_enabled: true,
responsive_web_grok_imagine_annotation_enabled: true, responsive_web_grok_imagine_annotation_enabled: true,
responsive_web_grok_community_note_auto_translation_is_enabled: false, responsive_web_grok_community_note_auto_translation_is_enabled: true,
responsive_web_enhance_cards_enabled: false, responsive_web_enhance_cards_enabled: false,
blue_business_profile_image_shape_enabled: false, };
responsive_web_text_conversations_enabled: false,
tweetypie_unmention_optimization_enabled: true,
vibe_api_enabled: false,
interactive_text_enabled: false,
});
} }
export function buildHomeTimelineFeatures(): Record<string, boolean> { export function buildHomeTimelineFeatures(): Record<string, boolean> {
+32 -4
View File
@@ -14,6 +14,12 @@ function isQueryIdMismatch(errors: Array<{ message?: string }>): boolean {
export interface HomeTimelineFetchOptions { export interface HomeTimelineFetchOptions {
/** Include raw GraphQL response in `_raw` field */ /** Include raw GraphQL response in `_raw` field */
includeRaw?: boolean; includeRaw?: boolean;
/** Starting cursor for pagination */
cursor?: string;
/** Maximum number of pages to fetch */
maxPages?: number;
/** Delay in milliseconds between page fetches */
pageDelayMs?: number;
} }
export interface TwitterClientHomeMethods { export interface TwitterClientHomeMethods {
@@ -64,7 +70,17 @@ export function withHome<TBase extends AbstractConstructor<TwitterClientBase>>(
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;
let nextCursor: string | undefined;
let pagesFetched = 0;
const effectiveMaxPages =
options.maxPages !== undefined && Number.isFinite(options.maxPages) && options.maxPages > 0
? Math.floor(options.maxPages)
: Number.POSITIVE_INFINITY;
const pageDelayMs =
options.pageDelayMs !== undefined && Number.isFinite(options.pageDelayMs) && options.pageDelayMs > 0
? options.pageDelayMs
: 0;
const fetchPage = async (pageCount: number, pageCursor?: string) => { const fetchPage = async (pageCount: number, pageCursor?: string) => {
let lastError: string | undefined; let lastError: string | undefined;
@@ -168,11 +184,16 @@ export function withHome<TBase extends AbstractConstructor<TwitterClientBase>>(
}; };
while (tweets.length < count) { while (tweets.length < count) {
if (pagesFetched > 0 && pageDelayMs > 0) {
await this.sleep(pageDelayMs);
}
const pageCount = Math.min(pageSize, count - tweets.length); const pageCount = Math.min(pageSize, count - 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) {
@@ -187,13 +208,20 @@ export function withHome<TBase extends AbstractConstructor<TwitterClientBase>>(
} }
} }
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 (pagesFetched >= effectiveMaxPages) {
nextCursor = pageCursor;
break;
}
cursor = pageCursor;
nextCursor = pageCursor;
} }
return { success: true, tweets }; return { success: true, tweets, nextCursor };
} }
} }
+197 -223
View File
@@ -9,6 +9,7 @@ import type { GraphqlTweetResult, ListsResult, SearchResult, TweetData, TwitterL
import { extractCursorFromInstructions, parseTweetsFromInstructions } from './twitter-client-utils.js'; import { extractCursorFromInstructions, parseTweetsFromInstructions } from './twitter-client-utils.js';
export interface TwitterClientListMethods { export interface TwitterClientListMethods {
getLists(count?: number): Promise<ListsResult>;
getOwnedLists(count?: number): Promise<ListsResult>; getOwnedLists(count?: number): Promise<ListsResult>;
getListMemberships(count?: number): Promise<ListsResult>; getListMemberships(count?: number): Promise<ListsResult>;
getListTimeline(listId: string, count?: number, options?: TimelineFetchOptions): Promise<SearchResult>; getListTimeline(listId: string, count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
@@ -22,7 +23,7 @@ interface GraphqlListResult {
member_count?: number; member_count?: number;
subscriber_count?: number; subscriber_count?: number;
mode?: string; mode?: string;
created_at?: string; created_at?: string | number;
user_results?: { user_results?: {
result?: { result?: {
rest_id?: string; rest_id?: string;
@@ -30,16 +31,73 @@ interface GraphqlListResult {
screen_name?: string; screen_name?: string;
name?: string; name?: string;
}; };
core?: {
screen_name?: string;
name?: string;
};
}; };
}; };
} }
interface GraphqlListItem {
itemContent?: {
list?: GraphqlListResult;
};
}
interface GraphqlListInstruction {
entries?: Array<{
content?: GraphqlListItem & {
clientEventInfo?: {
component?: string;
};
items?: Array<{
item?: GraphqlListItem;
}>;
};
}>;
}
interface GraphqlListsResponse {
data?: {
user?: {
result?: {
__typename?: string;
timeline?: {
timeline?: {
instructions?: GraphqlListInstruction[];
};
};
};
};
viewer?: {
list_management_timeline?: {
timeline?: {
instructions?: GraphqlListInstruction[];
};
};
};
};
errors?: Array<{ message: string }>;
}
function parseList(listResult: GraphqlListResult): TwitterList | null { function parseList(listResult: GraphqlListResult): TwitterList | null {
if (!listResult.id_str || !listResult.name) { if (!listResult.id_str || !listResult.name) {
return null; return null;
} }
const owner = listResult.user_results?.result; const owner = listResult.user_results?.result;
const ownerProfile = owner?.core ?? owner?.legacy;
const createdAtDate =
typeof listResult.created_at === 'number' && Number.isFinite(listResult.created_at)
? new Date(listResult.created_at)
: null;
const createdAt =
createdAtDate && !Number.isNaN(createdAtDate.getTime())
? createdAtDate.toISOString()
: typeof listResult.created_at === 'string'
? listResult.created_at
: undefined;
return { return {
id: listResult.id_str, id: listResult.id_str,
name: listResult.name, name: listResult.name,
@@ -47,51 +105,49 @@ function parseList(listResult: GraphqlListResult): TwitterList | null {
memberCount: listResult.member_count, memberCount: listResult.member_count,
subscriberCount: listResult.subscriber_count, subscriberCount: listResult.subscriber_count,
isPrivate: listResult.mode?.toLowerCase() === 'private', isPrivate: listResult.mode?.toLowerCase() === 'private',
createdAt: listResult.created_at, createdAt,
owner: owner owner: owner
? { ? {
id: owner.rest_id ?? '', id: owner.rest_id ?? '',
username: owner.legacy?.screen_name ?? '', username: ownerProfile?.screen_name ?? '',
name: owner.legacy?.name ?? '', name: ownerProfile?.name ?? '',
} }
: undefined, : undefined,
}; };
} }
function parseListsFromInstructions( function parseListsFromInstructions(
instructions: instructions: GraphqlListInstruction[] | undefined,
| Array<{ component?: string,
entries?: Array<{
content?: {
itemContent?: {
list?: GraphqlListResult;
};
};
}>;
}>
| undefined,
): TwitterList[] { ): TwitterList[] {
const lists: TwitterList[] = []; const lists = new Map<string, TwitterList>();
if (!instructions) { if (!instructions) {
return lists; return [];
} }
for (const instruction of instructions) { const addList = (listResult: GraphqlListResult | undefined) => {
if (!instruction.entries) { if (!listResult) {
continue; return;
} }
for (const entry of instruction.entries) { const parsed = parseList(listResult);
const listResult = entry.content?.itemContent?.list; if (parsed) {
if (listResult) { lists.set(parsed.id, parsed);
const parsed = parseList(listResult); }
if (parsed) { };
lists.push(parsed);
} for (const instruction of instructions) {
for (const entry of instruction.entries ?? []) {
if (component && entry.content?.clientEventInfo?.component !== component) {
continue;
}
addList(entry.content?.itemContent?.list);
for (const item of entry.content?.items ?? []) {
addList(item.item?.itemContent?.list);
} }
} }
} }
return lists; return Array.from(lists.values());
} }
export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>( export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
@@ -103,19 +159,108 @@ export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
super(...args); super(...args);
} }
private async getListsManagementQueryIds(): Promise<string[]> {
return [await this.getQueryId('ListsManagementPageTimeline')];
}
private async getListOwnershipsQueryIds(): Promise<string[]> { private async getListOwnershipsQueryIds(): Promise<string[]> {
const primary = await this.getQueryId('ListOwnerships'); return [await this.getQueryId('ListOwnerships')];
return Array.from(new Set([primary, 'wQcOSjSQ8NtgxIwvYl1lMg']));
} }
private async getListMembershipsQueryIds(): Promise<string[]> { private async getListMembershipsQueryIds(): Promise<string[]> {
const primary = await this.getQueryId('ListMemberships'); return [await this.getQueryId('ListMemberships')];
return Array.from(new Set([primary, 'BlEXXdARdSeL_0KyKHHvvg']));
} }
private async getListTimelineQueryIds(): Promise<string[]> { private async getListTimelineQueryIds(): Promise<string[]> {
const primary = await this.getQueryId('ListLatestTweetsTimeline'); return [await this.getQueryId('ListLatestTweetsTimeline')];
return Array.from(new Set([primary, '2TemLyqrMpTeAmysdbnVqw'])); }
private async fetchListsOperation(
operationName: 'ListsManagementPageTimeline' | 'ListOwnerships' | 'ListMemberships',
variables: Record<string, unknown>,
getQueryIds: () => Promise<string[]>,
selectInstructions: (data: GraphqlListsResponse) => GraphqlListInstruction[] | undefined,
component?: string,
): Promise<ListsResult> {
const params = new URLSearchParams({
variables: JSON.stringify(variables),
features: JSON.stringify(buildListsFeatures()),
});
const tryOnce = async () => {
let lastError: string | undefined;
let had404 = false;
for (const queryId of await getQueryIds()) {
const url = `${TWITTER_API_BASE}/${queryId}/${operationName}?${params.toString()}`;
try {
const response = await this.fetchWithTimeout(url, {
method: 'GET',
headers: this.getHeaders(),
});
if (response.status === 404) {
had404 = true;
lastError = `HTTP ${response.status}`;
continue;
}
if (!response.ok) {
const text = await response.text();
return { success: false as const, error: `HTTP ${response.status}: ${text.slice(0, 200)}`, had404 };
}
const data = (await response.json()) as GraphqlListsResponse;
const instructions = selectInstructions(data);
if (instructions) {
return { success: true as const, lists: parseListsFromInstructions(instructions, component), had404 };
}
if (data.data?.user?.result?.__typename === 'UserUnavailable') {
return { success: false as const, error: 'User unavailable', had404 };
}
if (data.errors?.length) {
return { success: false as const, error: data.errors.map((error) => error.message).join(', '), had404 };
}
return { success: false as const, error: `Missing ${operationName} timeline`, had404 };
} catch (error) {
lastError = error instanceof Error ? error.message : String(error);
}
}
return { success: false as const, error: lastError ?? `Unknown error fetching ${operationName}`, had404 };
};
const firstAttempt = await tryOnce();
if (firstAttempt.success) {
return { success: true, lists: firstAttempt.lists };
}
if (!firstAttempt.had404) {
return { success: false, error: firstAttempt.error };
}
await this.refreshQueryIds();
const secondAttempt = await tryOnce();
return secondAttempt.success
? { success: true, lists: secondAttempt.lists }
: { success: false, error: secondAttempt.error };
}
/**
* Get the lists shown on the authenticated user's Lists page.
*/
async getLists(count = 100): Promise<ListsResult> {
return this.fetchListsOperation(
'ListsManagementPageTimeline',
{ count },
() => this.getListsManagementQueryIds(),
(data) => data.data?.viewer?.list_management_timeline?.timeline?.instructions,
'suggest_owned_subscribed_list',
);
} }
/** /**
@@ -127,99 +272,16 @@ export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
return { success: false, error: userResult.error ?? 'Could not determine current user' }; return { success: false, error: userResult.error ?? 'Could not determine current user' };
} }
const variables = { return this.fetchListsOperation(
userId: userResult.user.id, 'ListOwnerships',
count, {
isListMembershipShown: true, userId: userResult.user.id,
isListMemberTargetUserId: userResult.user.id, isListMemberTargetUserId: userResult.user.id,
}; count,
},
const features = buildListsFeatures(); () => this.getListOwnershipsQueryIds(),
(data) => data.data?.user?.result?.timeline?.timeline?.instructions,
const params = new URLSearchParams({ );
variables: JSON.stringify(variables),
features: JSON.stringify(features),
});
const tryOnce = async () => {
let lastError: string | undefined;
let had404 = false;
const queryIds = await this.getListOwnershipsQueryIds();
for (const queryId of queryIds) {
const url = `${TWITTER_API_BASE}/${queryId}/ListOwnerships?${params.toString()}`;
try {
const response = await this.fetchWithTimeout(url, {
method: 'GET',
headers: this.getHeaders(),
});
if (response.status === 404) {
had404 = true;
lastError = `HTTP ${response.status}`;
continue;
}
if (!response.ok) {
const text = await response.text();
return { success: false as const, error: `HTTP ${response.status}: ${text.slice(0, 200)}`, had404 };
}
const data = (await response.json()) as {
data?: {
user?: {
result?: {
timeline?: {
timeline?: {
instructions?: Array<{
entries?: Array<{
content?: {
itemContent?: {
list?: GraphqlListResult;
};
};
}>;
}>;
};
};
};
};
};
errors?: Array<{ message: string }>;
};
if (data.errors && data.errors.length > 0) {
return { success: false as const, error: data.errors.map((e) => e.message).join(', '), had404 };
}
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
const lists = parseListsFromInstructions(instructions);
return { success: true as const, lists, had404 };
} catch (error) {
lastError = error instanceof Error ? error.message : String(error);
}
}
return { success: false as const, error: lastError ?? 'Unknown error fetching owned lists', had404 };
};
const firstAttempt = await tryOnce();
if (firstAttempt.success) {
return { success: true, lists: firstAttempt.lists };
}
if (firstAttempt.had404) {
await this.refreshQueryIds();
const secondAttempt = await tryOnce();
if (secondAttempt.success) {
return { success: true, lists: secondAttempt.lists };
}
return { success: false, error: secondAttempt.error };
}
return { success: false, error: firstAttempt.error };
} }
/** /**
@@ -231,99 +293,12 @@ export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
return { success: false, error: userResult.error ?? 'Could not determine current user' }; return { success: false, error: userResult.error ?? 'Could not determine current user' };
} }
const variables = { return this.fetchListsOperation(
userId: userResult.user.id, 'ListMemberships',
count, { userId: userResult.user.id, count },
isListMembershipShown: true, () => this.getListMembershipsQueryIds(),
isListMemberTargetUserId: userResult.user.id, (data) => data.data?.user?.result?.timeline?.timeline?.instructions,
}; );
const features = buildListsFeatures();
const params = new URLSearchParams({
variables: JSON.stringify(variables),
features: JSON.stringify(features),
});
const tryOnce = async () => {
let lastError: string | undefined;
let had404 = false;
const queryIds = await this.getListMembershipsQueryIds();
for (const queryId of queryIds) {
const url = `${TWITTER_API_BASE}/${queryId}/ListMemberships?${params.toString()}`;
try {
const response = await this.fetchWithTimeout(url, {
method: 'GET',
headers: this.getHeaders(),
});
if (response.status === 404) {
had404 = true;
lastError = `HTTP ${response.status}`;
continue;
}
if (!response.ok) {
const text = await response.text();
return { success: false as const, error: `HTTP ${response.status}: ${text.slice(0, 200)}`, had404 };
}
const data = (await response.json()) as {
data?: {
user?: {
result?: {
timeline?: {
timeline?: {
instructions?: Array<{
entries?: Array<{
content?: {
itemContent?: {
list?: GraphqlListResult;
};
};
}>;
}>;
};
};
};
};
};
errors?: Array<{ message: string }>;
};
if (data.errors && data.errors.length > 0) {
return { success: false as const, error: data.errors.map((e) => e.message).join(', '), had404 };
}
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
const lists = parseListsFromInstructions(instructions);
return { success: true as const, lists, had404 };
} catch (error) {
lastError = error instanceof Error ? error.message : String(error);
}
}
return { success: false as const, error: lastError ?? 'Unknown error fetching list memberships', had404 };
};
const firstAttempt = await tryOnce();
if (firstAttempt.success) {
return { success: true, lists: firstAttempt.lists };
}
if (firstAttempt.had404) {
await this.refreshQueryIds();
const secondAttempt = await tryOnce();
if (secondAttempt.success) {
return { success: true, lists: secondAttempt.lists };
}
return { success: false, error: secondAttempt.error };
}
return { success: false, error: firstAttempt.error };
} }
/** /**
@@ -416,11 +391,10 @@ export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
errors?: Array<{ message: string }>; errors?: Array<{ message: string }>;
}; };
if (data.errors && data.errors.length > 0) { const instructions = data.data?.list?.tweets_timeline?.timeline?.instructions;
if (!instructions && data.errors?.length) {
return { success: false as const, error: data.errors.map((e) => e.message).join(', '), had404 }; return { success: false as const, error: data.errors.map((e) => e.message).join(', '), had404 };
} }
const instructions = data.data?.list?.tweets_timeline?.timeline?.instructions;
const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw }); const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
const nextCursor = extractCursorFromInstructions(instructions); const nextCursor = extractCursorFromInstructions(instructions);
+6 -2
View File
@@ -6,10 +6,14 @@ import { extractCursorFromInstructions, parseTweetsFromInstructions } from './tw
const RAW_QUERY_MISSING_REGEX = /must be defined/i; const RAW_QUERY_MISSING_REGEX = /must be defined/i;
export type SearchProduct = 'Top' | 'Latest';
/** Options for search methods */ /** Options for search methods */
export interface SearchFetchOptions { export interface SearchFetchOptions {
/** Include raw GraphQL response in `_raw` field */ /** Include raw GraphQL response in `_raw` field */
includeRaw?: boolean; includeRaw?: boolean;
/** Search result ranking (default: Latest) */
product?: SearchProduct;
} }
/** Options for paged search methods */ /** Options for paged search methods */
@@ -80,7 +84,7 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
let cursor: string | undefined = options.cursor; let cursor: string | undefined = options.cursor;
let nextCursor: string | undefined; let nextCursor: string | undefined;
let pagesFetched = 0; let pagesFetched = 0;
const { includeRaw = false, maxPages } = options; const { includeRaw = false, maxPages, product = 'Latest' } = options;
const fetchPage = async (pageCount: number, pageCursor?: string) => { const fetchPage = async (pageCount: number, pageCursor?: string) => {
let lastError: string | undefined; let lastError: string | undefined;
@@ -92,7 +96,7 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
rawQuery: query, rawQuery: query,
count: pageCount, count: pageCount,
querySource: 'typed_query', querySource: 'typed_query',
product: 'Latest', product,
...(pageCursor ? { cursor: pageCursor } : {}), ...(pageCursor ? { cursor: pageCursor } : {}),
}; };
+57
View File
@@ -47,11 +47,15 @@ export type GraphqlTweetResult = {
legacy?: { legacy?: {
screen_name?: string; screen_name?: string;
name?: string; name?: string;
profile_image_url_https?: string;
}; };
core?: { core?: {
screen_name?: string; screen_name?: string;
name?: string; name?: string;
}; };
avatar?: {
image_url?: string;
};
}; };
}; };
}; };
@@ -263,6 +267,7 @@ export interface TweetData {
author: { author: {
username: string; username: string;
name: string; name: string;
profileImageUrl?: string;
}; };
authorId?: string; authorId?: string;
createdAt?: string; createdAt?: string;
@@ -334,6 +339,58 @@ export interface TwitterUser {
createdAt?: string; createdAt?: string;
} }
export interface TwitterUserUrlEntity {
url?: string;
expanded_url?: string;
display_url?: string;
}
export interface TwitterUserProfile {
id: string;
username: string;
name: string;
description?: string;
location?: string;
url?: string;
verified?: boolean;
verifiedType?: string;
followersCount?: number;
followingCount?: number;
profileImageUrl?: string;
createdAt?: string;
entities?: Record<string, unknown>;
affiliation?: {
description?: string;
url?: string;
badgeUrl?: string;
};
raw?: unknown;
}
export type UserProfileResult =
| {
success: true;
profile: TwitterUserProfile;
}
| {
success: false;
error: string;
};
export type UserProfilesResult = {
success: true;
results: Array<
| {
target: string;
profile: TwitterUserProfile;
}
| {
target: string;
error: string;
}
>;
};
export interface FollowingResult { export interface FollowingResult {
success: boolean; success: boolean;
users?: TwitterUser[]; users?: TwitterUser[];
+265 -1
View File
@@ -1,7 +1,14 @@
import { normalizeHandle } from './normalize-handle.js'; import { normalizeHandle } from './normalize-handle.js';
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js'; import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
import { TWITTER_API_BASE } from './twitter-client-constants.js'; import { TWITTER_API_BASE } from './twitter-client-constants.js';
import type { AboutAccountResult } from './twitter-client-types.js'; import type {
AboutAccountResult,
TwitterUserProfile,
UserProfileResult,
UserProfilesResult,
} from './twitter-client-types.js';
const NUMERIC_USER_ID_PATTERN = /^[0-9]+$/;
/** Result of username to userId lookup */ /** Result of username to userId lookup */
export interface UserLookupResult { export interface UserLookupResult {
@@ -14,9 +21,119 @@ export interface UserLookupResult {
export interface TwitterClientUserLookupMethods { export interface TwitterClientUserLookupMethods {
getUserIdByUsername(username: string): Promise<UserLookupResult>; getUserIdByUsername(username: string): Promise<UserLookupResult>;
getUserProfile(target: string): Promise<UserProfileResult>;
getUserProfiles(targets: string[]): Promise<UserProfilesResult>;
getUserAboutAccount(username: string): Promise<AboutAccountResult>; getUserAboutAccount(username: string): Promise<AboutAccountResult>;
} }
type UserProfileGraphqlResult = {
__typename?: string;
rest_id?: string;
is_blue_verified?: boolean;
avatar?: {
image_url?: string;
};
verification_info?: unknown;
legacy?: {
screen_name?: string;
name?: string;
description?: string;
location?: string;
url?: string;
created_at?: string;
verified?: boolean;
verified_type?: string;
followers_count?: number;
friends_count?: number;
profile_image_url_https?: string;
entities?: Record<string, unknown>;
};
core?: {
screen_name?: string;
name?: string;
created_at?: string;
};
location?: {
location?: string;
};
affiliates_highlighted_label?: {
label?: {
description?: string;
url?: { url?: string };
badge?: { url?: string };
};
};
user?: UserProfileGraphqlResult;
};
function isNumericUserId(value: string): boolean {
return NUMERIC_USER_ID_PATTERN.test(value.trim());
}
function firstExpandedUrl(entities: Record<string, unknown> | undefined): string | undefined {
const urlEntity = entities?.url;
if (!urlEntity || typeof urlEntity !== 'object') {
return undefined;
}
const urls = (urlEntity as { urls?: unknown }).urls;
if (!Array.isArray(urls)) {
return undefined;
}
const first = urls[0];
if (!first || typeof first !== 'object') {
return undefined;
}
const expandedUrl = (first as { expanded_url?: unknown }).expanded_url;
const url = (first as { url?: unknown }).url;
return typeof expandedUrl === 'string' ? expandedUrl : typeof url === 'string' ? url : undefined;
}
function normalizeGraphqlUserResult(result: UserProfileGraphqlResult): TwitterUserProfile | null {
const user = result.__typename === 'UserWithVisibilityResults' && result.user ? result.user : result;
if (user.__typename === 'UserUnavailable') {
return null;
}
const id = user.rest_id;
const username = user.legacy?.screen_name ?? user.core?.screen_name;
if (!id || !username) {
return null;
}
const entities = user.legacy?.entities;
const location = user.legacy?.location ?? user.location?.location;
const createdAt = user.legacy?.created_at ?? user.core?.created_at;
const label = user.affiliates_highlighted_label?.label;
const affiliation =
label?.description || label?.url?.url || label?.badge?.url
? {
...(label.description ? { description: label.description } : {}),
...(label.url?.url ? { url: label.url.url } : {}),
...(label.badge?.url ? { badgeUrl: label.badge.url } : {}),
}
: undefined;
return {
id,
username,
name: user.legacy?.name ?? user.core?.name ?? username,
...(user.legacy?.description ? { description: user.legacy.description } : {}),
...(location ? { location } : {}),
...(firstExpandedUrl(entities) ? { url: firstExpandedUrl(entities) } : {}),
...(typeof user.is_blue_verified === 'boolean' || typeof user.legacy?.verified === 'boolean'
? { verified: Boolean(user.is_blue_verified || user.legacy?.verified) }
: {}),
...(user.legacy?.verified_type ? { verifiedType: user.legacy.verified_type } : {}),
...(typeof user.legacy?.followers_count === 'number' ? { followersCount: user.legacy.followers_count } : {}),
...(typeof user.legacy?.friends_count === 'number' ? { followingCount: user.legacy.friends_count } : {}),
...(user.avatar?.image_url || user.legacy?.profile_image_url_https
? { profileImageUrl: user.avatar?.image_url ?? user.legacy?.profile_image_url_https }
: {}),
...(createdAt ? { createdAt } : {}),
...(entities ? { entities } : {}),
...(affiliation ? { affiliation } : {}),
raw: user,
};
}
export function withUserLookup<TBase extends AbstractConstructor<TwitterClientBase>>( export function withUserLookup<TBase extends AbstractConstructor<TwitterClientBase>>(
Base: TBase, Base: TBase,
): Mixin<TBase, TwitterClientUserLookupMethods> { ): Mixin<TBase, TwitterClientUserLookupMethods> {
@@ -208,6 +325,153 @@ export function withUserLookup<TBase extends AbstractConstructor<TwitterClientBa
return { success: false, error: lastError ?? 'Unknown error looking up user' }; return { success: false, error: lastError ?? 'Unknown error looking up user' };
} }
private buildUserByScreenNameFeatures(): Record<string, boolean> {
return {
hidden_profile_subscriptions_enabled: true,
profile_label_improvements_pcf_label_in_post_enabled: true,
responsive_web_profile_redirect_enabled: false,
rweb_tipjar_consumption_enabled: false,
verified_phone_label_enabled: false,
subscriptions_verification_info_is_identity_verified_enabled: true,
subscriptions_verification_info_verified_since_enabled: true,
highlights_tweets_tab_ui_enabled: true,
responsive_web_twitter_article_notes_tab_enabled: true,
subscriptions_feature_can_gift_premium: true,
creator_subscriptions_tweet_preview_api_enabled: true,
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
responsive_web_graphql_timeline_navigation_enabled: true,
};
}
private buildUserByRestIdFeatures(): Record<string, boolean> {
return {
hidden_profile_subscriptions_enabled: true,
profile_label_improvements_pcf_label_in_post_enabled: true,
responsive_web_profile_redirect_enabled: false,
rweb_tipjar_consumption_enabled: false,
verified_phone_label_enabled: false,
highlights_tweets_tab_ui_enabled: true,
responsive_web_twitter_article_notes_tab_enabled: true,
subscriptions_feature_can_gift_premium: true,
creator_subscriptions_tweet_preview_api_enabled: true,
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
responsive_web_graphql_timeline_navigation_enabled: true,
};
}
private async getUserProfileByScreenName(screenName: string): Promise<UserProfileResult> {
const queryId = await this.getQueryId('UserByScreenName');
const variables = {
screen_name: screenName,
withGrokTranslatedBio: true,
};
const params = new URLSearchParams({
variables: JSON.stringify(variables),
features: JSON.stringify(this.buildUserByScreenNameFeatures()),
fieldToggles: JSON.stringify({
withPayments: false,
withAuxiliaryUserLabels: true,
}),
});
const response = await this.fetchWithTimeout(
`${TWITTER_API_BASE}/${queryId}/UserByScreenName?${params.toString()}`,
{
method: 'GET',
headers: this.getHeaders(),
},
);
if (!response.ok) {
const text = await response.text();
return { success: false, error: `HTTP ${response.status}: ${text.slice(0, 200)}` };
}
const data = (await response.json()) as {
data?: { user?: { result?: UserProfileGraphqlResult } };
errors?: Array<{ message?: string }>;
};
if (data.errors?.length) {
return { success: false, error: data.errors.map((error) => error.message ?? 'GraphQL error').join(', ') };
}
const result = data.data?.user?.result;
if (result?.__typename === 'UserUnavailable') {
return { success: false, error: `User @${screenName} not found or unavailable` };
}
const profile = result ? normalizeGraphqlUserResult(result) : null;
if (!profile) {
return { success: false, error: `Could not parse profile for @${screenName}` };
}
return { success: true, profile };
}
private async getUserProfileByRestId(userId: string): Promise<UserProfileResult> {
const queryId = await this.getQueryId('UserByRestId');
const params = new URLSearchParams({
variables: JSON.stringify({ userId }),
features: JSON.stringify(this.buildUserByRestIdFeatures()),
});
const response = await this.fetchWithTimeout(`${TWITTER_API_BASE}/${queryId}/UserByRestId?${params.toString()}`, {
method: 'GET',
headers: this.getHeaders(),
});
if (!response.ok) {
const text = await response.text();
return { success: false, error: `HTTP ${response.status}: ${text.slice(0, 200)}` };
}
const data = (await response.json()) as {
data?: { user?: { result?: UserProfileGraphqlResult } };
errors?: Array<{ message?: string }>;
};
if (data.errors?.length) {
return { success: false, error: data.errors.map((error) => error.message ?? 'GraphQL error').join(', ') };
}
const result = data.data?.user?.result;
if (result?.__typename === 'UserUnavailable') {
return { success: false, error: `User ${userId} not found or unavailable` };
}
const profile = result ? normalizeGraphqlUserResult(result) : null;
if (!profile) {
return { success: false, error: `Could not parse profile for ${userId}` };
}
return { success: true, profile };
}
async getUserProfile(target: string): Promise<UserProfileResult> {
const trimmed = target.trim();
if (!trimmed) {
return { success: false, error: 'User target is required' };
}
if (isNumericUserId(trimmed)) {
return this.getUserProfileByRestId(trimmed);
}
const cleanUsername = normalizeHandle(trimmed);
if (!cleanUsername) {
return { success: false, error: `Invalid username: ${target}` };
}
return this.getUserProfileByScreenName(cleanUsername);
}
async getUserProfiles(targets: string[]): Promise<UserProfilesResult> {
const results: UserProfilesResult['results'] = [];
const seen = new Set<string>();
for (const target of targets) {
const trimmed = target.trim();
if (!trimmed || seen.has(trimmed)) {
continue;
}
seen.add(trimmed);
const result = await this.getUserProfile(trimmed);
if (result.success) {
results.push({ target: trimmed, profile: result.profile });
} else {
results.push({ target: trimmed, error: result.error });
}
}
return { success: true, results };
}
private async getAboutAccountQueryIds(): Promise<string[]> { private async getAboutAccountQueryIds(): Promise<string[]> {
const primary = await this.getQueryId('AboutAccountQuery'); const primary = await this.getQueryId('AboutAccountQuery');
return Array.from(new Set([primary, 'zs_jFPFT78rBpXv9Z3U2YQ'])); return Array.from(new Set([primary, 'zs_jFPFT78rBpXv9Z3U2YQ']));
+1
View File
@@ -566,6 +566,7 @@ export function mapTweetResult(
author: { author: {
username, username,
name: name || username, name: name || username,
profileImageUrl: userLegacy?.profile_image_url_https ?? userResult?.avatar?.image_url,
}, },
authorId: userId, authorId: userId,
quotedTweet, quotedTweet,
+3
View File
@@ -67,5 +67,8 @@ export type {
TwitterClientOptions, TwitterClientOptions,
TwitterList, TwitterList,
TwitterUser, TwitterUser,
TwitterUserProfile,
UploadMediaResult, UploadMediaResult,
UserProfileResult,
UserProfilesResult,
} from './twitter-client-types.js'; } from './twitter-client-types.js';
+7
View File
@@ -14,6 +14,8 @@ describe('cli-args', () => {
'bookmarks', 'bookmarks',
'following', 'following',
'followers', 'followers',
'user',
'profiles',
'likes', 'likes',
'help', 'help',
'whoami', 'whoami',
@@ -58,6 +60,11 @@ describe('cli-args', () => {
expect(result.argv).toBeNull(); expect(result.argv).toBeNull();
}); });
it('does not rewrite numeric profile targets when profiles command is provided', () => {
const result = resolveCliInvocation(['profiles', '@steipete', '25401953', '--json'], known);
expect(result.argv).toBeNull();
});
it('does not rewrite unknown commands', () => { it('does not rewrite unknown commands', () => {
const result = resolveCliInvocation(['https://example.com'], known); const result = resolveCliInvocation(['https://example.com'], known);
expect(result.argv).toBeNull(); expect(result.argv).toBeNull();
+61
View File
@@ -0,0 +1,61 @@
import { Command } from 'commander';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { CliContext } from '../src/cli/shared.js';
import { registerHomeCommand } from '../src/commands/home.js';
import { TwitterClient } from '../src/lib/twitter-client.js';
describe('home command', () => {
let program: Command;
let mockContext: Partial<CliContext>;
beforeEach(() => {
program = new Command();
mockContext = {
resolveTimeoutFromOptions: () => undefined,
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
resolveProfileNameFromOptions: () => undefined,
p: () => '',
printTweetsResult: vi.fn(),
};
});
it('uses cursor pagination when --cursor is set', async () => {
registerHomeCommand(program, mockContext as CliContext);
const timelineSpy = vi
.spyOn(TwitterClient.prototype, 'getHomeLatestTimeline')
.mockResolvedValue({ success: true, tweets: [], nextCursor: 'next-1' });
try {
await program.parseAsync(['node', 'bird', 'home', '--following', '--cursor', 'cursor-1']);
expect(timelineSpy).toHaveBeenCalledWith(20, expect.objectContaining({ cursor: 'cursor-1' }));
expect(mockContext.printTweetsResult).toHaveBeenCalledWith(expect.objectContaining({ nextCursor: 'next-1' }), {
json: false,
usePagination: true,
emptyMessage: 'No tweets found in Following timeline.',
});
} finally {
timelineSpy.mockRestore();
}
});
it('uses paged home timeline when --max-pages is set', async () => {
registerHomeCommand(program, mockContext as CliContext);
const timelineSpy = vi.spyOn(TwitterClient.prototype, 'getHomeTimeline').mockResolvedValue({
success: true,
tweets: [],
nextCursor: 'next-2',
});
try {
await program.parseAsync(['node', 'bird', 'home', '--max-pages', '3', '--json']);
expect(timelineSpy).toHaveBeenCalledWith(20, expect.objectContaining({ maxPages: 3 }));
expect(mockContext.printTweetsResult).toHaveBeenCalledWith(expect.objectContaining({ nextCursor: 'next-2' }), {
json: true,
usePagination: true,
emptyMessage: 'No tweets found in For You timeline.',
});
} finally {
timelineSpy.mockRestore();
}
});
});
+35
View File
@@ -0,0 +1,35 @@
import { Command } from 'commander';
import { describe, expect, it, vi } from 'vitest';
import type { CliContext } from '../src/cli/shared.js';
import { registerListsCommand } from '../src/commands/lists.js';
import { TwitterClient } from '../src/lib/twitter-client.js';
describe('lists command', () => {
it('uses the authenticated Lists page by default', async () => {
const program = new Command();
const ctx = {
resolveTimeoutFromOptions: () => undefined,
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
resolveProfileNameFromOptions: () => undefined,
p: () => '',
colors: { muted: (value: string) => value, accent: (value: string) => value },
getOutput: () => 'plain',
} as unknown as CliContext;
const listsSpy = vi.spyOn(TwitterClient.prototype, 'getLists').mockResolvedValue({
success: true,
lists: [],
});
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
try {
registerListsCommand(program, ctx);
await program.parseAsync(['node', 'bird', 'lists', '--count', '25']);
expect(listsSpy).toHaveBeenCalledWith(25);
expect(logSpy).toHaveBeenCalledWith('No lists found.');
} finally {
listsSpy.mockRestore();
logSpy.mockRestore();
}
});
});
+26 -2
View File
@@ -82,8 +82,8 @@ describe('search command', () => {
const searchSpy = vi.spyOn(TwitterClient.prototype, 'search').mockResolvedValue({ success: true, tweets: [] }); const searchSpy = vi.spyOn(TwitterClient.prototype, 'search').mockResolvedValue({ success: true, tweets: [] });
try { try {
await program.parseAsync(['node', 'bird', 'search', 'cats', '--all', '--json']); await program.parseAsync(['node', 'bird', 'search', 'cats', '--all', '--json', '--product', 'Top']);
expect(getAllSpy).toHaveBeenCalledWith('cats', expect.objectContaining({ includeRaw: false })); expect(getAllSpy).toHaveBeenCalledWith('cats', expect.objectContaining({ includeRaw: false, product: 'Top' }));
expect(searchSpy).not.toHaveBeenCalled(); expect(searchSpy).not.toHaveBeenCalled();
expect(mockContext.printTweetsResult).toHaveBeenCalledWith(expect.objectContaining({ tweets: [] }), { expect(mockContext.printTweetsResult).toHaveBeenCalledWith(expect.objectContaining({ tweets: [] }), {
json: true, json: true,
@@ -96,6 +96,30 @@ describe('search command', () => {
} }
}); });
it('passes --product to non-paged search', async () => {
registerSearchCommands(program, mockContext as CliContext);
const searchSpy = vi.spyOn(TwitterClient.prototype, 'search').mockResolvedValue({ success: true, tweets: [] });
try {
await program.parseAsync(['node', 'bird', 'search', 'cats', '--product', 'Top']);
expect(searchSpy).toHaveBeenCalledWith('cats', 10, {
includeRaw: false,
product: 'Top',
});
} finally {
searchSpy.mockRestore();
}
});
it('rejects unsupported search products', async () => {
program.exitOverride();
registerSearchCommands(program, mockContext as CliContext);
await expect(program.parseAsync(['node', 'bird', 'search', 'cats', '--product', 'Media'])).rejects.toMatchObject({
code: 'commander.invalidArgument',
});
});
it('uses cursor pagination when --cursor is set', async () => { it('uses cursor pagination when --cursor is set', async () => {
registerSearchCommands(program, mockContext as CliContext); registerSearchCommands(program, mockContext as CliContext);
const getAllSpy = vi const getAllSpy = vi
+40
View File
@@ -209,4 +209,44 @@ describe('users commands', () => {
expect(payload.nextCursor).toBeNull(); expect(payload.nextCursor).toBeNull();
expect(followingSpy).toHaveBeenCalledTimes(2); expect(followingSpy).toHaveBeenCalledTimes(2);
}); });
it('prints a single profile as JSON', async () => {
const program = new Command();
registerUserCommands(program, baseCtx);
const profileSpy = vi.spyOn(TwitterClient.prototype, 'getUserProfile').mockResolvedValue({
success: true,
profile: { id: '1', username: 'alpha', name: 'Alpha' },
});
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
await program.parseAsync(['node', 'bird', 'user', '@alpha', '--json']);
expect(profileSpy).toHaveBeenCalledWith('@alpha');
expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toMatchObject({
id: '1',
username: 'alpha',
name: 'Alpha',
});
});
it('prints batch profiles with per-target errors as JSON', async () => {
const program = new Command();
registerUserCommands(program, baseCtx);
const profilesSpy = vi.spyOn(TwitterClient.prototype, 'getUserProfiles').mockResolvedValue({
success: true,
results: [
{ target: 'alpha', profile: { id: '1', username: 'alpha', name: 'Alpha' } },
{ target: 'missing', error: 'not found' },
],
});
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
await program.parseAsync(['node', 'bird', 'profiles', 'alpha', 'missing', '--json']);
expect(profilesSpy).toHaveBeenCalledWith(['alpha', 'missing']);
expect(JSON.parse(String(logSpy.mock.calls[0]?.[0]))).toEqual({
users: [{ id: '1', username: 'alpha', name: 'Alpha' }],
errors: [{ target: 'missing', error: 'not found' }],
});
});
}); });
+2
View File
@@ -17,6 +17,8 @@ describe('root help output', () => {
expect(help).toContain('following'); expect(help).toContain('following');
expect(help).toContain('followers'); expect(help).toContain('followers');
expect(help).toContain('user');
expect(help).toContain('profiles');
expect(help).toContain('likes'); expect(help).toContain('likes');
expect(help).toContain('bird <tweet-id-or-url>'); expect(help).toContain('bird <tweet-id-or-url>');
+8 -1
View File
@@ -1,8 +1,15 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { TwitterClient } from '../src/index.js'; import { type SearchFetchOptions, type SearchProduct, TwitterClient } from '../src/index.js';
describe('library exports', () => { describe('library exports', () => {
it('exposes primary library surface', () => { it('exposes primary library surface', () => {
expect(typeof TwitterClient).toBe('function'); expect(typeof TwitterClient).toBe('function');
}); });
it('exposes search product types', () => {
const product: SearchProduct = 'Top';
const options: SearchFetchOptions = { product };
expect(options.product).toBe('Top');
});
}); });
+23 -12
View File
@@ -29,9 +29,6 @@ describe('runtime-features', () => {
likes: { likes: {
likes_only: true, likes_only: true,
}, },
lists: {
responsive_web_text_conversations_enabled: true,
},
}, },
}); });
@@ -44,9 +41,6 @@ describe('runtime-features', () => {
const likes = buildLikesFeatures(); const likes = buildLikesFeatures();
expect(likes.global_flag).toBe(true); expect(likes.global_flag).toBe(true);
expect(likes.likes_only).toBe(true); expect(likes.likes_only).toBe(true);
const lists = buildListsFeatures();
expect(lists.responsive_web_text_conversations_enabled).toBe(true);
}); });
it('refresh merges defaults with existing cache', async () => { it('refresh merges defaults with existing cache', async () => {
@@ -119,11 +113,28 @@ describe('runtime-features', () => {
it('includes required lists API feature flags', () => { it('includes required lists API feature flags', () => {
const features = buildListsFeatures(); const features = buildListsFeatures();
expect(features.responsive_web_graphql_exclude_directive_enabled).toBe(true); expect(features.responsive_web_graphql_exclude_directive_enabled).toBeUndefined();
expect(features.blue_business_profile_image_shape_enabled).toBe(true); expect(features.responsive_web_grok_annotations_enabled).toBe(true);
expect(features.responsive_web_text_conversations_enabled).toBe(false); expect(features.rweb_cashtags_enabled).toBe(true);
expect(features.tweetypie_unmention_optimization_enabled).toBe(true); expect(features.responsive_web_grok_show_grok_translated_post).toBe(true);
expect(features.vibe_api_enabled).toBe(true); expect(features.longform_notetweets_inline_media_enabled).toBe(false);
expect(features.interactive_text_enabled).toBe(true); });
it('keeps catalog-locked list features independent from runtime overrides', () => {
process.env.BIRD_FEATURES_JSON = JSON.stringify({
global: {
responsive_web_grok_annotations_enabled: false,
},
sets: {
lists: {
rweb_cashtags_enabled: false,
},
},
});
clearFeatureOverridesCache();
const features = buildListsFeatures();
expect(features.responsive_web_grok_annotations_enabled).toBe(true);
expect(features.rweb_cashtags_enabled).toBe(true);
}); });
}); });
+1
View File
@@ -9,6 +9,7 @@ export type TwitterClientPrivate = TwitterClient & {
error?: string; error?: string;
}>; }>;
getLikesQueryIds: () => Promise<string[]>; getLikesQueryIds: () => Promise<string[]>;
getListsManagementQueryIds: () => Promise<string[]>;
getListTimelineQueryIds: () => Promise<string[]>; getListTimelineQueryIds: () => Promise<string[]>;
getListOwnershipsQueryIds: () => Promise<string[]>; getListOwnershipsQueryIds: () => Promise<string[]>;
getListMembershipsQueryIds: () => Promise<string[]>; getListMembershipsQueryIds: () => Promise<string[]>;
+10 -10
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TwitterClient } from '../src/lib/twitter-client.js'; import { TwitterClient } from '../src/lib/twitter-client.js';
import { validCookies } from './twitter-client-fixtures.js'; import { testRelayBaseUrl } from './twitter-client-fixtures.js';
const originalFetch = global.fetch; const originalFetch = global.fetch;
@@ -25,7 +25,7 @@ describe('TwitterClient engagement', () => {
json: async () => ({ data: { favorite_tweet: 'Done' } }), json: async () => ({ data: { favorite_tweet: 'Done' } }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.like('1234567890'); const result = await client.like('1234567890');
expect(result.success).toBe(true); expect(result.success).toBe(true);
@@ -45,7 +45,7 @@ describe('TwitterClient engagement', () => {
text: async () => 'Forbidden', text: async () => 'Forbidden',
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.like('1234567890'); const result = await client.like('1234567890');
expect(result.success).toBe(false); expect(result.success).toBe(false);
@@ -61,7 +61,7 @@ describe('TwitterClient engagement', () => {
}), }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.like('1234567890'); const result = await client.like('1234567890');
expect(result.success).toBe(false); expect(result.success).toBe(false);
@@ -75,7 +75,7 @@ describe('TwitterClient engagement', () => {
json: async () => ({ data: { favorite_tweet: 'Done' } }), json: async () => ({ data: { favorite_tweet: 'Done' } }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.like('1234567890'); const result = await client.like('1234567890');
expect(result.success).toBe(true); expect(result.success).toBe(true);
@@ -91,7 +91,7 @@ describe('TwitterClient engagement', () => {
json: async () => ({ data: { unfavorite_tweet: 'Done' } }), json: async () => ({ data: { unfavorite_tweet: 'Done' } }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.unlike('1234567890'); const result = await client.unlike('1234567890');
expect(result.success).toBe(true); expect(result.success).toBe(true);
@@ -111,7 +111,7 @@ describe('TwitterClient engagement', () => {
json: async () => ({ data: { create_retweet: { retweet_results: { result: {} } } } }), json: async () => ({ data: { create_retweet: { retweet_results: { result: {} } } } }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.retweet('1234567890'); const result = await client.retweet('1234567890');
expect(result.success).toBe(true); expect(result.success).toBe(true);
@@ -131,7 +131,7 @@ describe('TwitterClient engagement', () => {
json: async () => ({ data: { unretweet: { source_tweet_results: {} } } }), json: async () => ({ data: { unretweet: { source_tweet_results: {} } } }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.unretweet('1234567890'); const result = await client.unretweet('1234567890');
expect(result.success).toBe(true); expect(result.success).toBe(true);
@@ -154,7 +154,7 @@ describe('TwitterClient engagement', () => {
json: async () => ({ data: { tweet_bookmark_put: 'Done' } }), json: async () => ({ data: { tweet_bookmark_put: 'Done' } }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.bookmark('1234567890'); const result = await client.bookmark('1234567890');
expect(result.success).toBe(true); expect(result.success).toBe(true);
@@ -170,7 +170,7 @@ describe('TwitterClient engagement', () => {
it('catches network errors', async () => { it('catches network errors', async () => {
mockFetch.mockRejectedValueOnce(new Error('Network error')); mockFetch.mockRejectedValueOnce(new Error('Network error'));
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.like('1234567890'); const result = await client.like('1234567890');
expect(result.success).toBe(false); expect(result.success).toBe(false);
+115
View File
@@ -145,6 +145,121 @@ describe('TwitterClient home timeline', () => {
}); });
describe('pagination', () => { describe('pagination', () => {
it('returns the next cursor when stopping before the end', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: {
home: {
home_timeline_urt: {
instructions: [
{
entries: [
{
content: {
itemContent: {
tweet_results: {
result: {
rest_id: 'tweet1',
legacy: { full_text: 'First tweet', created_at: 'Mon Jan 06 00:00:00 +0000 2025' },
core: {
user_results: {
result: { rest_id: 'u1', legacy: { screen_name: 'user1', name: 'User 1' } },
},
},
},
},
},
},
},
{
content: {
cursorType: 'Bottom',
value: 'cursor123',
},
},
],
},
],
},
},
},
}),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getHomeTimeline(1);
expect(result.success).toBe(true);
expect(result.nextCursor).toBe('cursor123');
});
it('resumes from a provided cursor', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => makeHomeTimelineResponse('tweet2', 'Second page tweet', 'user2'),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getHomeLatestTimeline(1, { cursor: 'resume-cursor' });
expect(result.success).toBe(true);
const callUrl = String(mockFetch.mock.calls[0]?.[0]);
const variables = JSON.parse(new URL(callUrl).searchParams.get('variables') ?? '{}') as { cursor?: string };
expect(variables.cursor).toBe('resume-cursor');
});
it('stops at maxPages and returns the cursor to resume', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
json: async () => ({
data: {
home: {
home_timeline_urt: {
instructions: [
{
entries: [
{
content: {
itemContent: {
tweet_results: {
result: {
rest_id: 'tweet1',
legacy: { full_text: 'First tweet', created_at: 'Mon Jan 06 00:00:00 +0000 2025' },
core: {
user_results: {
result: { rest_id: 'u1', legacy: { screen_name: 'user1', name: 'User 1' } },
},
},
},
},
},
},
},
{
content: {
cursorType: 'Bottom',
value: 'cursor-page-2',
},
},
],
},
],
},
},
},
}),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getHomeTimeline(5, { maxPages: 1 });
expect(result.success).toBe(true);
expect(result.tweets).toHaveLength(1);
expect(result.nextCursor).toBe('cursor-page-2');
expect(mockFetch).toHaveBeenCalledTimes(1);
});
it('should deduplicate tweets across pages', async () => { it('should deduplicate tweets across pages', async () => {
// First page // First page
mockFetch.mockResolvedValueOnce({ mockFetch.mockResolvedValueOnce({
@@ -0,0 +1,171 @@
// ABOUTME: Tests for the authenticated user's Lists management timeline.
// ABOUTME: Covers nested list items, deduplication, and partial GraphQL errors.
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TwitterClient } from '../src/lib/twitter-client.js';
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
const originalFetch = global.fetch;
afterEach(() => {
global.fetch = originalFetch;
vi.restoreAllMocks();
});
describe('TwitterClient lists management', () => {
let mockFetch: ReturnType<typeof vi.fn>;
beforeEach(() => {
mockFetch = vi.fn();
global.fetch = mockFetch as unknown as typeof fetch;
});
it('gets and deduplicates the lists shown on the authenticated Lists page', async () => {
const list = {
id_str: '1234567890',
name: 'My List',
description: 'A useful list',
member_count: 10,
mode: 'Private',
created_at: 1_704_067_200_000,
user_results: {
result: {
rest_id: '12345',
core: { screen_name: 'testuser', name: 'Test User' },
},
},
};
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
data: {
viewer: {
list_management_timeline: {
timeline: {
instructions: [
{
entries: [
{
content: {
clientEventInfo: { component: 'suggest_list_to_follow' },
items: [
{
item: {
itemContent: {
list: { id_str: '999', name: 'Suggested List' },
},
},
},
],
},
},
{
content: {
clientEventInfo: { component: 'suggest_owned_subscribed_list' },
items: [{ item: { itemContent: { list } } }, { item: { itemContent: { list } } }],
},
},
],
},
],
},
},
},
},
errors: [{ message: 'optional banner field failed' }],
}),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const clientPrivate = client as unknown as TwitterClientPrivate;
clientPrivate.getListsManagementQueryIds = async () => ['test'];
const result = await client.getLists(100);
expect(result).toEqual({
success: true,
lists: [
{
id: '1234567890',
name: 'My List',
description: 'A useful list',
memberCount: 10,
subscriberCount: undefined,
isPrivate: true,
createdAt: '2024-01-01T00:00:00.000Z',
owner: {
id: '12345',
username: 'testuser',
name: 'Test User',
},
},
],
});
const [url] = mockFetch.mock.calls[0];
const requestUrl = new URL(url as string);
expect(requestUrl.pathname).toContain('/test/ListsManagementPageTimeline');
expect(JSON.parse(requestUrl.searchParams.get('variables') as string)).toEqual({ count: 100 });
});
it('returns an error when the management timeline is missing', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({ errors: [{ message: 'Not authorized' }] }),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const clientPrivate = client as unknown as TwitterClientPrivate;
clientPrivate.getListsManagementQueryIds = async () => ['test'];
await expect(client.getLists()).resolves.toEqual({
success: false,
error: 'Not authorized',
});
});
it('ignores an invalid numeric creation date', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
data: {
viewer: {
list_management_timeline: {
timeline: {
instructions: [
{
entries: [
{
content: {
clientEventInfo: { component: 'suggest_owned_subscribed_list' },
items: [
{
item: {
itemContent: {
list: { id_str: '123', name: 'List', created_at: Number.NaN },
},
},
},
],
},
},
],
},
],
},
},
},
},
}),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const clientPrivate = client as unknown as TwitterClientPrivate;
clientPrivate.getListsManagementQueryIds = async () => ['test'];
const result = await client.getLists();
expect(result.success && result.lists?.[0].createdAt).toBeUndefined();
});
});
@@ -75,6 +75,9 @@ describe('TwitterClient lists memberships', () => {
expect(result.lists?.[0].id).toBe('5555'); expect(result.lists?.[0].id).toBe('5555');
expect(result.lists?.[0].name).toBe('Member List'); expect(result.lists?.[0].name).toBe('Member List');
expect(result.lists?.[0].owner?.username).toBe('otheruser'); expect(result.lists?.[0].owner?.username).toBe('otheruser');
const [url] = mockFetch.mock.calls[0];
const variables = JSON.parse(new URL(url as string).searchParams.get('variables') as string);
expect(variables).toEqual({ userId: '12345', count: 100 });
}); });
it('retries on 404 error after refreshing query IDs', async () => { it('retries on 404 error after refreshing query IDs', async () => {
+13 -7
View File
@@ -116,13 +116,19 @@ describe('TwitterClient lists owned', () => {
await client.getOwnedLists(1); await client.getOwnedLists(1);
const [url] = mockFetch.mock.calls[0]; const [url] = mockFetch.mock.calls[0];
const parsedFeatures = JSON.parse(new URL(url as string).searchParams.get('features') as string); const requestUrl = new URL(url as string);
expect(parsedFeatures.responsive_web_graphql_exclude_directive_enabled).toBe(true); const parsedVariables = JSON.parse(requestUrl.searchParams.get('variables') as string);
expect(parsedFeatures.blue_business_profile_image_shape_enabled).toBe(true); const parsedFeatures = JSON.parse(requestUrl.searchParams.get('features') as string);
expect(parsedFeatures.responsive_web_text_conversations_enabled).toBe(false); expect(parsedVariables).toEqual({
expect(parsedFeatures.tweetypie_unmention_optimization_enabled).toBe(true); userId: '12345',
expect(parsedFeatures.vibe_api_enabled).toBe(true); isListMemberTargetUserId: '12345',
expect(parsedFeatures.interactive_text_enabled).toBe(true); count: 1,
});
expect(parsedFeatures.responsive_web_graphql_exclude_directive_enabled).toBeUndefined();
expect(parsedFeatures.responsive_web_grok_annotations_enabled).toBe(true);
expect(parsedFeatures.rweb_cashtags_enabled).toBe(true);
expect(parsedFeatures.responsive_web_grok_show_grok_translated_post).toBe(true);
expect(parsedFeatures.longform_notetweets_inline_media_enabled).toBe(false);
}); });
it('handles private lists correctly', async () => { it('handles private lists correctly', async () => {
@@ -66,6 +66,7 @@ describe('TwitterClient lists timeline', () => {
}, },
}, },
}, },
errors: [{ message: 'optional media field failed' }],
}), }),
}); });
+10 -4
View File
@@ -83,8 +83,12 @@ describe('TwitterClient search', () => {
expect(body.queryId).toBeDefined(); expect(body.queryId).toBeDefined();
const urlVars = new URL(url as string).searchParams.get('variables'); const urlVars = new URL(url as string).searchParams.get('variables');
expect(urlVars).toBeTruthy(); expect(urlVars).toBeTruthy();
const parsed = JSON.parse(urlVars as string) as { rawQuery?: string }; const parsed = JSON.parse(urlVars as string) as {
rawQuery?: string;
product?: string;
};
expect(parsed.rawQuery).toBe('needle'); expect(parsed.rawQuery).toBe('needle');
expect(parsed.product).toBe('Latest');
}); });
it('refreshes query IDs when all search endpoints 404', async () => { it('refreshes query IDs when all search endpoints 404', async () => {
@@ -186,7 +190,7 @@ describe('TwitterClient search', () => {
}); });
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.search('needle', 3); const result = await client.search('needle', 3, { product: 'Top' });
expect(result.success).toBe(true); expect(result.success).toBe(true);
expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1', '2', '3']); expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1', '2', '3']);
@@ -194,13 +198,15 @@ describe('TwitterClient search', () => {
const firstVars = JSON.parse( const firstVars = JSON.parse(
new URL(mockFetch.mock.calls[0][0] as string).searchParams.get('variables') as string, new URL(mockFetch.mock.calls[0][0] as string).searchParams.get('variables') as string,
) as { cursor?: string }; ) as { cursor?: string; product?: string };
const secondVars = JSON.parse( const secondVars = JSON.parse(
new URL(mockFetch.mock.calls[1][0] as string).searchParams.get('variables') as string, new URL(mockFetch.mock.calls[1][0] as string).searchParams.get('variables') as string,
) as { cursor?: string }; ) as { cursor?: string; product?: string };
expect(firstVars.cursor).toBeUndefined(); expect(firstVars.cursor).toBeUndefined();
expect(secondVars.cursor).toBe('cursor-1'); expect(secondVars.cursor).toBe('cursor-1');
expect(firstVars.product).toBe('Top');
expect(secondVars.product).toBe('Top');
}); });
it('stops paginating when the cursor repeats', async () => { it('stops paginating when the cursor repeats', async () => {
+10 -10
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { TwitterClient } from '../src/lib/twitter-client.js'; import { TwitterClient } from '../src/lib/twitter-client.js';
import { validCookies } from './twitter-client-fixtures.js'; import { testRelayBaseUrl } from './twitter-client-fixtures.js';
const originalFetch = global.fetch; const originalFetch = global.fetch;
@@ -38,7 +38,7 @@ describe('TwitterClient getUserAboutAccount', () => {
}), }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount('testuser'); const result = await client.getUserAboutAccount('testuser');
expect(result.success).toBe(true); expect(result.success).toBe(true);
@@ -67,7 +67,7 @@ describe('TwitterClient getUserAboutAccount', () => {
}), }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount('@testuser'); const result = await client.getUserAboutAccount('@testuser');
expect(result.success).toBe(true); expect(result.success).toBe(true);
@@ -75,7 +75,7 @@ describe('TwitterClient getUserAboutAccount', () => {
}); });
it('returns error for invalid username', async () => { it('returns error for invalid username', async () => {
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount(''); const result = await client.getUserAboutAccount('');
expect(result.success).toBe(false); expect(result.success).toBe(false);
@@ -95,7 +95,7 @@ describe('TwitterClient getUserAboutAccount', () => {
}), }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount('testuser'); const result = await client.getUserAboutAccount('testuser');
expect(result.success).toBe(false); expect(result.success).toBe(false);
@@ -111,7 +111,7 @@ describe('TwitterClient getUserAboutAccount', () => {
}), }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount('testuser'); const result = await client.getUserAboutAccount('testuser');
expect(result.success).toBe(false); expect(result.success).toBe(false);
@@ -125,7 +125,7 @@ describe('TwitterClient getUserAboutAccount', () => {
text: async () => 'Not Found', text: async () => 'Not Found',
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount('testuser'); const result = await client.getUserAboutAccount('testuser');
expect(result.success).toBe(false); expect(result.success).toBe(false);
@@ -139,7 +139,7 @@ describe('TwitterClient getUserAboutAccount', () => {
text: async () => 'Internal Server Error', text: async () => 'Internal Server Error',
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount('testuser'); const result = await client.getUserAboutAccount('testuser');
expect(result.success).toBe(false); expect(result.success).toBe(false);
@@ -149,7 +149,7 @@ describe('TwitterClient getUserAboutAccount', () => {
it('handles network errors', async () => { it('handles network errors', async () => {
mockFetch.mockRejectedValueOnce(new Error('Network error')); mockFetch.mockRejectedValueOnce(new Error('Network error'));
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount('testuser'); const result = await client.getUserAboutAccount('testuser');
expect(result.success).toBe(false); expect(result.success).toBe(false);
@@ -174,7 +174,7 @@ describe('TwitterClient getUserAboutAccount', () => {
}), }),
}); });
const client = new TwitterClient({ cookies: validCookies }); const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserAboutAccount('testuser'); const result = await client.getUserAboutAccount('testuser');
expect(result.success).toBe(true); expect(result.success).toBe(true);
+180
View File
@@ -163,4 +163,184 @@ describe('TwitterClient getUserIdByUsername', () => {
expect(result.userId).toBe('99999'); expect(result.userId).toBe('99999');
expect(mockFetch).toHaveBeenCalledTimes(3); expect(mockFetch).toHaveBeenCalledTimes(3);
}); });
it('resolves a rich profile by screen name', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
data: {
user: {
result: {
__typename: 'User',
rest_id: '12345',
is_blue_verified: true,
verification_info: { reason: { verified_since_msec: '1700000000000' } },
avatar: { image_url: 'https://pbs.twimg.com/profile_images/123/avatar_normal.jpg' },
legacy: {
screen_name: 'testuser',
name: 'Test User',
description: 'Building tools',
location: 'Internet',
url: 'https://t.co/site',
created_at: 'Mon Jan 06 00:00:00 +0000 2025',
verified: false,
verified_type: 'Business',
followers_count: 123,
friends_count: 45,
profile_image_url_https: 'https://pbs.twimg.com/profile_images/123/legacy_normal.jpg',
entities: {
url: {
urls: [
{
url: 'https://t.co/site',
expanded_url: 'https://example.com',
display_url: 'example.com',
},
],
},
description: {
urls: [
{
url: 'https://t.co/bio',
expanded_url: 'https://bio.example',
display_url: 'bio.example',
},
],
},
},
},
affiliates_highlighted_label: {
label: {
description: 'Example Org',
url: { url: 'https://x.com/example' },
badge: { url: 'https://pbs.twimg.com/profile_images/org/badge.png' },
},
},
},
},
},
}),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserProfile('@testuser');
expect(result).toEqual({
success: true,
profile: expect.objectContaining({
id: '12345',
username: 'testuser',
name: 'Test User',
description: 'Building tools',
location: 'Internet',
url: 'https://example.com',
verified: true,
verifiedType: 'Business',
followersCount: 123,
followingCount: 45,
profileImageUrl: 'https://pbs.twimg.com/profile_images/123/avatar_normal.jpg',
entities: expect.objectContaining({
url: expect.objectContaining({
urls: [expect.objectContaining({ expanded_url: 'https://example.com' })],
}),
}),
affiliation: {
description: 'Example Org',
url: 'https://x.com/example',
badgeUrl: 'https://pbs.twimg.com/profile_images/org/badge.png',
},
raw: expect.any(Object),
}),
});
});
it('resolves a rich profile by user id', async () => {
mockFetch.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
data: {
user: {
result: {
__typename: 'User',
rest_id: '42',
core: {
screen_name: 'byid',
name: 'By Id',
created_at: 'Tue Feb 01 00:00:00 +0000 2022',
},
location: {
location: 'Vienna & London',
},
legacy: {
description: 'Lookup by id',
followers_count: 10,
friends_count: 2,
},
},
},
},
}),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserProfile('42');
expect(result.success).toBe(true);
expect(result.profile).toMatchObject({
id: '42',
username: 'byid',
name: 'By Id',
description: 'Lookup by id',
location: 'Vienna & London',
createdAt: 'Tue Feb 01 00:00:00 +0000 2022',
followersCount: 10,
followingCount: 2,
});
expect(String(mockFetch.mock.calls[0]?.[0])).toContain('/UserByRestId?');
});
it('resolves profile batches with per-target errors', async () => {
mockFetch
.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
data: {
user: {
result: {
__typename: 'User',
rest_id: '1',
legacy: { screen_name: 'alpha', name: 'Alpha' },
},
},
},
}),
})
.mockResolvedValueOnce({
ok: true,
status: 200,
json: async () => ({
data: {
user: {
result: {
__typename: 'UserUnavailable',
},
},
},
}),
});
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
const result = await client.getUserProfiles(['alpha', 'missing']);
expect(result).toEqual({
success: true,
results: [
{ target: 'alpha', profile: expect.objectContaining({ id: '1', username: 'alpha' }) },
{ target: 'missing', error: 'User @missing not found or unavailable' },
],
});
});
}); });
+4
View File
@@ -5,3 +5,7 @@
- When the user asks to investigate odd API counts, do not change client-side limiting behavior unless they explicitly approve the behavior change. - When the user asks to investigate odd API counts, do not change client-side limiting behavior unless they explicitly approve the behavior change.
- When adding package registry publishing for this repository, use the `@yuta` package scope unless the user explicitly asks for another namespace. - When adding package registry publishing for this repository, use the `@yuta` package scope unless the user explicitly asks for another namespace.
- Gitea Actions secret and variable names are case-insensitive, alphanumeric or underscore only, and cannot start with `GITEA_` or `GITHUB_`; use names like `PACKAGE_TOKEN`. - Gitea Actions secret and variable names are case-insensitive, alphanumeric or underscore only, and cannot start with `GITEA_` or `GITHUB_`; use names like `PACKAGE_TOKEN`.
- When adapting upstream tests to this fork, run tests with `TWITTER_RELAY_BASE_URL` unset; local relay environment variables can hide missing explicit `relayBaseUrl` fixtures.
- For authenticated account pages, use the viewer-scoped catalog operation that
matches the UI. Do not substitute a similarly named user-scoped operation;
verify the exact request against the relay before changing Bird.