Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8400469ca | ||
|
|
81921226f0 | ||
|
|
0caf2677e4 | ||
|
|
9340ed3f47 | ||
|
|
2e293ad65b | ||
|
|
826de66d78 | ||
|
|
01f4b58b99 | ||
|
|
eedf9b1644 | ||
|
|
55fd5c3d81 | ||
|
|
b7320a19c8 | ||
|
|
9b40a2d43c | ||
|
|
a167ac4380 | ||
|
|
81f1229660 | ||
|
|
da013664c8 | ||
|
|
471cd9b26f | ||
|
|
966599522a | ||
|
|
38d5dfe96a | ||
|
|
98a7145dea | ||
|
|
75848960cb | ||
|
|
1b2afd5acb | ||
|
|
77c7d676a7 | ||
|
|
058aa0e3c3 | ||
|
|
df449ea736 | ||
|
|
3c2f6f480e | ||
|
|
253791cc8f | ||
|
|
71aa56517e | ||
|
|
afc06864c6 | ||
|
|
a2021193ee | ||
|
|
769245503c | ||
|
|
083c8cd007 | ||
|
|
6cf0c00d1b | ||
|
|
17599dfb75 | ||
|
|
63e6d71959 | ||
|
|
5509d915ba | ||
|
|
3dc78d8fff | ||
|
|
3f370cc4b6 | ||
|
|
7a036e244d | ||
|
|
ea7e5191b2 |
+42
-10
@@ -1,30 +1,62 @@
|
||||
# Changelog
|
||||
|
||||
## 0.7.0 — 2026-06-24
|
||||
## 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
|
||||
|
||||
### Added
|
||||
- `bookmarks` thread expansion controls (`--expand-root-only`, `--author-chain`, `--author-only`, `--full-chain-only`, `--include-ancestor-branches`, `--include-parent`, `--thread-meta`, `--sort-chronological`) for richer context exports (#55) — thanks @kkretschmer2.
|
||||
- `about` command to report account origin/location metadata (#51) — thanks @pjtf93.
|
||||
- `follow`/`unfollow` commands to manage follows (#54) — thanks @citizenlee.
|
||||
- Twitter client now supports like/unlike/retweet/unretweet/bookmark via the engagement mixin (#53) — thanks @the-vampiire.
|
||||
|
||||
### Fixed
|
||||
- `bookmarks` expanded JSON now preserves pagination `nextCursor`, and full-chain filtering only includes ancestor branches when requested.
|
||||
- Follow/unfollow REST fallback now supports cursor pagination for followers/following (#54).
|
||||
- About account live coverage now verifies data extraction paths (#51) — thanks @pjtf93.
|
||||
|
||||
### Tests
|
||||
- Live tests now exercise engagement mutations (opt-in) (#53) — thanks @the-vampiire.
|
||||
|
||||
## 0.7.0 — 2026-01-12
|
||||
|
||||
### Added
|
||||
- `list-timeline` now supports pagination (`--all`, `--max-pages`, `--cursor`) (#30) — thanks @zheli.
|
||||
- `home` command for the "For You" and "Following" home timelines (#31) — thanks @odysseus0.
|
||||
- Rich text output now shows article previews, quoted tweets, and media links (#32) — thanks @odysseus0.
|
||||
- `news`/`trending` command for Explore tabs with AI-curated headlines (#39) — thanks @aavetis.
|
||||
- `user-tweets` command to fetch a user's profile timeline (#34) — thanks @crcatala.
|
||||
- `replies` and `thread` now support pagination (`--all`, `--max-pages`, `--cursor`, `--delay`) (#35) — thanks @crcatala.
|
||||
- Long-form article tweets now render rich Draft.js content blocks/entities (#36) — thanks @crcatala.
|
||||
- `news`/`trending` command for Explore tabs with AI-curated headlines (#39) — thanks @aavetis.
|
||||
- `search` now supports pagination (`--all`, `--max-pages`, `--cursor`) (#42) — thanks @pjtf93.
|
||||
- `likes` now supports pagination (`--all`, `--max-pages`, `--cursor`) (#44) — thanks @jsholmes.
|
||||
- `list-timeline` now supports pagination (`--all`, `--max-pages`, `--cursor`) (#30) — thanks @zheli.
|
||||
- Rich text output now shows article previews, quoted tweets, and media links (#32) — thanks @odysseus0.
|
||||
- Long-form article tweets now render rich Draft.js content blocks/entities (#36) — thanks @crcatala.
|
||||
|
||||
### Changed
|
||||
- Library typing: `SearchResult` is now a discriminated union (so `error` only exists when `success: false`).
|
||||
|
||||
### Fixed
|
||||
- Lists GraphQL feature flags updated to prevent 400s (#27) — thanks @zheli.
|
||||
- Lists feature overrides now scope new GraphQL flags correctly (#50) — thanks @ryanh-ai.
|
||||
- Tweet detail parsing now tolerates partial GraphQL errors when usable data exists (#48) — thanks @jsholmes.
|
||||
- News output now respects `--tweets-per-item`, keeps unique IDs, and parses non-add entry instructions (#39) — thanks @aavetis.
|
||||
- Following/followers pagination now guards repeat cursors and standardizes JSON output (#28) — thanks @malpern.
|
||||
- Likes pagination now follows cursors and avoids stalling on duplicate pages (#12) — thanks @titouv.
|
||||
- macOS cookie extraction now supports Brave keychain storage (#40) — thanks @gakonst.
|
||||
- Terminal hyperlinks now sanitize control characters before emitting OSC 8 sequences (#29) — thanks @mafulafunk.
|
||||
- Following/followers pagination now guards repeat cursors and standardizes JSON output (#28) — thanks @malpern.
|
||||
- Lists GraphQL feature flags updated to prevent 400s (#27) — thanks @zheli.
|
||||
- Likes pagination now follows cursors and avoids stalling on duplicate pages (#12) — thanks @titouv.
|
||||
- Tweet detail parsing now tolerates partial GraphQL errors when usable data exists (#48) — thanks @jsholmes.
|
||||
- `pnpm run build:dist` now succeeds after tightening JSON/pagination option typing in tweet output commands.
|
||||
- News output now respects `--tweets-per-item`, keeps unique IDs, and parses non-add entry instructions (#39) — thanks @aavetis.
|
||||
|
||||
### Tests
|
||||
- Following: split following/likes tests + cover cursor handling (#33) — thanks @VACInc.
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
# bird 🐦 — fast X CLI for tweeting, replying, and reading
|
||||
|
||||
`bird` is a fast X CLI for tweeting, replying, and reading via X/Twitter GraphQL through twitter safe relay.
|
||||
`bird` is a fast X CLI for tweeting, replying, and reading via X/Twitter GraphQL through
|
||||
[twitter safe relay](https://github.com/fa0311/twitter_api_safe_relay).
|
||||
|
||||
## Disclaimer
|
||||
|
||||
This project uses X/Twitter’s [**documented**](https://github.com/fa0311/TwitterInternalAPIDocument) internal web
|
||||
GraphQL API through twitter safe relay. X can change endpoints, query IDs, and anti-bot behavior at any time —
|
||||
**expect this to break without notice**.
|
||||
GraphQL API through [twitter safe relay](https://github.com/fa0311/twitter_api_safe_relay). X can change endpoints,
|
||||
query IDs, and anti-bot behavior at any time — **expect this to break without notice**.
|
||||
|
||||
## Install
|
||||
|
||||
@@ -17,7 +18,7 @@ npm config set @yuta:registry=https://git.yutakobayashi.com/api/packages/yuta/np
|
||||
npm install -g @yuta/bird
|
||||
|
||||
# one-shot (no install)
|
||||
npx -y @yuta/bird whoami
|
||||
npx -y --@yuta:registry=https://git.yutakobayashi.com/api/packages/yuta/npm/ @yuta/bird whoami
|
||||
```
|
||||
|
||||
Nix flakes:
|
||||
@@ -26,12 +27,6 @@ Nix flakes:
|
||||
nix run git+https://git.yutakobayashi.com/yuta/bird -- --help
|
||||
```
|
||||
|
||||
Homebrew (macOS, prebuilt Bun binary):
|
||||
|
||||
```bash
|
||||
brew install steipete/tap/bird
|
||||
```
|
||||
|
||||
## Quickstart
|
||||
|
||||
```bash
|
||||
@@ -56,6 +51,8 @@ bird thread 1234567890123456789 --max-pages 3 --json
|
||||
|
||||
# Search + mentions
|
||||
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 --user @steipete -n 5
|
||||
|
||||
@@ -68,6 +65,7 @@ bird bookmarks -n 5
|
||||
bird bookmarks --folder-id 123456789123456789 -n 5 # https://x.com/i/bookmarks/<folder-id>
|
||||
bird bookmarks --all --json
|
||||
bird bookmarks --all --max-pages 2 --json
|
||||
bird bookmarks --include-parent --json
|
||||
bird unbookmark 1234567890123456789
|
||||
bird unbookmark https://x.com/user/status/1234567890123456789
|
||||
|
||||
@@ -91,6 +89,10 @@ bird following --user 12345678 -n 10 # by user ID
|
||||
bird followers -n 20
|
||||
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)
|
||||
bird query-ids --fresh
|
||||
```
|
||||
@@ -139,11 +141,15 @@ By default, the command fetches from For You, News, Sports, and Entertainment ta
|
||||
import { TwitterClient } from '@yuta/bird';
|
||||
|
||||
const client = new TwitterClient({
|
||||
relayBaseUrl: process.env.TWITTER_RELAY_BASE_URL
|
||||
relayBaseUrl: process.env.TWITTER_RELAY_BASE_URL,
|
||||
profileName: process.env.BIRD_PROFILE_NAME
|
||||
});
|
||||
|
||||
// Search for tweets
|
||||
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)
|
||||
const newsResult = await client.getNews(10, { aiOnly: true });
|
||||
@@ -156,40 +162,64 @@ const sportsNews = await client.getNews(10, {
|
||||
});
|
||||
```
|
||||
|
||||
Account details (About profile):
|
||||
|
||||
```ts
|
||||
const aboutResult = await client.getUserAboutAccount('steipete');
|
||||
if (aboutResult.success && aboutResult.aboutProfile) {
|
||||
console.log(aboutResult.aboutProfile.accountBasedIn);
|
||||
}
|
||||
```
|
||||
|
||||
Fields:
|
||||
- `accountBasedIn`
|
||||
- `source`
|
||||
- `createdCountryAccurate`
|
||||
- `locationAccurate`
|
||||
- `learnMoreUrl`
|
||||
|
||||
## Commands
|
||||
|
||||
- `bird tweet "<text>"` — post a new tweet.
|
||||
- `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 query-ids [--fresh] [--json]` — inspect or refresh cached GraphQL query IDs.
|
||||
- `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 <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 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 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] [--json]` — list your bookmarked tweets (or a specific bookmark folder); `--max-pages` requires `--all`.
|
||||
- `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 unbookmark <tweet-id-or-url...>` — remove one or more bookmarks by tweet ID or URL.
|
||||
- `bird likes [-n count] [--json]` — list your liked tweets.
|
||||
- `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 trending` — alias for `news` command.
|
||||
- `bird lists [--member-of] [-n count] [--json]` — list your lists (owned or memberships).
|
||||
- `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] [--json]` — list users that you (or another user) follow.
|
||||
- `bird followers [--user <userId>] [-n count] [--json]` — list users that follow you (or another user).
|
||||
- `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 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 whoami` — print which Twitter account your relay belongs to.
|
||||
- `bird check` — verify relay configuration and account access.
|
||||
- `bird likes [-n count] [--json]` — list your liked tweets.
|
||||
- `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 (fetches from For You, News, Sports, and Entertainment tabs by default).
|
||||
- `bird trending` — alias for `news` command.
|
||||
- `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] [--json]` — list users that you (or another user) follow.
|
||||
- `bird followers [--user <userId>] [-n count] [--json]` — list users that follow you (or another user).
|
||||
- `bird whoami` — print which Twitter account your relay belongs to.
|
||||
- `bird check` — verify relay configuration and account access.
|
||||
|
||||
Bookmarks flags:
|
||||
- `--expand-root-only`: expand threads only when the bookmark is a root tweet.
|
||||
- `--author-chain`: keep only the bookmarked author's connected self-reply chain.
|
||||
- `--author-only`: include all tweets from the bookmarked author within the thread.
|
||||
- `--full-chain-only`: keep the entire reply chain connected to the bookmarked tweet (all authors).
|
||||
- `--include-ancestor-branches`: include sibling branches for ancestors when using `--full-chain-only`.
|
||||
- `--include-parent`: include the direct parent tweet for non-root bookmarks.
|
||||
- `--thread-meta`: add thread metadata fields to each tweet.
|
||||
- `--sort-chronological`: sort output globally oldest to newest (default preserves bookmark order).
|
||||
|
||||
Global options:
|
||||
- `--relay-base-url <url>`: twitter safe relay base URL (defaults to `TWITTER_RELAY_BASE_URL`).
|
||||
- `--profile-name <name>`: twitter safe relay profile name (sent as `x-profile-name`).
|
||||
- `--timeout <ms>`: abort requests after the given timeout (milliseconds).
|
||||
- `--quote-depth <n>`: max quoted tweet depth in JSON output (default: 1; 0 disables).
|
||||
- `--plain`: stable output (no emoji, no color).
|
||||
@@ -200,14 +230,16 @@ Global options:
|
||||
|
||||
## Authentication (GraphQL)
|
||||
|
||||
`bird` does not handle Twitter authentication locally. It sends Twitter API-compatible requests to twitter safe relay,
|
||||
and the relay handles authentication.
|
||||
`bird` does not handle Twitter authentication locally. It sends Twitter API-compatible requests to
|
||||
[twitter safe relay](https://github.com/fa0311/twitter_api_safe_relay), and the relay handles authentication.
|
||||
|
||||
Write operations:
|
||||
- `tweet`/`reply` primarily use GraphQL (`CreateTweet`).
|
||||
- If GraphQL returns error `226` (“automated request”), `bird` falls back to the legacy `statuses/update.json` endpoint.
|
||||
|
||||
Configure the relay URL with `TWITTER_RELAY_BASE_URL` or `--relay-base-url`.
|
||||
When your relay has multiple profiles, select one with `--profile-name`, `BIRD_PROFILE_NAME`, or `profileName`
|
||||
in config; bird forwards it as the `x-profile-name` header.
|
||||
|
||||
## Config (JSON5)
|
||||
|
||||
@@ -221,6 +253,7 @@ Example `~/.config/bird/config.json5`:
|
||||
```json5
|
||||
{
|
||||
relayBaseUrl: "http://localhost:6900",
|
||||
profileName: "main",
|
||||
timeoutMs: 20000,
|
||||
quoteDepth: 1
|
||||
}
|
||||
@@ -228,6 +261,7 @@ Example `~/.config/bird/config.json5`:
|
||||
|
||||
Environment shortcuts:
|
||||
- `TWITTER_RELAY_BASE_URL`
|
||||
- `BIRD_PROFILE_NAME`
|
||||
- `BIRD_TIMEOUT_MS`
|
||||
- `BIRD_QUOTE_DEPTH`
|
||||
|
||||
@@ -270,6 +304,18 @@ When using `--json` with `following`/`followers`, user objects include:
|
||||
| `profileImageUrl` | string? | Profile image URL |
|
||||
| `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:
|
||||
|
||||
| Field | Type | Description |
|
||||
|
||||
@@ -22,6 +22,7 @@ Run:
|
||||
Notes:
|
||||
- Live tests are skipped unless `BIRD_LIVE=1` (set by `pnpm test:live`).
|
||||
- Search query is configurable via `BIRD_LIVE_SEARCH_QUERY`.
|
||||
- Follow/unfollow handle is configurable via `BIRD_LIVE_FOLLOW_HANDLE` (opt-in).
|
||||
- Command timeout is configurable via `BIRD_LIVE_TIMEOUT_MS` (ms).
|
||||
- Spawned CLI `NODE_ENV` defaults to `production` (override with `BIRD_LIVE_NODE_ENV`).
|
||||
- If you don't tweet, set `BIRD_LIVE_TWEET_ID` to a known tweet ID to use for `read/replies/thread`.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@yuta/bird",
|
||||
"version": "0.7.0",
|
||||
"version": "0.10.0",
|
||||
"description": "CLI tool for tweeting and replying via Twitter/X GraphQL API",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
|
||||
@@ -10,7 +10,12 @@ import path from 'node:path';
|
||||
const TARGET_OPERATIONS = [
|
||||
'CreateTweet',
|
||||
'CreateRetweet',
|
||||
'DeleteRetweet',
|
||||
'CreateFriendship',
|
||||
'DestroyFriendship',
|
||||
'FavoriteTweet',
|
||||
'UnfavoriteTweet',
|
||||
'CreateBookmark',
|
||||
'DeleteBookmark',
|
||||
'TweetDetail',
|
||||
'SearchTimeline',
|
||||
@@ -23,6 +28,7 @@ const TARGET_OPERATIONS = [
|
||||
'ExplorePage',
|
||||
'GenericTimelineById',
|
||||
'TrendHistory',
|
||||
'AboutAccountQuery',
|
||||
] as const;
|
||||
|
||||
type OperationName = (typeof TARGET_OPERATIONS)[number];
|
||||
|
||||
+10
-3
@@ -1,6 +1,7 @@
|
||||
import { Command } from 'commander';
|
||||
import { registerBookmarksCommand } from '../commands/bookmarks.js';
|
||||
import { registerCheckCommand } from '../commands/check.js';
|
||||
import { registerFollowCommands } from '../commands/follow.js';
|
||||
import { registerHelpCommand } from '../commands/help.js';
|
||||
import { registerHomeCommand } from '../commands/home.js';
|
||||
import { registerListsCommand } from '../commands/lists.js';
|
||||
@@ -26,8 +27,12 @@ export const KNOWN_COMMANDS = new Set([
|
||||
'mentions',
|
||||
'bookmarks',
|
||||
'unbookmark',
|
||||
'follow',
|
||||
'unfollow',
|
||||
'following',
|
||||
'followers',
|
||||
'user',
|
||||
'profiles',
|
||||
'likes',
|
||||
'lists',
|
||||
'list-timeline',
|
||||
@@ -93,7 +98,7 @@ export function createProgram(ctx: CliContext): Command {
|
||||
].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>`'),
|
||||
].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, 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(
|
||||
` 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.)`)}`,
|
||||
@@ -105,14 +110,15 @@ export function createProgram(ctx: CliContext): Command {
|
||||
`\n\n${ctx.colors.section('Config')}\n${ctx.colors.muted(
|
||||
` Reads ${ctx.colors.argument('~/.config/bird/config.json5')} and ${ctx.colors.argument('./.birdrc.json5')} (JSON5)`,
|
||||
)}\n${ctx.colors.muted(
|
||||
` Supports: relayBaseUrl, timeoutMs, quoteDepth`,
|
||||
` Supports: relayBaseUrl, profileName, timeoutMs, quoteDepth`,
|
||||
)}\n\n${ctx.colors.section('Env')}\n${ctx.colors.muted(
|
||||
` ${ctx.colors.option('TWITTER_RELAY_BASE_URL')}, ${ctx.colors.option('NO_COLOR')}, ${ctx.colors.option('BIRD_TIMEOUT_MS')}, ${ctx.colors.option('BIRD_QUOTE_DEPTH')}`,
|
||||
` ${ctx.colors.option('TWITTER_RELAY_BASE_URL')}, ${ctx.colors.option('BIRD_PROFILE_NAME')}, ${ctx.colors.option('NO_COLOR')}, ${ctx.colors.option('BIRD_TIMEOUT_MS')}, ${ctx.colors.option('BIRD_QUOTE_DEPTH')}`,
|
||||
)}`,
|
||||
);
|
||||
|
||||
program
|
||||
.option('--relay-base-url <url>', 'twitter safe relay base URL', ctx.config.relayBaseUrl)
|
||||
.option('--profile-name <name>', 'twitter safe relay profile name')
|
||||
.option('--media <path>', 'Attach media file (repeatable, up to 4 images or 1 video)', collect)
|
||||
.option('--alt <text>', 'Alt text for the corresponding --media (repeatable)', collect)
|
||||
.option('--timeout <ms>', 'Request timeout in milliseconds')
|
||||
@@ -132,6 +138,7 @@ export function createProgram(ctx: CliContext): Command {
|
||||
registerSearchCommands(program, ctx);
|
||||
registerBookmarksCommand(program, ctx);
|
||||
registerUnbookmarkCommand(program, ctx);
|
||||
registerFollowCommands(program, ctx);
|
||||
registerListsCommand(program, ctx);
|
||||
registerHomeCommand(program, ctx);
|
||||
registerUserCommands(program, ctx);
|
||||
|
||||
@@ -17,6 +17,7 @@ import type { TweetData } from '../lib/twitter-client.js';
|
||||
|
||||
export type BirdConfig = {
|
||||
relayBaseUrl?: string;
|
||||
profileName?: string;
|
||||
timeoutMs?: number;
|
||||
quoteDepth?: number;
|
||||
};
|
||||
@@ -44,6 +45,7 @@ export type CliContext = {
|
||||
applyOutputFromCommand: (command: Command) => void;
|
||||
resolveTimeoutFromOptions: (options: { timeout?: string | number }) => number | undefined;
|
||||
resolveQuoteDepthFromOptions: (options: { quoteDepth?: string | number }) => number | undefined;
|
||||
resolveProfileNameFromOptions: (opts: ProfileOptions) => string | undefined;
|
||||
resolveRelayBaseUrlFromOptions: (opts: RelayOptions) => string | undefined;
|
||||
loadMedia: (opts: { media: string[]; alts: string[] }) => MediaSpec[];
|
||||
printTweets: (tweets: TweetData[], opts?: { json?: boolean; emptyMessage?: string; showSeparator?: boolean }) => void;
|
||||
@@ -138,6 +140,10 @@ type RelayOptions = {
|
||||
relayBaseUrl?: string;
|
||||
};
|
||||
|
||||
type ProfileOptions = {
|
||||
profileName?: string;
|
||||
};
|
||||
|
||||
export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEnv = process.env): CliContext {
|
||||
const isTty = process.stdout.isTTY;
|
||||
let output: OutputConfig = resolveOutputConfigFromArgv(normalizedArgs, env, isTty);
|
||||
@@ -235,6 +241,10 @@ export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEn
|
||||
return opts.relayBaseUrl || config.relayBaseUrl || env.TWITTER_RELAY_BASE_URL;
|
||||
}
|
||||
|
||||
function resolveProfileNameFromOptions(opts: ProfileOptions): string | undefined {
|
||||
return opts.profileName || env.BIRD_PROFILE_NAME || config.profileName;
|
||||
}
|
||||
|
||||
function loadMedia(opts: { media: string[]; alts: string[] }): MediaSpec[] {
|
||||
if (opts.media.length === 0) {
|
||||
return [];
|
||||
@@ -367,6 +377,7 @@ export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEn
|
||||
applyOutputFromCommand,
|
||||
resolveTimeoutFromOptions,
|
||||
resolveQuoteDepthFromOptions,
|
||||
resolveProfileNameFromOptions,
|
||||
resolveRelayBaseUrlFromOptions,
|
||||
loadMedia,
|
||||
printTweets,
|
||||
|
||||
+167
-13
@@ -1,8 +1,10 @@
|
||||
import type { Command } from 'commander';
|
||||
import { parsePositiveIntFlag } from '../cli/pagination.js';
|
||||
import { parsePaginationFlags } from '../cli/pagination.js';
|
||||
import type { CliContext } from '../cli/shared.js';
|
||||
import { extractBookmarkFolderId } from '../lib/extract-bookmark-folder-id.js';
|
||||
import { addThreadMetadata, filterAuthorChain, filterAuthorOnly, filterFullChain } from '../lib/thread-filters.js';
|
||||
import { TwitterClient } from '../lib/twitter-client.js';
|
||||
import type { TweetData, TweetWithMeta } from '../lib/twitter-client-types.js';
|
||||
|
||||
export function registerBookmarksCommand(program: Command, ctx: CliContext): void {
|
||||
program
|
||||
@@ -13,6 +15,14 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
.option('--all', 'Fetch all bookmarks (paged)')
|
||||
.option('--max-pages <number>', 'Stop after N pages when using --all')
|
||||
.option('--cursor <string>', 'Resume pagination from a cursor')
|
||||
.option('--expand-root-only', 'Only expand threads when bookmarked tweet is root')
|
||||
.option('--author-chain', 'Only include author self-reply chains connected to the bookmark')
|
||||
.option('--author-only', 'Include all tweets from bookmarked tweet author in thread')
|
||||
.option('--full-chain-only', 'Save entire reply chain connected to the bookmarked tweet')
|
||||
.option('--include-ancestor-branches', 'Include sibling branches for ancestors when using --full-chain-only')
|
||||
.option('--include-parent', 'Include direct parent tweet for non-root bookmarks')
|
||||
.option('--thread-meta', 'Add metadata fields (isThread, threadPosition, etc.)')
|
||||
.option('--sort-chronological', 'Sort output globally oldest -> newest')
|
||||
.option('--json', 'Output as JSON')
|
||||
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
||||
.action(
|
||||
@@ -24,19 +34,29 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
cursor?: string;
|
||||
expandRootOnly?: boolean;
|
||||
authorChain?: boolean;
|
||||
authorOnly?: boolean;
|
||||
fullChainOnly?: boolean;
|
||||
includeAncestorBranches?: boolean;
|
||||
includeParent?: boolean;
|
||||
threadMeta?: boolean;
|
||||
sortChronological?: boolean;
|
||||
}) => {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPagesParsed = parsePositiveIntFlag(cmdOpts.maxPages, '--max-pages');
|
||||
if (!maxPagesParsed.ok) {
|
||||
console.error(`${ctx.p('err')}${maxPagesParsed.error}`);
|
||||
|
||||
const pagination = parsePaginationFlags(cmdOpts);
|
||||
if (!pagination.ok) {
|
||||
console.error(`${ctx.p('err')}${pagination.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const maxPages = maxPagesParsed.value;
|
||||
const maxPages = pagination.maxPages;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const usePagination = Boolean(cmdOpts.all || cmdOpts.cursor);
|
||||
const usePagination = pagination.usePagination;
|
||||
if (maxPages !== undefined && !usePagination) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
|
||||
process.exit(1);
|
||||
@@ -46,7 +66,7 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
const folderId = cmdOpts.folderId ? extractBookmarkFolderId(cmdOpts.folderId) : null;
|
||||
if (cmdOpts.folderId && !folderId) {
|
||||
console.error(`${ctx.p('err')}Invalid --folder-id. Expected numeric ID or https://x.com/i/bookmarks/<id>.`);
|
||||
@@ -54,7 +74,7 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
}
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const timelineOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: pagination.cursor };
|
||||
const result = folderId
|
||||
? usePagination
|
||||
? await client.getAllBookmarkFolderTimeline(folderId, paginationOptions)
|
||||
@@ -63,14 +83,148 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
||||
? await client.getAllBookmarks(paginationOptions)
|
||||
: await client.getBookmarks(count, timelineOptions);
|
||||
|
||||
if (result.success) {
|
||||
const emptyMessage = folderId ? 'No bookmarks found in folder.' : 'No bookmarks found.';
|
||||
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||
ctx.printTweetsResult(result, { json: isJson, usePagination, emptyMessage });
|
||||
} else {
|
||||
if (!result.success) {
|
||||
console.error(`${ctx.p('err')}Failed to fetch bookmarks: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (cmdOpts.authorChain && (cmdOpts.authorOnly || cmdOpts.fullChainOnly)) {
|
||||
console.error(
|
||||
`${ctx.p('warn')}--author-chain already limits to the connected self-reply chain; ` +
|
||||
'other chain filters are redundant.',
|
||||
);
|
||||
}
|
||||
if (cmdOpts.includeAncestorBranches && !cmdOpts.fullChainOnly) {
|
||||
console.error(`${ctx.p('warn')}--include-ancestor-branches only applies with --full-chain-only.`);
|
||||
}
|
||||
|
||||
const bookmarks = result.tweets;
|
||||
if (!bookmarks || bookmarks.length === 0) {
|
||||
const emptyMessage = folderId ? 'No bookmarks found in folder.' : 'No bookmarks found.';
|
||||
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||
ctx.printTweetsResult(result, { json: isJson, usePagination, emptyMessage });
|
||||
return;
|
||||
}
|
||||
|
||||
const expandedResults: TweetData[] = [];
|
||||
const threadCache = new Map<string, TweetData[]>();
|
||||
const includeMeta = Boolean(cmdOpts.threadMeta);
|
||||
const includeParent = Boolean(cmdOpts.includeParent);
|
||||
const expandRootOnly = Boolean(cmdOpts.expandRootOnly);
|
||||
const filterAuthorChainFlag = Boolean(cmdOpts.authorChain);
|
||||
const filterAuthorOnlyFlag = Boolean(cmdOpts.authorOnly);
|
||||
const filterFullChainFlag = Boolean(cmdOpts.fullChainOnly);
|
||||
const includeAncestorBranches = Boolean(cmdOpts.includeAncestorBranches) && filterFullChainFlag;
|
||||
const useChronologicalSort = Boolean(cmdOpts.sortChronological);
|
||||
|
||||
const shouldAttemptExpand =
|
||||
expandRootOnly || filterAuthorChainFlag || filterAuthorOnlyFlag || filterFullChainFlag;
|
||||
const shouldFetchThread = shouldAttemptExpand || includeMeta;
|
||||
|
||||
const fetchThread = async (tweet: TweetData): Promise<TweetData[] | null> => {
|
||||
const cachedKey = tweet.conversationId ?? tweet.id;
|
||||
const cached = threadCache.get(cachedKey);
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const threadResult = await client.getThread(tweet.id, { includeRaw });
|
||||
if (!threadResult.success) {
|
||||
console.error(
|
||||
`${ctx.p('warn')}Failed to expand thread for ${tweet.id}: ${threadResult.error ?? 'Unknown error'}`,
|
||||
);
|
||||
return null;
|
||||
}
|
||||
if (!threadResult.tweets) {
|
||||
console.error(`${ctx.p('warn')}No thread tweets returned for ${tweet.id}.`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const rootKey = threadResult.tweets[0]?.conversationId ?? cachedKey;
|
||||
threadCache.set(rootKey, threadResult.tweets);
|
||||
return threadResult.tweets;
|
||||
};
|
||||
|
||||
const delayBetweenExpansionsMs = 1000;
|
||||
|
||||
for (let index = 0; index < bookmarks.length; index += 1) {
|
||||
const bookmark = bookmarks[index];
|
||||
const isRoot = !bookmark.inReplyToStatusId;
|
||||
let threadTweets: TweetData[] | null = null;
|
||||
|
||||
if (shouldFetchThread) {
|
||||
if (!expandRootOnly || isRoot || includeMeta) {
|
||||
if (index > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, delayBetweenExpansionsMs));
|
||||
}
|
||||
threadTweets = await fetchThread(bookmark);
|
||||
}
|
||||
}
|
||||
|
||||
let outputTweets: TweetData[] = [bookmark];
|
||||
|
||||
if (shouldAttemptExpand) {
|
||||
if (expandRootOnly && !isRoot) {
|
||||
outputTweets = [bookmark];
|
||||
} else if (threadTweets) {
|
||||
if (filterAuthorChainFlag) {
|
||||
outputTweets = filterAuthorChain(threadTweets, bookmark);
|
||||
} else {
|
||||
outputTweets = filterFullChainFlag
|
||||
? filterFullChain(threadTweets, bookmark, { includeAncestorBranches })
|
||||
: threadTweets;
|
||||
if (filterAuthorOnlyFlag) {
|
||||
outputTweets = filterAuthorOnly(outputTweets, bookmark);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (includeParent && bookmark.inReplyToStatusId) {
|
||||
const alreadyIncluded = outputTweets.some((tweet) => tweet.id === bookmark.inReplyToStatusId);
|
||||
if (!alreadyIncluded) {
|
||||
const parentFromThread = threadTweets?.find((tweet) => tweet.id === bookmark.inReplyToStatusId);
|
||||
if (parentFromThread) {
|
||||
expandedResults.push(parentFromThread);
|
||||
} else {
|
||||
const parentResult = await client.getTweet(bookmark.inReplyToStatusId, { includeRaw });
|
||||
if (parentResult.success && parentResult.tweet) {
|
||||
expandedResults.push(parentResult.tweet);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expandedResults.push(...outputTweets);
|
||||
}
|
||||
|
||||
let finalResults: Array<TweetData | TweetWithMeta> = expandedResults;
|
||||
if (includeMeta) {
|
||||
finalResults = expandedResults.map((tweet) => {
|
||||
const cacheKey = tweet.conversationId ?? tweet.id;
|
||||
let conversationTweets = threadCache.get(cacheKey);
|
||||
if (!conversationTweets) {
|
||||
conversationTweets = [tweet];
|
||||
}
|
||||
return addThreadMetadata(tweet, conversationTweets);
|
||||
});
|
||||
}
|
||||
|
||||
const uniqueTweets = Array.from(new Map(finalResults.map((tweet) => [tweet.id, tweet])).values());
|
||||
if (useChronologicalSort) {
|
||||
uniqueTweets.sort((a, b) => {
|
||||
const aTime = a.createdAt ? Date.parse(a.createdAt) : 0;
|
||||
const bTime = b.createdAt ? Date.parse(b.createdAt) : 0;
|
||||
return aTime - bTime;
|
||||
});
|
||||
}
|
||||
|
||||
const emptyMessage = folderId ? 'No bookmarks found in folder.' : 'No bookmarks found.';
|
||||
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||
ctx.printTweetsResult(
|
||||
{ tweets: uniqueTweets, nextCursor: result.nextCursor },
|
||||
{ json: isJson, usePagination, emptyMessage },
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ export function registerCheckCommand(program: Command, ctx: CliContext): void {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
console.log(`${ctx.p('info')}Relay check`);
|
||||
console.log('-'.repeat(40));
|
||||
@@ -21,7 +22,7 @@ export function registerCheckCommand(program: Command, ctx: CliContext): void {
|
||||
|
||||
console.log(`${ctx.p('ok')}relay: ${relayBaseUrl}`);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
const result = await client.getCurrentUser();
|
||||
|
||||
if (result.success && result.user) {
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { Command } from 'commander';
|
||||
import type { CliContext } from '../cli/shared.js';
|
||||
import { normalizeHandle } from '../lib/normalize-handle.js';
|
||||
import { TwitterClient } from '../lib/twitter-client.js';
|
||||
|
||||
const ONLY_DIGITS_REGEX = /^\d+$/;
|
||||
|
||||
async function resolveUserId(
|
||||
client: TwitterClient,
|
||||
usernameOrId: string,
|
||||
ctx: CliContext,
|
||||
): Promise<{ userId: string; username?: string } | null> {
|
||||
const raw = usernameOrId.trim();
|
||||
const isNumeric = ONLY_DIGITS_REGEX.test(raw);
|
||||
|
||||
// Otherwise, treat as username and look up
|
||||
const handle = normalizeHandle(raw);
|
||||
if (handle) {
|
||||
const lookup = await client.getUserIdByUsername(handle);
|
||||
if (lookup.success && lookup.userId) {
|
||||
return { userId: lookup.userId, username: lookup.username };
|
||||
}
|
||||
if (!isNumeric) {
|
||||
console.error(`${ctx.p('err')}Failed to find user @${handle}: ${lookup.error ?? 'Unknown error'}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
if (isNumeric) {
|
||||
return { userId: raw };
|
||||
}
|
||||
|
||||
console.error(`${ctx.p('err')}Invalid username: ${usernameOrId}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
export function registerFollowCommands(program: Command, ctx: CliContext): void {
|
||||
program
|
||||
.command('follow')
|
||||
.description('Follow a user')
|
||||
.argument('<username-or-id>', 'Username (with or without @) or user ID to follow')
|
||||
.action(async (usernameOrId: string) => {
|
||||
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 resolved = await resolveUserId(client, usernameOrId, ctx);
|
||||
if (!resolved) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { userId, username } = resolved;
|
||||
const displayName = username ? `@${username}` : userId;
|
||||
|
||||
const result = await client.follow(userId);
|
||||
if (result.success) {
|
||||
const finalName = result.username ? `@${result.username}` : displayName;
|
||||
console.log(`${ctx.p('ok')}Now following ${finalName}`);
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to follow ${displayName}: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command('unfollow')
|
||||
.description('Unfollow a user')
|
||||
.argument('<username-or-id>', 'Username (with or without @) or user ID to unfollow')
|
||||
.action(async (usernameOrId: string) => {
|
||||
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 resolved = await resolveUserId(client, usernameOrId, ctx);
|
||||
if (!resolved) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { userId, username } = resolved;
|
||||
const displayName = username ? `@${username}` : userId;
|
||||
|
||||
const result = await client.unfollow(userId);
|
||||
if (result.success) {
|
||||
const finalName = result.username ? `@${result.username}` : displayName;
|
||||
console.log(`${ctx.p('ok')}Unfollowed ${finalName}`);
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to unfollow ${displayName}: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
+45
-6
@@ -1,4 +1,5 @@
|
||||
import type { Command } from 'commander';
|
||||
import { parsePaginationFlags } from '../cli/pagination.js';
|
||||
import type { CliContext } from '../cli/shared.js';
|
||||
import { TwitterClient } from '../lib/twitter-client.js';
|
||||
|
||||
@@ -7,35 +8,73 @@ export function registerHomeCommand(program: Command, ctx: CliContext): void {
|
||||
.command('home')
|
||||
.description('Get your home timeline ("For You" feed)')
|
||||
.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('--json', 'Output as JSON')
|
||||
.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(
|
||||
async (cmdOpts: {
|
||||
count?: string;
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
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) {
|
||||
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
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
|
||||
? await client.getHomeLatestTimeline(count, { includeRaw })
|
||||
: await client.getHomeTimeline(count, { includeRaw });
|
||||
? await client.getHomeLatestTimeline(count, fetchOptions)
|
||||
: await client.getHomeTimeline(count, fetchOptions);
|
||||
|
||||
if (result.success) {
|
||||
const feedType = cmdOpts.following ? 'Following' : 'For You';
|
||||
const emptyMessage = `No tweets found in ${feedType} timeline.`;
|
||||
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||
ctx.printTweets(result.tweets, { json: isJson, emptyMessage });
|
||||
ctx.printTweetsResult(result, {
|
||||
json: isJson,
|
||||
usePagination,
|
||||
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);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -43,8 +43,9 @@ export function registerListsCommand(program: Command, ctx: CliContext): void {
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '100', 10);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
|
||||
const result = cmdOpts.memberOf ? await client.getListMemberships(count) : await client.getOwnedLists(count);
|
||||
|
||||
@@ -109,8 +110,9 @@ export function registerListsCommand(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const timelineOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages: pagination.maxPages, cursor: pagination.cursor };
|
||||
|
||||
@@ -102,6 +102,7 @@ export function registerNewsCommand(program: Command, ctx: CliContext): void {
|
||||
const count = Number.parseInt(cmdOpts.count || '10', 10);
|
||||
const tweetsPerItem = Number.parseInt(cmdOpts.tweetsPerItem || '5', 10);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
if (Number.isNaN(count) || count < 1) {
|
||||
console.error(`${ctx.p('err')}--count must be a positive number`);
|
||||
@@ -134,7 +135,7 @@ export function registerNewsCommand(program: Command, ctx: CliContext): void {
|
||||
// If no specific tabs selected, use defaults (all tabs except trending)
|
||||
const tabsToFetch = tabs.length > 0 ? tabs : undefined;
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const withTweets = cmdOpts.withTweets ?? false;
|
||||
const aiOnly = cmdOpts.aiOnly ?? false;
|
||||
|
||||
@@ -41,7 +41,8 @@ export function registerPostCommands(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const mediaIds = await uploadMediaOrExit(client, media, ctx);
|
||||
const result = await client.tweet(text, mediaIds);
|
||||
|
||||
@@ -72,9 +73,10 @@ export function registerPostCommands(program: Command, ctx: CliContext): void {
|
||||
}
|
||||
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
console.error(`${ctx.p('info')}Replying to tweet: ${tweetId}`);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const mediaIds = await uploadMediaOrExit(client, media, ctx);
|
||||
const result = await client.reply(text, tweetId, mediaIds);
|
||||
|
||||
|
||||
@@ -18,8 +18,9 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
||||
|
||||
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const result = await client.getTweet(tweetId, { includeRaw });
|
||||
|
||||
@@ -69,8 +70,9 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
|
||||
const result = pagination.usePagination
|
||||
@@ -136,8 +138,9 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
|
||||
const result = pagination.usePagination
|
||||
|
||||
+25
-12
@@ -1,7 +1,9 @@
|
||||
import type { Command } from 'commander';
|
||||
import { type Command, Option } from 'commander';
|
||||
import { parsePaginationFlags } from '../cli/pagination.js';
|
||||
import type { CliContext } from '../cli/shared.js';
|
||||
import { mentionsQueryFromUserOption, normalizeHandle } from '../lib/normalize-handle.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 {
|
||||
program
|
||||
@@ -12,6 +14,11 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
.option('--all', 'Fetch all search results (paged)')
|
||||
.option('--max-pages <number>', 'Stop after N pages when using --all')
|
||||
.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-full', 'Output as JSON with full raw API response in _raw field')
|
||||
.action(
|
||||
@@ -22,6 +29,7 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
cursor?: string;
|
||||
product?: SearchProduct;
|
||||
json?: boolean;
|
||||
jsonFull?: boolean;
|
||||
},
|
||||
@@ -30,10 +38,17 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '10', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
const pagination = parsePaginationFlags(cmdOpts);
|
||||
if (!pagination.ok) {
|
||||
console.error(`${ctx.p('err')}${pagination.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const maxPages = pagination.maxPages;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const usePagination = pagination.usePagination;
|
||||
if (maxPages !== undefined && !usePagination) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
|
||||
process.exit(1);
|
||||
@@ -42,15 +57,12 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const searchOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||
const product = cmdOpts.product ?? 'Latest';
|
||||
const searchOptions = { includeRaw, product };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: pagination.cursor, product };
|
||||
const result = usePagination
|
||||
? await client.getAllSearchResults(query, paginationOptions)
|
||||
: await client.search(query, count, searchOptions);
|
||||
@@ -90,8 +102,9 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
||||
|
||||
let query: string | null = fromUserOpt.query;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
|
||||
if (!query) {
|
||||
const who = await client.getCurrentUser();
|
||||
|
||||
@@ -11,8 +11,9 @@ export function registerUnbookmarkCommand(program: Command, ctx: CliContext): vo
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
let failures = 0;
|
||||
|
||||
for (const input of tweetIdOrUrls) {
|
||||
|
||||
@@ -87,8 +87,9 @@ export function registerUserTweetsCommand(program: Command, ctx: CliContext): vo
|
||||
process.exit(2);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
|
||||
// Look up user ID from username
|
||||
console.error(`${ctx.p('info')}Looking up @${username}...`);
|
||||
|
||||
+312
-281
@@ -1,309 +1,304 @@
|
||||
import type { Command } from 'commander';
|
||||
import type { CliContext } from '../cli/shared.js';
|
||||
import { normalizeHandle } from '../lib/normalize-handle.js';
|
||||
import { TwitterClient } from '../lib/twitter-client.js';
|
||||
import type { 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[] {
|
||||
const lines: string[] = [`${ctx.p('info')}Account information for @${handle}:`];
|
||||
if (profile.accountBasedIn) {
|
||||
lines.push(` Account based in: ${profile.accountBasedIn}`);
|
||||
}
|
||||
if (profile.createdCountryAccurate !== undefined) {
|
||||
lines.push(` Creation country accurate: ${profile.createdCountryAccurate ? 'Yes' : 'No'}`);
|
||||
}
|
||||
if (profile.locationAccurate !== undefined) {
|
||||
lines.push(` Location accurate: ${profile.locationAccurate ? 'Yes' : 'No'}`);
|
||||
}
|
||||
if (profile.source) {
|
||||
lines.push(`${ctx.l('source')}${profile.source}`);
|
||||
}
|
||||
if (profile.learnMoreUrl) {
|
||||
lines.push(` Learn more: ${profile.learnMoreUrl}`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
type PagedUsersResult = {
|
||||
success: boolean;
|
||||
users?: TwitterUser[];
|
||||
nextCursor?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type UserListCommandOpts = {
|
||||
user?: string;
|
||||
count?: string;
|
||||
cursor?: string;
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
json?: boolean;
|
||||
};
|
||||
|
||||
type UserListCommandSpec = {
|
||||
name: 'following' | 'followers';
|
||||
description: string;
|
||||
fetch: (
|
||||
client: TwitterClient,
|
||||
userId: string,
|
||||
count: number,
|
||||
cursor: string | undefined,
|
||||
) => Promise<PagedUsersResult>;
|
||||
};
|
||||
|
||||
function printUsers(users: TwitterUser[], ctx: CliContext): void {
|
||||
for (const user of users) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
}
|
||||
|
||||
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(
|
||||
client: TwitterClient,
|
||||
requestedUserId: string | undefined,
|
||||
ctx: CliContext,
|
||||
): Promise<string> {
|
||||
if (requestedUserId) {
|
||||
return requestedUserId;
|
||||
}
|
||||
|
||||
const currentUser = await client.getCurrentUser();
|
||||
if (!currentUser.success || !currentUser.user?.id) {
|
||||
console.error(`${ctx.p('err')}Failed to get current user: ${currentUser.error || 'Unknown error'}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
return currentUser.user.id;
|
||||
}
|
||||
|
||||
async function runUserListCommand(
|
||||
program: Command,
|
||||
ctx: CliContext,
|
||||
spec: UserListCommandSpec,
|
||||
cmdOpts: UserListCommandOpts,
|
||||
) {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !cmdOpts.all) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
const userId = await resolveUserIdOrExit(client, cmdOpts.user, ctx);
|
||||
|
||||
if (cmdOpts.all) {
|
||||
const allUsers: TwitterUser[] = [];
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | undefined = cmdOpts.cursor;
|
||||
let pageNum = 0;
|
||||
let nextCursor: string | undefined;
|
||||
|
||||
while (true) {
|
||||
pageNum += 1;
|
||||
if (!cmdOpts.json) {
|
||||
console.error(`${ctx.p('info')}Fetching page ${pageNum}...`);
|
||||
}
|
||||
|
||||
const result = await spec.fetch(client, userId, count, cursor);
|
||||
|
||||
if (!result.success || !result.users) {
|
||||
console.error(`${ctx.p('err')}Failed to fetch ${spec.name}: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let added = 0;
|
||||
for (const user of result.users) {
|
||||
if (!seen.has(user.id)) {
|
||||
seen.add(user.id);
|
||||
allUsers.push(user);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const pageCursor = result.nextCursor;
|
||||
if (!pageCursor || result.users.length === 0 || added === 0 || pageCursor === cursor) {
|
||||
nextCursor = undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
if (maxPages && pageNum >= maxPages) {
|
||||
nextCursor = pageCursor;
|
||||
break;
|
||||
}
|
||||
|
||||
cursor = pageCursor;
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
if (cmdOpts.json) {
|
||||
console.log(JSON.stringify({ users: allUsers, nextCursor: nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.error(`${ctx.p('info')}Total: ${allUsers.length} users`);
|
||||
if (nextCursor) {
|
||||
console.error(`${ctx.p('info')}Stopped at --max-pages. Use --cursor to continue.`);
|
||||
console.error(`${ctx.p('info')}Next cursor: ${nextCursor}`);
|
||||
}
|
||||
printUsers(allUsers, ctx);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await spec.fetch(client, userId, count, cmdOpts.cursor);
|
||||
if (result.success && result.users) {
|
||||
if (cmdOpts.json) {
|
||||
if (usePagination) {
|
||||
console.log(JSON.stringify({ users: result.users, nextCursor: result.nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.log(JSON.stringify(result.users, null, 2));
|
||||
}
|
||||
} else {
|
||||
if (result.users.length === 0) {
|
||||
console.log('No users found.');
|
||||
} else {
|
||||
printUsers(result.users, ctx);
|
||||
if (result.nextCursor) {
|
||||
console.error(`${ctx.p('info')}Next cursor: ${result.nextCursor}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to fetch ${spec.name}: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
const registerUserListCommand = (spec: UserListCommandSpec): void => {
|
||||
program
|
||||
.command('following')
|
||||
.description('Get users that you (or another user) follow')
|
||||
.option('--user <userId>', 'User ID to get following for (defaults to current user)')
|
||||
.command(spec.name)
|
||||
.description(spec.description)
|
||||
.option('--user <userId>', `User ID to get ${spec.name} for (defaults to current user)`)
|
||||
.option('-n, --count <number>', 'Number of users to fetch per page', '20')
|
||||
.option('--cursor <cursor>', 'Cursor for pagination (from previous response)')
|
||||
.option('--all', 'Fetch all users (paginate automatically)')
|
||||
.option('--max-pages <number>', 'Stop after N pages when using --all')
|
||||
.option('--json', 'Output as JSON')
|
||||
.action(
|
||||
async (cmdOpts: {
|
||||
user?: string;
|
||||
count?: string;
|
||||
cursor?: string;
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
json?: boolean;
|
||||
}) => {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
.action(async (cmdOpts: UserListCommandOpts) => runUserListCommand(program, ctx, spec, cmdOpts));
|
||||
};
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !cmdOpts.all) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
registerUserListCommand({
|
||||
name: 'following',
|
||||
description: 'Get users that you (or another user) follow',
|
||||
fetch: (client, userId, count, cursor) => client.getFollowing(userId, count, cursor),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
|
||||
let userId = cmdOpts.user;
|
||||
if (!userId) {
|
||||
const currentUser = await client.getCurrentUser();
|
||||
if (!currentUser.success || !currentUser.user?.id) {
|
||||
console.error(`${ctx.p('err')}Failed to get current user: ${currentUser.error || 'Unknown error'}`);
|
||||
process.exit(1);
|
||||
}
|
||||
userId = currentUser.user.id;
|
||||
}
|
||||
|
||||
if (cmdOpts.all) {
|
||||
// Fetch all pages
|
||||
const allUsers: TwitterUser[] = [];
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | undefined = cmdOpts.cursor;
|
||||
let pageNum = 0;
|
||||
let nextCursor: string | undefined;
|
||||
|
||||
while (true) {
|
||||
pageNum++;
|
||||
if (!cmdOpts.json) {
|
||||
console.error(`${ctx.p('info')}Fetching page ${pageNum}...`);
|
||||
}
|
||||
|
||||
const result = await client.getFollowing(userId, count, cursor);
|
||||
|
||||
if (!result.success || !result.users) {
|
||||
console.error(`${ctx.p('err')}Failed to fetch following: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let added = 0;
|
||||
for (const user of result.users) {
|
||||
if (!seen.has(user.id)) {
|
||||
seen.add(user.id);
|
||||
allUsers.push(user);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const pageCursor = result.nextCursor;
|
||||
if (!pageCursor || result.users.length === 0 || added === 0 || pageCursor === cursor) {
|
||||
nextCursor = undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
if (maxPages && pageNum >= maxPages) {
|
||||
nextCursor = pageCursor;
|
||||
break;
|
||||
}
|
||||
|
||||
cursor = pageCursor;
|
||||
|
||||
// Rate limit: wait between pages to avoid overwhelming the API
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
if (cmdOpts.json) {
|
||||
console.log(JSON.stringify({ users: allUsers, nextCursor: nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.error(`${ctx.p('info')}Total: ${allUsers.length} users`);
|
||||
if (nextCursor) {
|
||||
console.error(`${ctx.p('info')}Stopped at --max-pages. Use --cursor to continue.`);
|
||||
console.error(`${ctx.p('info')}Next cursor: ${nextCursor}`);
|
||||
}
|
||||
for (const user of allUsers) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single page fetch
|
||||
const result = await client.getFollowing(userId, count, cmdOpts.cursor);
|
||||
|
||||
if (result.success && result.users) {
|
||||
if (cmdOpts.json) {
|
||||
if (usePagination) {
|
||||
console.log(JSON.stringify({ users: result.users, nextCursor: result.nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.log(JSON.stringify(result.users, null, 2));
|
||||
}
|
||||
} else {
|
||||
if (result.users.length === 0) {
|
||||
console.log('No users found.');
|
||||
} else {
|
||||
for (const user of result.users) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
if (result.nextCursor) {
|
||||
console.error(`${ctx.p('info')}Next cursor: ${result.nextCursor}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to fetch following: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
registerUserListCommand({
|
||||
name: 'followers',
|
||||
description: 'Get users that follow you (or another user)',
|
||||
fetch: (client, userId, count, cursor) => client.getFollowers(userId, count, cursor),
|
||||
});
|
||||
|
||||
program
|
||||
.command('followers')
|
||||
.description('Get users that follow you (or another user)')
|
||||
.option('--user <userId>', 'User ID to get followers for (defaults to current user)')
|
||||
.option('-n, --count <number>', 'Number of users to fetch per page', '20')
|
||||
.option('--cursor <cursor>', 'Cursor for pagination (from previous response)')
|
||||
.option('--all', 'Fetch all users (paginate automatically)')
|
||||
.option('--max-pages <number>', 'Stop after N pages when using --all')
|
||||
.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 (cmdOpts: {
|
||||
user?: string;
|
||||
count?: string;
|
||||
cursor?: string;
|
||||
all?: boolean;
|
||||
maxPages?: string;
|
||||
json?: boolean;
|
||||
}) => {
|
||||
.action(async (target: string, cmdOpts: { json?: boolean }) => {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !cmdOpts.all) {
|
||||
console.error(`${ctx.p('err')}--max-pages requires --all.`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||
process.exit(1);
|
||||
}
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
const result = await client.getUserProfile(target);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||
|
||||
let userId = cmdOpts.user;
|
||||
if (!userId) {
|
||||
const currentUser = await client.getCurrentUser();
|
||||
if (!currentUser.success || !currentUser.user?.id) {
|
||||
console.error(`${ctx.p('err')}Failed to get current user: ${currentUser.error || 'Unknown error'}`);
|
||||
if (!result.success) {
|
||||
console.error(`${ctx.p('err')}Failed to resolve user: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
userId = currentUser.user.id;
|
||||
}
|
||||
|
||||
if (cmdOpts.all) {
|
||||
// Fetch all pages
|
||||
const allUsers: TwitterUser[] = [];
|
||||
const seen = new Set<string>();
|
||||
let cursor: string | undefined = cmdOpts.cursor;
|
||||
let pageNum = 0;
|
||||
let nextCursor: string | undefined;
|
||||
|
||||
while (true) {
|
||||
pageNum++;
|
||||
if (!cmdOpts.json) {
|
||||
console.error(`${ctx.p('info')}Fetching page ${pageNum}...`);
|
||||
}
|
||||
|
||||
const result = await client.getFollowers(userId, count, cursor);
|
||||
|
||||
if (!result.success || !result.users) {
|
||||
console.error(`${ctx.p('err')}Failed to fetch followers: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
let added = 0;
|
||||
for (const user of result.users) {
|
||||
if (!seen.has(user.id)) {
|
||||
seen.add(user.id);
|
||||
allUsers.push(user);
|
||||
added += 1;
|
||||
}
|
||||
}
|
||||
|
||||
const pageCursor = result.nextCursor;
|
||||
if (!pageCursor || result.users.length === 0 || added === 0 || pageCursor === cursor) {
|
||||
nextCursor = undefined;
|
||||
break;
|
||||
}
|
||||
|
||||
if (maxPages && pageNum >= maxPages) {
|
||||
nextCursor = pageCursor;
|
||||
break;
|
||||
}
|
||||
|
||||
cursor = pageCursor;
|
||||
|
||||
// Rate limit: wait between pages to avoid overwhelming the API
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
|
||||
if (cmdOpts.json) {
|
||||
console.log(JSON.stringify({ users: allUsers, nextCursor: nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.error(`${ctx.p('info')}Total: ${allUsers.length} users`);
|
||||
if (nextCursor) {
|
||||
console.error(`${ctx.p('info')}Stopped at --max-pages. Use --cursor to continue.`);
|
||||
console.error(`${ctx.p('info')}Next cursor: ${nextCursor}`);
|
||||
console.log(JSON.stringify(result.profile, null, 2));
|
||||
return;
|
||||
}
|
||||
for (const user of allUsers) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single page fetch
|
||||
const result = await client.getFollowers(userId, count, cmdOpts.cursor);
|
||||
printProfile(result.profile, ctx);
|
||||
});
|
||||
|
||||
if (result.success && result.users) {
|
||||
if (cmdOpts.json) {
|
||||
if (usePagination) {
|
||||
console.log(JSON.stringify({ users: result.users, nextCursor: result.nextCursor ?? null }, null, 2));
|
||||
} else {
|
||||
console.log(JSON.stringify(result.users, null, 2));
|
||||
}
|
||||
} else {
|
||||
if (result.users.length === 0) {
|
||||
console.log('No users found.');
|
||||
} else {
|
||||
for (const user of result.users) {
|
||||
console.log(`@${user.username} (${user.name})`);
|
||||
if (user.description) {
|
||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||
}
|
||||
if (user.followersCount !== undefined) {
|
||||
console.log(` ${ctx.p('info')}${user.followersCount.toLocaleString()} followers`);
|
||||
}
|
||||
console.log('──────────────────────────────────────────────────');
|
||||
}
|
||||
if (result.nextCursor) {
|
||||
console.error(`${ctx.p('info')}Next cursor: ${result.nextCursor}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to fetch followers: ${result.error}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
},
|
||||
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
|
||||
.command('likes')
|
||||
.description('Get your liked tweets')
|
||||
@@ -328,6 +323,7 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||
if (maxPages !== undefined && !usePagination) {
|
||||
@@ -343,7 +339,7 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||
const timelineOptions = { includeRaw };
|
||||
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||
@@ -373,8 +369,9 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs, quoteDepth });
|
||||
const result = await client.getCurrentUser();
|
||||
|
||||
if (result.success && result.user) {
|
||||
@@ -387,4 +384,38 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
|
||||
program
|
||||
.command('about')
|
||||
.description('Get account origin and location information for a user')
|
||||
.argument('<username>', 'Twitter username (with or without @)')
|
||||
.option('--json', 'Output as JSON')
|
||||
.action(async (username: string, cmdOpts: { json?: boolean }) => {
|
||||
const opts = program.opts();
|
||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||
const normalizedHandle = normalizeHandle(username);
|
||||
|
||||
if (!normalizedHandle) {
|
||||
console.error(`${ctx.p('err')}Invalid username: ${username}`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||
const profileName = ctx.resolveProfileNameFromOptions(opts);
|
||||
const client = new TwitterClient({ relayBaseUrl, profileName, timeoutMs });
|
||||
const result = await client.getUserAboutAccount(normalizedHandle);
|
||||
|
||||
if (result.success && result.aboutProfile) {
|
||||
if (cmdOpts.json) {
|
||||
console.log(JSON.stringify(result.aboutProfile, null, 2));
|
||||
} else {
|
||||
for (const line of formatAboutProfile(result.aboutProfile, ctx, normalizedHandle)) {
|
||||
console.log(line);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.error(`${ctx.p('err')}Failed to fetch account information: ${result.error ?? 'Unknown error'}`);
|
||||
process.exit(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+13
-1
@@ -1,5 +1,17 @@
|
||||
{
|
||||
"global": {
|
||||
"responsive_web_grok_annotations_enabled": false
|
||||
"responsive_web_grok_annotations_enabled": false,
|
||||
"post_ctas_fetch_enabled": true,
|
||||
"responsive_web_graphql_exclude_directive_enabled": true
|
||||
},
|
||||
"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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-2
@@ -11,7 +11,16 @@ export {
|
||||
} from './twitter-client.js';
|
||||
export type { HomeTimelineFetchOptions } from './twitter-client-home.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 { TweetFetchOptions } from './twitter-client-tweet-detail.js';
|
||||
export type { TweetResult, UploadMediaResult } from './twitter-client-types.js';
|
||||
export type {
|
||||
AboutAccountProfile,
|
||||
AboutAccountResult,
|
||||
TweetResult,
|
||||
UploadMediaResult,
|
||||
} from './twitter-client-types.js';
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
{
|
||||
"CreateTweet": "nmdAQXJDxw6-0KKF2on7eA",
|
||||
"CreateRetweet": "LFho5rIi4xcKO90p9jwG7A",
|
||||
"CreateFriendship": "8h9JVdV8dlSyqyRDJEPCsA",
|
||||
"DestroyFriendship": "ppXWuagMNXgvzx6WoXBW0Q",
|
||||
"FavoriteTweet": "lI07N6Otwv1PhnEgXILM7A",
|
||||
"DeleteBookmark": "Wlmlj2-xzyS1GN3a6cj-mQ",
|
||||
"TweetDetail": "_NvJCnIjOW__EP5-RF197A",
|
||||
@@ -13,5 +15,6 @@
|
||||
"ExploreSidebar": "lpSN4M6qpimkF4nRFPE3nQ",
|
||||
"ExplorePage": "kheAINB_4pzRDqkzG3K-ng",
|
||||
"GenericTimelineById": "uGSr7alSjR9v6QJAIaqSKQ",
|
||||
"TrendHistory": "Sj4T-jSB9pr0Mxtsc1UKZQ"
|
||||
"TrendHistory": "Sj4T-jSB9pr0Mxtsc1UKZQ",
|
||||
"AboutAccountQuery": "zs_jFPFT78rBpXv9Z3U2YQ"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,146 @@
|
||||
import type { TweetData, TweetWithMeta } from './twitter-client-types.js';
|
||||
|
||||
const sortByCreatedAt = (tweets: TweetData[]): TweetData[] =>
|
||||
tweets.slice().sort((a, b) => {
|
||||
const aTime = a.createdAt ? Date.parse(a.createdAt) : 0;
|
||||
const bTime = b.createdAt ? Date.parse(b.createdAt) : 0;
|
||||
return aTime - bTime;
|
||||
});
|
||||
|
||||
export function filterAuthorChain(tweets: TweetData[], bookmarkedTweet: TweetData): TweetData[] {
|
||||
const author = bookmarkedTweet.author.username;
|
||||
const byId = new Map(tweets.map((tweet) => [tweet.id, tweet]));
|
||||
const chainIds = new Set<string>();
|
||||
|
||||
let current: TweetData | undefined = bookmarkedTweet;
|
||||
while (current && current.author.username === author) {
|
||||
chainIds.add(current.id);
|
||||
const parentId = current.inReplyToStatusId;
|
||||
if (!parentId) {
|
||||
break;
|
||||
}
|
||||
const parent = byId.get(parentId);
|
||||
if (!parent || parent.author.username !== author) {
|
||||
break;
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
|
||||
let changed = true;
|
||||
while (changed) {
|
||||
changed = false;
|
||||
for (const tweet of tweets) {
|
||||
if (tweet.author.username !== author) {
|
||||
continue;
|
||||
}
|
||||
if (chainIds.has(tweet.id)) {
|
||||
continue;
|
||||
}
|
||||
if (tweet.inReplyToStatusId && chainIds.has(tweet.inReplyToStatusId)) {
|
||||
chainIds.add(tweet.id);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return sortByCreatedAt(tweets.filter((tweet) => chainIds.has(tweet.id)));
|
||||
}
|
||||
|
||||
export function filterAuthorOnly(tweets: TweetData[], bookmarkedTweet: TweetData): TweetData[] {
|
||||
const author = bookmarkedTweet.author.username;
|
||||
return tweets.filter((tweet) => tweet.author.username === author);
|
||||
}
|
||||
|
||||
export function filterFullChain(
|
||||
tweets: TweetData[],
|
||||
bookmarkedTweet: TweetData,
|
||||
options: { includeAncestorBranches?: boolean } = {},
|
||||
): TweetData[] {
|
||||
const byId = new Map(tweets.map((tweet) => [tweet.id, tweet]));
|
||||
const repliesByParent = new Map<string, TweetData[]>();
|
||||
|
||||
for (const tweet of tweets) {
|
||||
if (!tweet.inReplyToStatusId) {
|
||||
continue;
|
||||
}
|
||||
const list = repliesByParent.get(tweet.inReplyToStatusId) ?? [];
|
||||
list.push(tweet);
|
||||
repliesByParent.set(tweet.inReplyToStatusId, list);
|
||||
}
|
||||
|
||||
const chainIds = new Set<string>();
|
||||
const ancestorIds: string[] = [];
|
||||
|
||||
chainIds.add(bookmarkedTweet.id);
|
||||
let current: TweetData | undefined = bookmarkedTweet;
|
||||
while (current?.inReplyToStatusId) {
|
||||
const parent = byId.get(current.inReplyToStatusId);
|
||||
if (!parent) {
|
||||
break;
|
||||
}
|
||||
if (!chainIds.has(parent.id)) {
|
||||
chainIds.add(parent.id);
|
||||
ancestorIds.push(parent.id);
|
||||
}
|
||||
current = parent;
|
||||
}
|
||||
|
||||
const addDescendants = (startIds: string[]) => {
|
||||
const queue = [...startIds];
|
||||
while (queue.length > 0) {
|
||||
const currentId = queue.shift();
|
||||
if (!currentId) {
|
||||
continue;
|
||||
}
|
||||
if (!chainIds.has(currentId)) {
|
||||
chainIds.add(currentId);
|
||||
}
|
||||
const replies = repliesByParent.get(currentId) ?? [];
|
||||
for (const reply of replies) {
|
||||
if (chainIds.has(reply.id)) {
|
||||
continue;
|
||||
}
|
||||
chainIds.add(reply.id);
|
||||
queue.push(reply.id);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
addDescendants([bookmarkedTweet.id]);
|
||||
|
||||
if (options.includeAncestorBranches) {
|
||||
for (const ancestorId of ancestorIds) {
|
||||
addDescendants([ancestorId]);
|
||||
}
|
||||
}
|
||||
|
||||
return sortByCreatedAt(tweets.filter((tweet) => chainIds.has(tweet.id)));
|
||||
}
|
||||
|
||||
export function addThreadMetadata(tweet: TweetData, allConversationTweets: TweetData[]): TweetWithMeta {
|
||||
const author = tweet.author.username;
|
||||
const hasSelfReplies = allConversationTweets.some(
|
||||
(candidate) => candidate.inReplyToStatusId === tweet.id && candidate.author.username === author,
|
||||
);
|
||||
|
||||
const isRoot = !tweet.inReplyToStatusId;
|
||||
let threadPosition: 'root' | 'middle' | 'end' | 'standalone';
|
||||
|
||||
if (isRoot && !hasSelfReplies) {
|
||||
threadPosition = 'standalone';
|
||||
} else if (isRoot && hasSelfReplies) {
|
||||
threadPosition = 'root';
|
||||
} else if (!isRoot && hasSelfReplies) {
|
||||
threadPosition = 'middle';
|
||||
} else {
|
||||
threadPosition = 'end';
|
||||
}
|
||||
|
||||
return {
|
||||
...tweet,
|
||||
isThread: hasSelfReplies || !isRoot,
|
||||
threadPosition,
|
||||
hasSelfReplies,
|
||||
threadRootId: tweet.conversationId ?? null,
|
||||
};
|
||||
}
|
||||
@@ -15,12 +15,14 @@ export type Mixin<TBase extends AbstractConstructor<TwitterClientBase>, TAdded>
|
||||
|
||||
export abstract class TwitterClientBase {
|
||||
protected relayBaseUrl: string;
|
||||
protected profileName?: string;
|
||||
protected timeoutMs?: number;
|
||||
protected quoteDepth: number;
|
||||
protected clientUserId?: string;
|
||||
|
||||
constructor(options: TwitterClientOptions) {
|
||||
this.relayBaseUrl = this.normalizeRelayBaseUrl(options.relayBaseUrl ?? process.env.TWITTER_RELAY_BASE_URL);
|
||||
this.profileName = this.normalizeProfileName(options.profileName);
|
||||
this.timeoutMs = options.timeoutMs;
|
||||
this.quoteDepth = normalizeQuoteDepth(options.quoteDepth);
|
||||
}
|
||||
@@ -47,6 +49,18 @@ export abstract class TwitterClientBase {
|
||||
}
|
||||
}
|
||||
|
||||
protected async withRefreshedQueryIdsOn404<T extends { success: boolean; had404?: boolean }>(
|
||||
attempt: () => Promise<T>,
|
||||
): Promise<{ result: T; refreshed: boolean }> {
|
||||
const firstAttempt = await attempt();
|
||||
if (firstAttempt.success || !firstAttempt.had404) {
|
||||
return { result: firstAttempt, refreshed: false };
|
||||
}
|
||||
await this.refreshQueryIds();
|
||||
const secondAttempt = await attempt();
|
||||
return { result: secondAttempt, refreshed: true };
|
||||
}
|
||||
|
||||
protected async getTweetDetailQueryIds(): Promise<string[]> {
|
||||
const primary = await this.getQueryId('TweetDetail');
|
||||
return Array.from(new Set([primary, '97JF30KziU00483E_8elBA', 'aFvUsJm2c-oDkJV75blV6g']));
|
||||
@@ -73,7 +87,7 @@ export abstract class TwitterClientBase {
|
||||
}
|
||||
|
||||
protected getHeaders(): Record<string, string> {
|
||||
return {};
|
||||
return this.profileName ? { 'x-profile-name': this.profileName } : {};
|
||||
}
|
||||
|
||||
private normalizeRelayBaseUrl(value: string | undefined): string {
|
||||
@@ -84,6 +98,11 @@ export abstract class TwitterClientBase {
|
||||
return trimmed.replace(TRAILING_SLASHES, '');
|
||||
}
|
||||
|
||||
private normalizeProfileName(value: string | undefined): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed || undefined;
|
||||
}
|
||||
|
||||
private toRelayUrl(url: string): string {
|
||||
const parsed = new URL(url);
|
||||
if (!['x.com', 'twitter.com', 'api.twitter.com', 'upload.twitter.com'].includes(parsed.hostname)) {
|
||||
@@ -93,11 +112,11 @@ export abstract class TwitterClientBase {
|
||||
}
|
||||
|
||||
protected getJsonHeaders(): Record<string, string> {
|
||||
return { 'content-type': 'application/json' };
|
||||
return { 'content-type': 'application/json', ...this.getHeaders() };
|
||||
}
|
||||
|
||||
protected getUploadHeaders(): Record<string, string> {
|
||||
return {};
|
||||
return this.getHeaders();
|
||||
}
|
||||
|
||||
protected async ensureClientUserId(): Promise<void> {
|
||||
|
||||
@@ -12,7 +12,12 @@ export const TWITTER_STATUS_UPDATE_URL = 'https://x.com/i/api/1.1/statuses/updat
|
||||
export const FALLBACK_QUERY_IDS = {
|
||||
CreateTweet: 'TAJw1rBsjAtdNgTdlo2oeg',
|
||||
CreateRetweet: 'ojPdsZsimiJrUGLR1sjUtA',
|
||||
DeleteRetweet: 'iQtK4dl5hBmXewYZuEOKVw',
|
||||
CreateFriendship: '8h9JVdV8dlSyqyRDJEPCsA',
|
||||
DestroyFriendship: 'ppXWuagMNXgvzx6WoXBW0Q',
|
||||
FavoriteTweet: 'lI07N6Otwv1PhnEgXILM7A',
|
||||
UnfavoriteTweet: 'ZYKSe-w7KEslx3JhSIk5LA',
|
||||
CreateBookmark: 'aoDbu3RHznuiSkQ9aNM67Q',
|
||||
DeleteBookmark: 'Wlmlj2-xzyS1GN3a6cj-mQ',
|
||||
TweetDetail: '97JF30KziU00483E_8elBA',
|
||||
SearchTimeline: 'M1jEez78PEfVfbQLvlWMvQ',
|
||||
@@ -33,6 +38,9 @@ export const FALLBACK_QUERY_IDS = {
|
||||
ExplorePage: 'kheAINB_4pzRDqkzG3K-ng',
|
||||
GenericTimelineById: 'uGSr7alSjR9v6QJAIaqSKQ',
|
||||
TrendHistory: 'Sj4T-jSB9pr0Mxtsc1UKZQ',
|
||||
AboutAccountQuery: 'zs_jFPFT78rBpXv9Z3U2YQ',
|
||||
UserByScreenName: 'IGgvgiOx4QZndDHuD3x9TQ',
|
||||
UserByRestId: 'VQfQ9wwYdk6j_u2O4vt64Q',
|
||||
} as const;
|
||||
|
||||
export type OperationName = keyof typeof FALLBACK_QUERY_IDS;
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||
import { type OperationName, TWITTER_API_BASE, TWITTER_GRAPHQL_POST_URL } from './twitter-client-constants.js';
|
||||
import type { BookmarkMutationResult } from './twitter-client-types.js';
|
||||
|
||||
export interface TwitterClientEngagementMethods {
|
||||
/** Like a tweet. */
|
||||
like(tweetId: string): Promise<BookmarkMutationResult>;
|
||||
/** Remove a like from a tweet. */
|
||||
unlike(tweetId: string): Promise<BookmarkMutationResult>;
|
||||
/** Retweet a tweet. */
|
||||
retweet(tweetId: string): Promise<BookmarkMutationResult>;
|
||||
/** Remove a retweet. */
|
||||
unretweet(tweetId: string): Promise<BookmarkMutationResult>;
|
||||
/** Bookmark a tweet. */
|
||||
bookmark(tweetId: string): Promise<BookmarkMutationResult>;
|
||||
}
|
||||
|
||||
export function withEngagement<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
Base: TBase,
|
||||
): Mixin<TBase, TwitterClientEngagementMethods> {
|
||||
abstract class TwitterClientEngagement extends Base {
|
||||
// biome-ignore lint/complexity/noUselessConstructor lint/suspicious/noExplicitAny: TS mixin constructor requirement.
|
||||
constructor(...args: any[]) {
|
||||
super(...args);
|
||||
}
|
||||
|
||||
private async performEngagementMutation(
|
||||
operationName: OperationName,
|
||||
tweetId: string,
|
||||
): Promise<BookmarkMutationResult> {
|
||||
await this.ensureClientUserId();
|
||||
const variables =
|
||||
operationName === 'DeleteRetweet' ? { tweet_id: tweetId, source_tweet_id: tweetId } : { tweet_id: tweetId };
|
||||
let queryId = await this.getQueryId(operationName);
|
||||
let urlWithOperation = `${TWITTER_API_BASE}/${queryId}/${operationName}`;
|
||||
|
||||
const buildBody = () => JSON.stringify({ variables, queryId });
|
||||
const buildHeaders = () => ({ ...this.getHeaders(), referer: `https://x.com/i/status/${tweetId}` });
|
||||
let body = buildBody();
|
||||
|
||||
const parseResponse = async (response: Response): Promise<BookmarkMutationResult> => {
|
||||
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 { errors?: Array<{ message: string }> };
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
return { success: false, error: data.errors.map((e) => e.message).join(', ') };
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
};
|
||||
|
||||
try {
|
||||
let response = await this.fetchWithTimeout(urlWithOperation, {
|
||||
method: 'POST',
|
||||
headers: buildHeaders(),
|
||||
body,
|
||||
});
|
||||
|
||||
if (response.status === 404) {
|
||||
await this.refreshQueryIds();
|
||||
queryId = await this.getQueryId(operationName);
|
||||
urlWithOperation = `${TWITTER_API_BASE}/${queryId}/${operationName}`;
|
||||
body = buildBody();
|
||||
|
||||
response = await this.fetchWithTimeout(urlWithOperation, {
|
||||
method: 'POST',
|
||||
headers: buildHeaders(),
|
||||
body,
|
||||
});
|
||||
|
||||
if (response.status === 404) {
|
||||
const retry = await this.fetchWithTimeout(TWITTER_GRAPHQL_POST_URL, {
|
||||
method: 'POST',
|
||||
headers: buildHeaders(),
|
||||
body,
|
||||
});
|
||||
|
||||
return parseResponse(retry);
|
||||
}
|
||||
}
|
||||
|
||||
return parseResponse(response);
|
||||
} catch (error) {
|
||||
return { success: false, error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
}
|
||||
|
||||
/** Like a tweet. */
|
||||
async like(tweetId: string): Promise<BookmarkMutationResult> {
|
||||
return this.performEngagementMutation('FavoriteTweet', tweetId);
|
||||
}
|
||||
|
||||
/** Remove a like from a tweet. */
|
||||
async unlike(tweetId: string): Promise<BookmarkMutationResult> {
|
||||
return this.performEngagementMutation('UnfavoriteTweet', tweetId);
|
||||
}
|
||||
|
||||
/** Retweet a tweet. */
|
||||
async retweet(tweetId: string): Promise<BookmarkMutationResult> {
|
||||
return this.performEngagementMutation('CreateRetweet', tweetId);
|
||||
}
|
||||
|
||||
/** Remove a retweet. */
|
||||
async unretweet(tweetId: string): Promise<BookmarkMutationResult> {
|
||||
return this.performEngagementMutation('DeleteRetweet', tweetId);
|
||||
}
|
||||
|
||||
/** Bookmark a tweet. */
|
||||
async bookmark(tweetId: string): Promise<BookmarkMutationResult> {
|
||||
return this.performEngagementMutation('CreateBookmark', tweetId);
|
||||
}
|
||||
}
|
||||
|
||||
return TwitterClientEngagement;
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
||||
import type { FollowMutationResult } from './twitter-client-types.js';
|
||||
|
||||
export interface TwitterClientFollowMethods {
|
||||
follow(userId: string): Promise<FollowMutationResult>;
|
||||
unfollow(userId: string): Promise<FollowMutationResult>;
|
||||
}
|
||||
|
||||
export function withFollow<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
Base: TBase,
|
||||
): Mixin<TBase, TwitterClientFollowMethods> {
|
||||
abstract class TwitterClientFollow extends Base {
|
||||
// biome-ignore lint/complexity/noUselessConstructor lint/suspicious/noExplicitAny: TS mixin constructor requirement.
|
||||
constructor(...args: any[]) {
|
||||
super(...args);
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow a user by their user ID
|
||||
*/
|
||||
async follow(userId: string): Promise<FollowMutationResult> {
|
||||
await this.ensureClientUserId();
|
||||
|
||||
// Try REST API first (more reliable for follow/unfollow)
|
||||
const restResult = await this.followViaRest(userId, 'create');
|
||||
if (restResult.success) {
|
||||
return restResult;
|
||||
}
|
||||
|
||||
// Fallback to GraphQL
|
||||
return this.followViaGraphQL(userId, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unfollow a user by their user ID
|
||||
*/
|
||||
async unfollow(userId: string): Promise<FollowMutationResult> {
|
||||
await this.ensureClientUserId();
|
||||
|
||||
// Try REST API first (more reliable for follow/unfollow)
|
||||
const restResult = await this.followViaRest(userId, 'destroy');
|
||||
if (restResult.success) {
|
||||
return restResult;
|
||||
}
|
||||
|
||||
// Fallback to GraphQL
|
||||
return this.followViaGraphQL(userId, false);
|
||||
}
|
||||
|
||||
private async followViaRest(userId: string, action: 'create' | 'destroy'): Promise<FollowMutationResult> {
|
||||
const urls = [
|
||||
`https://x.com/i/api/1.1/friendships/${action}.json`,
|
||||
`https://api.twitter.com/1.1/friendships/${action}.json`,
|
||||
];
|
||||
|
||||
const params = new URLSearchParams({
|
||||
user_id: userId,
|
||||
skip_status: 'true',
|
||||
});
|
||||
|
||||
let lastError: string | undefined;
|
||||
|
||||
for (const url of urls) {
|
||||
try {
|
||||
const response = await this.fetchWithTimeout(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...this.getHeaders(),
|
||||
'content-type': 'application/x-www-form-urlencoded',
|
||||
},
|
||||
body: params.toString(),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
|
||||
// Parse error response
|
||||
try {
|
||||
const errorData = JSON.parse(text) as { errors?: Array<{ code: number; message: string }> };
|
||||
if (errorData.errors && errorData.errors.length > 0) {
|
||||
const error = errorData.errors[0];
|
||||
// Code 160: Already following / already not following
|
||||
if (error.code === 160) {
|
||||
return { success: true };
|
||||
}
|
||||
// Code 162: Blocked from following
|
||||
if (error.code === 162) {
|
||||
return { success: false, error: 'You have been blocked from following this account' };
|
||||
}
|
||||
// Code 108: Cannot find specified user
|
||||
if (error.code === 108) {
|
||||
return { success: false, error: 'User not found' };
|
||||
}
|
||||
lastError = `${error.message} (code ${error.code})`;
|
||||
continue;
|
||||
}
|
||||
} catch {
|
||||
// Not JSON, continue with generic error
|
||||
}
|
||||
|
||||
lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
id_str?: string;
|
||||
screen_name?: string;
|
||||
following?: boolean;
|
||||
errors?: Array<{ message: string; code?: number }>;
|
||||
};
|
||||
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
lastError = data.errors.map((e) => e.message).join(', ');
|
||||
continue;
|
||||
}
|
||||
|
||||
// Success - user data returned
|
||||
if (data.id_str || data.screen_name) {
|
||||
return {
|
||||
success: true,
|
||||
userId: data.id_str,
|
||||
username: data.screen_name,
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true };
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
}
|
||||
|
||||
return { success: false, error: lastError ?? `Unknown error during ${action}` };
|
||||
}
|
||||
|
||||
private async followViaGraphQL(userId: string, follow: boolean): Promise<FollowMutationResult> {
|
||||
const operationName = follow ? 'CreateFriendship' : 'DestroyFriendship';
|
||||
const variables = {
|
||||
user_id: userId,
|
||||
};
|
||||
|
||||
const tryOnce = async () => {
|
||||
let lastError: string | undefined;
|
||||
let had404 = false;
|
||||
const queryIds = await this.getFollowQueryIds(follow);
|
||||
|
||||
for (const queryId of queryIds) {
|
||||
const url = `${TWITTER_API_BASE}/${queryId}/${operationName}`;
|
||||
|
||||
try {
|
||||
const response = await this.fetchWithTimeout(url, {
|
||||
method: 'POST',
|
||||
headers: this.getHeaders(),
|
||||
body: JSON.stringify({ variables, queryId }),
|
||||
});
|
||||
|
||||
if (response.status === 404) {
|
||||
had404 = true;
|
||||
lastError = 'HTTP 404';
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
data?: {
|
||||
user?: {
|
||||
result?: {
|
||||
rest_id?: string;
|
||||
legacy?: {
|
||||
screen_name?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
errors?: Array<{ message: string }>;
|
||||
};
|
||||
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
lastError = data.errors.map((e) => e.message).join(', ');
|
||||
continue;
|
||||
}
|
||||
|
||||
const result = data.data?.user?.result;
|
||||
return {
|
||||
success: true as const,
|
||||
userId: result?.rest_id,
|
||||
username: result?.legacy?.screen_name,
|
||||
had404,
|
||||
};
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: false as const,
|
||||
error: lastError ?? `Unknown error during ${operationName}`,
|
||||
had404,
|
||||
};
|
||||
};
|
||||
|
||||
const firstAttempt = await tryOnce();
|
||||
if (firstAttempt.success) {
|
||||
return { success: true, userId: firstAttempt.userId, username: firstAttempt.username };
|
||||
}
|
||||
|
||||
if (firstAttempt.had404) {
|
||||
await this.refreshQueryIds();
|
||||
const secondAttempt = await tryOnce();
|
||||
if (secondAttempt.success) {
|
||||
return { success: true, userId: secondAttempt.userId, username: secondAttempt.username };
|
||||
}
|
||||
return { success: false, error: secondAttempt.error };
|
||||
}
|
||||
|
||||
return { success: false, error: firstAttempt.error };
|
||||
}
|
||||
|
||||
private async getFollowQueryIds(follow: boolean): Promise<string[]> {
|
||||
const primary = await this.getQueryId(follow ? 'CreateFriendship' : 'DestroyFriendship');
|
||||
const fallbacks = follow
|
||||
? ['8h9JVdV8dlSyqyRDJEPCsA', 'OPwKc1HXnBT_bWXfAlo-9g']
|
||||
: ['ppXWuagMNXgvzx6WoXBW0Q', '8h9JVdV8dlSyqyRDJEPCsA'];
|
||||
return Array.from(new Set([primary, ...fallbacks]));
|
||||
}
|
||||
}
|
||||
|
||||
return TwitterClientFollow;
|
||||
}
|
||||
@@ -14,6 +14,12 @@ function isQueryIdMismatch(errors: Array<{ message?: string }>): boolean {
|
||||
export interface HomeTimelineFetchOptions {
|
||||
/** Include raw GraphQL response in `_raw` field */
|
||||
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 {
|
||||
@@ -64,7 +70,17 @@ export function withHome<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
const pageSize = 20;
|
||||
const seen = new Set<string>();
|
||||
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) => {
|
||||
let lastError: string | undefined;
|
||||
@@ -168,11 +184,16 @@ export function withHome<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
};
|
||||
|
||||
while (tweets.length < count) {
|
||||
if (pagesFetched > 0 && pageDelayMs > 0) {
|
||||
await this.sleep(pageDelayMs);
|
||||
}
|
||||
|
||||
const pageCount = Math.min(pageSize, count - tweets.length);
|
||||
const page = await fetchWithRefresh(pageCount, cursor);
|
||||
if (!page.success) {
|
||||
return { success: false, error: page.error };
|
||||
}
|
||||
pagesFetched += 1;
|
||||
|
||||
let added = 0;
|
||||
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;
|
||||
}
|
||||
cursor = page.cursor;
|
||||
if (pagesFetched >= effectiveMaxPages) {
|
||||
nextCursor = pageCursor;
|
||||
break;
|
||||
}
|
||||
cursor = pageCursor;
|
||||
nextCursor = pageCursor;
|
||||
}
|
||||
|
||||
return { success: true, tweets };
|
||||
return { success: true, tweets, nextCursor };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,10 +6,14 @@ import { extractCursorFromInstructions, parseTweetsFromInstructions } from './tw
|
||||
|
||||
const RAW_QUERY_MISSING_REGEX = /must be defined/i;
|
||||
|
||||
export type SearchProduct = 'Top' | 'Latest';
|
||||
|
||||
/** Options for search methods */
|
||||
export interface SearchFetchOptions {
|
||||
/** Include raw GraphQL response in `_raw` field */
|
||||
includeRaw?: boolean;
|
||||
/** Search result ranking (default: Latest) */
|
||||
product?: SearchProduct;
|
||||
}
|
||||
|
||||
/** Options for paged search methods */
|
||||
@@ -80,7 +84,7 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
|
||||
let cursor: string | undefined = options.cursor;
|
||||
let nextCursor: string | undefined;
|
||||
let pagesFetched = 0;
|
||||
const { includeRaw = false, maxPages } = options;
|
||||
const { includeRaw = false, maxPages, product = 'Latest' } = options;
|
||||
|
||||
const fetchPage = async (pageCount: number, pageCursor?: string) => {
|
||||
let lastError: string | undefined;
|
||||
@@ -92,7 +96,7 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
|
||||
rawQuery: query,
|
||||
count: pageCount,
|
||||
querySource: 'typed_query',
|
||||
product: 'Latest',
|
||||
product,
|
||||
...(pageCursor ? { cursor: pageCursor } : {}),
|
||||
};
|
||||
|
||||
|
||||
@@ -47,11 +47,15 @@ export type GraphqlTweetResult = {
|
||||
legacy?: {
|
||||
screen_name?: string;
|
||||
name?: string;
|
||||
profile_image_url_https?: string;
|
||||
};
|
||||
core?: {
|
||||
screen_name?: string;
|
||||
name?: string;
|
||||
};
|
||||
avatar?: {
|
||||
image_url?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
@@ -228,6 +232,17 @@ export type BookmarkMutationResult =
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type FollowMutationResult =
|
||||
| {
|
||||
success: true;
|
||||
userId?: string;
|
||||
username?: string;
|
||||
}
|
||||
| {
|
||||
success: false;
|
||||
error: string;
|
||||
};
|
||||
|
||||
export interface UploadMediaResult {
|
||||
success: boolean;
|
||||
mediaId?: string;
|
||||
@@ -252,6 +267,7 @@ export interface TweetData {
|
||||
author: {
|
||||
username: string;
|
||||
name: string;
|
||||
profileImageUrl?: string;
|
||||
};
|
||||
authorId?: string;
|
||||
createdAt?: string;
|
||||
@@ -273,6 +289,13 @@ export interface TweetData {
|
||||
_raw?: GraphqlTweetResult;
|
||||
}
|
||||
|
||||
export interface TweetWithMeta extends TweetData {
|
||||
isThread: boolean;
|
||||
threadPosition: 'root' | 'middle' | 'end' | 'standalone';
|
||||
hasSelfReplies: boolean;
|
||||
threadRootId: string | null;
|
||||
}
|
||||
|
||||
export interface GetTweetResult {
|
||||
success: boolean;
|
||||
tweet?: TweetData;
|
||||
@@ -316,6 +339,58 @@ export interface TwitterUser {
|
||||
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 {
|
||||
success: boolean;
|
||||
users?: TwitterUser[];
|
||||
@@ -324,8 +399,23 @@ export interface FollowingResult {
|
||||
nextCursor?: string;
|
||||
}
|
||||
|
||||
export interface AboutAccountProfile {
|
||||
accountBasedIn?: string;
|
||||
source?: string;
|
||||
createdCountryAccurate?: boolean;
|
||||
locationAccurate?: boolean;
|
||||
learnMoreUrl?: string;
|
||||
}
|
||||
|
||||
export interface AboutAccountResult {
|
||||
success: boolean;
|
||||
aboutProfile?: AboutAccountProfile;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface TwitterClientOptions {
|
||||
relayBaseUrl?: string;
|
||||
profileName?: string;
|
||||
timeoutMs?: number;
|
||||
// Max depth for quoted tweets (0 disables). Defaults to 1.
|
||||
quoteDepth?: number;
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import { normalizeHandle } from './normalize-handle.js';
|
||||
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||
import { TWITTER_API_BASE } from './twitter-client-constants.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 */
|
||||
export interface UserLookupResult {
|
||||
@@ -13,6 +21,117 @@ export interface UserLookupResult {
|
||||
|
||||
export interface TwitterClientUserLookupMethods {
|
||||
getUserIdByUsername(username: string): Promise<UserLookupResult>;
|
||||
getUserProfile(target: string): Promise<UserProfileResult>;
|
||||
getUserProfiles(targets: string[]): Promise<UserProfilesResult>;
|
||||
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>>(
|
||||
@@ -205,6 +324,259 @@ export function withUserLookup<TBase extends AbstractConstructor<TwitterClientBa
|
||||
|
||||
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[]> {
|
||||
const primary = await this.getQueryId('AboutAccountQuery');
|
||||
return Array.from(new Set([primary, 'zs_jFPFT78rBpXv9Z3U2YQ']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get account origin and location information for a user.
|
||||
* Returns data from Twitter's "About this account" feature.
|
||||
*/
|
||||
async getUserAboutAccount(username: string): Promise<AboutAccountResult> {
|
||||
const cleanUsername = normalizeHandle(username);
|
||||
if (!cleanUsername) {
|
||||
return { success: false, error: `Invalid username: ${username}` };
|
||||
}
|
||||
|
||||
const variables = {
|
||||
screenName: cleanUsername,
|
||||
};
|
||||
|
||||
const params = new URLSearchParams({
|
||||
variables: JSON.stringify(variables),
|
||||
});
|
||||
|
||||
const tryOnce = async () => {
|
||||
let lastError: string | undefined;
|
||||
let had404 = false;
|
||||
const queryIds = await this.getAboutAccountQueryIds();
|
||||
|
||||
for (const queryId of queryIds) {
|
||||
const url = `${TWITTER_API_BASE}/${queryId}/AboutAccountQuery?${params.toString()}`;
|
||||
|
||||
try {
|
||||
const response = await this.fetchWithTimeout(url, {
|
||||
method: 'GET',
|
||||
headers: this.getHeaders(),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
if (response.status === 404) {
|
||||
had404 = true;
|
||||
lastError = `HTTP ${response.status}`;
|
||||
continue;
|
||||
}
|
||||
lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = (await response.json()) as {
|
||||
data?: {
|
||||
user_result_by_screen_name?: {
|
||||
result?: {
|
||||
about_profile?: {
|
||||
account_based_in?: string;
|
||||
source?: string;
|
||||
created_country_accurate?: boolean;
|
||||
location_accurate?: boolean;
|
||||
learn_more_url?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
errors?: Array<{ message: string }>;
|
||||
};
|
||||
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
lastError = data.errors.map((e) => e.message).join(', ');
|
||||
continue;
|
||||
}
|
||||
|
||||
const aboutProfile = data.data?.user_result_by_screen_name?.result?.about_profile;
|
||||
if (!aboutProfile) {
|
||||
lastError = 'Missing about_profile in response';
|
||||
continue;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true as const,
|
||||
aboutProfile: {
|
||||
accountBasedIn: aboutProfile.account_based_in,
|
||||
source: aboutProfile.source,
|
||||
createdCountryAccurate: aboutProfile.created_country_accurate,
|
||||
locationAccurate: aboutProfile.location_accurate,
|
||||
learnMoreUrl: aboutProfile.learn_more_url,
|
||||
},
|
||||
had404,
|
||||
};
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
success: false as const,
|
||||
error: lastError ?? 'Unknown error fetching account details',
|
||||
had404,
|
||||
};
|
||||
};
|
||||
|
||||
const { result } = await this.withRefreshedQueryIdsOn404(tryOnce);
|
||||
if (result.success) {
|
||||
return { success: true, aboutProfile: result.aboutProfile };
|
||||
}
|
||||
return { success: false, error: result.error };
|
||||
}
|
||||
}
|
||||
|
||||
return TwitterClientUserLookup;
|
||||
|
||||
@@ -65,7 +65,7 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
.filter((u) => u !== null);
|
||||
}
|
||||
|
||||
private async getFollowersViaRest(userId: string, count: number): Promise<FollowingResult> {
|
||||
private async getFollowersViaRest(userId: string, count: number, cursor?: string): Promise<FollowingResult> {
|
||||
const params = new URLSearchParams({
|
||||
user_id: userId,
|
||||
count: String(count),
|
||||
@@ -73,6 +73,10 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
include_user_entities: 'false',
|
||||
});
|
||||
|
||||
if (cursor) {
|
||||
params.set('cursor', cursor);
|
||||
}
|
||||
|
||||
const urls = [
|
||||
`https://x.com/i/api/1.1/followers/list.json?${params.toString()}`,
|
||||
`https://api.twitter.com/1.1/followers/list.json?${params.toString()}`,
|
||||
@@ -95,11 +99,13 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
|
||||
const data = (await response.json()) as {
|
||||
users?: RestUser[];
|
||||
next_cursor_str?: string;
|
||||
};
|
||||
|
||||
const users = this.parseUsersFromRestResponse(data.users);
|
||||
const nextCursor = data.next_cursor_str && data.next_cursor_str !== '0' ? data.next_cursor_str : undefined;
|
||||
|
||||
return { success: true, users };
|
||||
return { success: true, users, nextCursor };
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -108,7 +114,7 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
return { success: false, error: lastError ?? 'Unknown error fetching followers' };
|
||||
}
|
||||
|
||||
private async getFollowingViaRest(userId: string, count: number): Promise<FollowingResult> {
|
||||
private async getFollowingViaRest(userId: string, count: number, cursor?: string): Promise<FollowingResult> {
|
||||
const params = new URLSearchParams({
|
||||
user_id: userId,
|
||||
count: String(count),
|
||||
@@ -116,6 +122,10 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
include_user_entities: 'false',
|
||||
});
|
||||
|
||||
if (cursor) {
|
||||
params.set('cursor', cursor);
|
||||
}
|
||||
|
||||
const urls = [
|
||||
`https://x.com/i/api/1.1/friends/list.json?${params.toString()}`,
|
||||
`https://api.twitter.com/1.1/friends/list.json?${params.toString()}`,
|
||||
@@ -138,11 +148,13 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
|
||||
const data = (await response.json()) as {
|
||||
users?: RestUser[];
|
||||
next_cursor_str?: string;
|
||||
};
|
||||
|
||||
const users = this.parseUsersFromRestResponse(data.users);
|
||||
const nextCursor = data.next_cursor_str && data.next_cursor_str !== '0' ? data.next_cursor_str : undefined;
|
||||
|
||||
return { success: true, users };
|
||||
return { success: true, users, nextCursor };
|
||||
} catch (error) {
|
||||
lastError = error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
@@ -205,6 +217,10 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
? data.user_id
|
||||
: typeof data?.user_id_str === 'string'
|
||||
? data.user_id_str
|
||||
: typeof data?.id_str === 'string'
|
||||
? data.id_str
|
||||
: typeof data?.id === 'string'
|
||||
? data.id
|
||||
: typeof data?.user?.id_str === 'string'
|
||||
? data.user.id_str
|
||||
: typeof data?.user?.id === 'string'
|
||||
@@ -315,30 +331,21 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
return { success: false as const, error: lastError ?? 'Unknown error fetching following', had404 };
|
||||
};
|
||||
|
||||
const firstAttempt = await tryOnce();
|
||||
if (firstAttempt.success) {
|
||||
return { success: true, users: firstAttempt.users, nextCursor: firstAttempt.nextCursor };
|
||||
}
|
||||
|
||||
if (firstAttempt.had404) {
|
||||
await this.refreshQueryIds();
|
||||
const secondAttempt = await tryOnce();
|
||||
if (secondAttempt.success) {
|
||||
return { success: true, users: secondAttempt.users, nextCursor: secondAttempt.nextCursor };
|
||||
const { result, refreshed } = await this.withRefreshedQueryIdsOn404(tryOnce);
|
||||
if (result.success) {
|
||||
return { success: true, users: result.users, nextCursor: result.nextCursor };
|
||||
}
|
||||
|
||||
if (refreshed) {
|
||||
// GraphQL Following can also return 404 (queryId churn / endpoint flakiness).
|
||||
// Fallback to the internal v1.1 REST endpoint used by the web client through the relay.
|
||||
// Note: REST fallback does not support cursor pagination.
|
||||
const restAttempt = await this.getFollowingViaRest(userId, count);
|
||||
const restAttempt = await this.getFollowingViaRest(userId, count, cursor);
|
||||
if (restAttempt.success) {
|
||||
return restAttempt;
|
||||
}
|
||||
|
||||
return { success: false, error: secondAttempt.error };
|
||||
}
|
||||
|
||||
return { success: false, error: firstAttempt.error };
|
||||
return { success: false, error: result.error };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -421,30 +428,21 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||
return { success: false as const, error: lastError ?? 'Unknown error fetching followers', had404 };
|
||||
};
|
||||
|
||||
const firstAttempt = await tryOnce();
|
||||
if (firstAttempt.success) {
|
||||
return { success: true, users: firstAttempt.users, nextCursor: firstAttempt.nextCursor };
|
||||
}
|
||||
|
||||
if (firstAttempt.had404) {
|
||||
await this.refreshQueryIds();
|
||||
const secondAttempt = await tryOnce();
|
||||
if (secondAttempt.success) {
|
||||
return { success: true, users: secondAttempt.users, nextCursor: secondAttempt.nextCursor };
|
||||
const { result, refreshed } = await this.withRefreshedQueryIdsOn404(tryOnce);
|
||||
if (result.success) {
|
||||
return { success: true, users: result.users, nextCursor: result.nextCursor };
|
||||
}
|
||||
|
||||
if (refreshed) {
|
||||
// GraphQL Followers regularly returns 404 (queryId churn / endpoint flakiness).
|
||||
// Fallback to the internal v1.1 REST endpoint used by the web client through the relay.
|
||||
// Note: REST fallback does not support cursor pagination.
|
||||
const restAttempt = await this.getFollowersViaRest(userId, count);
|
||||
const restAttempt = await this.getFollowersViaRest(userId, count, cursor);
|
||||
if (restAttempt.success) {
|
||||
return restAttempt;
|
||||
}
|
||||
|
||||
return { success: false, error: secondAttempt.error };
|
||||
}
|
||||
|
||||
return { success: false, error: firstAttempt.error };
|
||||
return { success: false, error: result.error };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -566,6 +566,7 @@ export function mapTweetResult(
|
||||
author: {
|
||||
username,
|
||||
name: name || username,
|
||||
profileImageUrl: userLegacy?.profile_image_url_https ?? userResult?.avatar?.image_url,
|
||||
},
|
||||
authorId: userId,
|
||||
quotedTweet,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { AbstractConstructor } from './twitter-client-base.js';
|
||||
import { TwitterClientBase } from './twitter-client-base.js';
|
||||
import { type TwitterClientBookmarkMethods, withBookmarks } from './twitter-client-bookmarks.js';
|
||||
import { type TwitterClientEngagementMethods, withEngagement } from './twitter-client-engagement.js';
|
||||
import { type TwitterClientFollowMethods, withFollow } from './twitter-client-follow.js';
|
||||
import { type TwitterClientHomeMethods, withHome } from './twitter-client-home.js';
|
||||
import { type TwitterClientListMethods, withLists } from './twitter-client-lists.js';
|
||||
import { type TwitterClientMediaMethods, withMedia } from './twitter-client-media.js';
|
||||
@@ -15,6 +17,8 @@ import { type TwitterClientUserMethods, withUsers } from './twitter-client-users
|
||||
|
||||
type TwitterClientInstance = TwitterClientBase &
|
||||
TwitterClientBookmarkMethods &
|
||||
TwitterClientEngagementMethods &
|
||||
TwitterClientFollowMethods &
|
||||
TwitterClientHomeMethods &
|
||||
TwitterClientListMethods &
|
||||
TwitterClientMediaMethods &
|
||||
@@ -28,13 +32,18 @@ type TwitterClientInstance = TwitterClientBase &
|
||||
TwitterClientUserTweetsMethods;
|
||||
|
||||
// News mixin wraps search because it depends on the search() method
|
||||
// Engagement mixin adds like/unlike/retweet/unretweet/bookmark methods
|
||||
const MixedTwitterClient = withNews(
|
||||
withUserTweets(
|
||||
withUserLookup(
|
||||
withUsers(
|
||||
withLists(
|
||||
withHome(
|
||||
withTimelines(withSearch(withTweetDetails(withPosting(withBookmarks(withMedia(TwitterClientBase)))))),
|
||||
withTimelines(
|
||||
withSearch(
|
||||
withTweetDetails(withPosting(withEngagement(withFollow(withBookmarks(withMedia(TwitterClientBase)))))),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -49,6 +58,7 @@ export type {
|
||||
BookmarkMutationResult,
|
||||
CurrentUserResult,
|
||||
FollowingResult,
|
||||
FollowMutationResult,
|
||||
GetTweetResult,
|
||||
ListsResult,
|
||||
SearchResult,
|
||||
@@ -57,5 +67,8 @@ export type {
|
||||
TwitterClientOptions,
|
||||
TwitterList,
|
||||
TwitterUser,
|
||||
TwitterUserProfile,
|
||||
UploadMediaResult,
|
||||
UserProfileResult,
|
||||
UserProfilesResult,
|
||||
} from './twitter-client-types.js';
|
||||
|
||||
@@ -14,6 +14,8 @@ describe('cli-args', () => {
|
||||
'bookmarks',
|
||||
'following',
|
||||
'followers',
|
||||
'user',
|
||||
'profiles',
|
||||
'likes',
|
||||
'help',
|
||||
'whoami',
|
||||
@@ -58,6 +60,11 @@ describe('cli-args', () => {
|
||||
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', () => {
|
||||
const result = resolveCliInvocation(['https://example.com'], known);
|
||||
expect(result.argv).toBeNull();
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { createCliContext } from '../src/cli/shared.js';
|
||||
|
||||
describe('createCliContext', () => {
|
||||
it('resolves profileName from CLI options before env', () => {
|
||||
const ctx = createCliContext([], { BIRD_PROFILE_NAME: 'env-profile' } as NodeJS.ProcessEnv);
|
||||
|
||||
expect(ctx.resolveProfileNameFromOptions({ profileName: 'cli-profile' })).toBe('cli-profile');
|
||||
});
|
||||
|
||||
it('resolves profileName from env when CLI option is absent', () => {
|
||||
const ctx = createCliContext([], { BIRD_PROFILE_NAME: 'env-profile' } as NodeJS.ProcessEnv);
|
||||
|
||||
expect(ctx.resolveProfileNameFromOptions({})).toBe('env-profile');
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ describe('bookmarks command', () => {
|
||||
const ctx = {
|
||||
resolveTimeoutFromOptions: () => undefined,
|
||||
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||
resolveProfileNameFromOptions: () => undefined,
|
||||
p: () => '',
|
||||
printTweets: () => undefined,
|
||||
} as unknown as CliContext;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Command } from 'commander';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { CliContext } from '../src/cli/shared.js';
|
||||
import { registerFollowCommands } from '../src/commands/follow.js';
|
||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
|
||||
const baseCtx = {
|
||||
resolveTimeoutFromOptions: () => undefined,
|
||||
resolveRelayBaseUrlFromOptions: () => 'http://relay.test',
|
||||
resolveProfileNameFromOptions: () => undefined,
|
||||
p: () => '',
|
||||
} as unknown as CliContext;
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('follow commands', () => {
|
||||
it('prefers username lookup for numeric handles', async () => {
|
||||
const program = new Command();
|
||||
registerFollowCommands(program, baseCtx);
|
||||
|
||||
const lookupSpy = vi.spyOn(TwitterClient.prototype, 'getUserIdByUsername').mockResolvedValue({
|
||||
success: true,
|
||||
userId: '999',
|
||||
username: '12345',
|
||||
});
|
||||
const followSpy = vi.spyOn(TwitterClient.prototype, 'follow').mockResolvedValue({ success: true });
|
||||
vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
|
||||
await program.parseAsync(['node', 'bird', 'follow', '12345']);
|
||||
|
||||
expect(lookupSpy).toHaveBeenCalledWith('12345');
|
||||
expect(followSpy).toHaveBeenCalledWith('999');
|
||||
});
|
||||
|
||||
it('falls back to numeric user IDs when lookup fails', async () => {
|
||||
const program = new Command();
|
||||
registerFollowCommands(program, baseCtx);
|
||||
|
||||
vi.spyOn(TwitterClient.prototype, 'getUserIdByUsername').mockResolvedValue({
|
||||
success: false,
|
||||
error: 'User not found',
|
||||
});
|
||||
const followSpy = vi.spyOn(TwitterClient.prototype, 'follow').mockResolvedValue({ success: true });
|
||||
vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
|
||||
await program.parseAsync(['node', 'bird', 'follow', '12345']);
|
||||
|
||||
expect(followSpy).toHaveBeenCalledWith('12345');
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -14,6 +14,7 @@ describe('news command', () => {
|
||||
resolveTimeoutFromOptions: () => 30000,
|
||||
resolveQuoteDepthFromOptions: () => undefined,
|
||||
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||
resolveProfileNameFromOptions: () => undefined,
|
||||
p: (type: string) => `[${type}] `,
|
||||
colors: {
|
||||
accent: (text: string) => text,
|
||||
|
||||
@@ -9,6 +9,7 @@ describe('replies command', () => {
|
||||
({
|
||||
resolveTimeoutFromOptions: () => undefined,
|
||||
resolveQuoteDepthFromOptions: () => 1,
|
||||
resolveProfileNameFromOptions: () => undefined,
|
||||
extractTweetId: (input: string) => input,
|
||||
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||
p: () => '',
|
||||
@@ -74,6 +75,38 @@ describe('replies command', () => {
|
||||
errorSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('passes profileName to TwitterClient', async () => {
|
||||
const program = new Command();
|
||||
registerReadCommands(program, {
|
||||
...createMockContext(),
|
||||
resolveProfileNameFromOptions: () => 'work',
|
||||
});
|
||||
|
||||
const getTweetSpy = vi.spyOn(TwitterClient.prototype, 'getTweet').mockImplementation(async function () {
|
||||
const headers = (this as unknown as { getHeaders: () => Record<string, string> }).getHeaders();
|
||||
expect(headers).toEqual({ 'x-profile-name': 'work' });
|
||||
return {
|
||||
success: true,
|
||||
tweet: {
|
||||
id: '123',
|
||||
text: 'hello',
|
||||
author: { username: 'tester', name: 'Tester' },
|
||||
createdAt: '2024-01-01T00:00:00Z',
|
||||
url: 'https://x.com/tester/status/123',
|
||||
},
|
||||
};
|
||||
});
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
|
||||
try {
|
||||
await program.parseAsync(['node', 'bird', 'read', '123', '--json']);
|
||||
expect(getTweetSpy).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
getTweetSpy.mockRestore();
|
||||
logSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('thread command', () => {
|
||||
@@ -81,6 +114,7 @@ describe('thread command', () => {
|
||||
({
|
||||
resolveTimeoutFromOptions: () => undefined,
|
||||
resolveQuoteDepthFromOptions: () => 1,
|
||||
resolveProfileNameFromOptions: () => undefined,
|
||||
extractTweetId: (input: string) => input,
|
||||
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||
p: () => '',
|
||||
|
||||
@@ -14,6 +14,7 @@ describe('search command', () => {
|
||||
resolveTimeoutFromOptions: () => undefined,
|
||||
resolveQuoteDepthFromOptions: () => undefined,
|
||||
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||
resolveProfileNameFromOptions: () => undefined,
|
||||
p: () => '',
|
||||
printTweetsResult: vi.fn(),
|
||||
};
|
||||
@@ -81,8 +82,8 @@ describe('search command', () => {
|
||||
const searchSpy = vi.spyOn(TwitterClient.prototype, 'search').mockResolvedValue({ success: true, tweets: [] });
|
||||
|
||||
try {
|
||||
await program.parseAsync(['node', 'bird', 'search', 'cats', '--all', '--json']);
|
||||
expect(getAllSpy).toHaveBeenCalledWith('cats', expect.objectContaining({ includeRaw: false }));
|
||||
await program.parseAsync(['node', 'bird', 'search', 'cats', '--all', '--json', '--product', 'Top']);
|
||||
expect(getAllSpy).toHaveBeenCalledWith('cats', expect.objectContaining({ includeRaw: false, product: 'Top' }));
|
||||
expect(searchSpy).not.toHaveBeenCalled();
|
||||
expect(mockContext.printTweetsResult).toHaveBeenCalledWith(expect.objectContaining({ tweets: [] }), {
|
||||
json: true,
|
||||
@@ -95,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 () => {
|
||||
registerSearchCommands(program, mockContext as CliContext);
|
||||
const getAllSpy = vi
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Command } from 'commander';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { CliContext } from '../src/cli/shared.js';
|
||||
import { registerUserCommands } from '../src/commands/users.js';
|
||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
|
||||
const baseCtx = {
|
||||
resolveTimeoutFromOptions: () => undefined,
|
||||
resolveRelayBaseUrlFromOptions: () => 'http://relay.test',
|
||||
resolveProfileNameFromOptions: () => undefined,
|
||||
p: () => '',
|
||||
l: () => '',
|
||||
printTweets: () => undefined,
|
||||
} as unknown as CliContext;
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('users about command', () => {
|
||||
it('prints account info JSON for about command', async () => {
|
||||
const program = new Command();
|
||||
registerUserCommands(program, baseCtx);
|
||||
vi.spyOn(TwitterClient.prototype, 'getUserAboutAccount').mockResolvedValue({
|
||||
success: true,
|
||||
aboutProfile: {
|
||||
accountBasedIn: 'Spain',
|
||||
source: 'Spain App Store',
|
||||
createdCountryAccurate: true,
|
||||
locationAccurate: false,
|
||||
learnMoreUrl: 'https://help.twitter.com/profile',
|
||||
},
|
||||
});
|
||||
|
||||
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||
await program.parseAsync(['node', 'bird', 'about', 'pablotovar_', '--json']);
|
||||
|
||||
const payload = JSON.parse(String(logSpy.mock.calls[0]?.[0]));
|
||||
expect(payload).toEqual({
|
||||
accountBasedIn: 'Spain',
|
||||
source: 'Spain App Store',
|
||||
createdCountryAccurate: true,
|
||||
locationAccurate: false,
|
||||
learnMoreUrl: 'https://help.twitter.com/profile',
|
||||
});
|
||||
});
|
||||
|
||||
it('exits on about command failure', async () => {
|
||||
const program = new Command();
|
||||
registerUserCommands(program, baseCtx);
|
||||
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||
throw new Error(`exit ${code}`);
|
||||
}) as never);
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||
vi.spyOn(TwitterClient.prototype, 'getUserAboutAccount').mockResolvedValue({
|
||||
success: false,
|
||||
error: 'Missing about_profile in response',
|
||||
});
|
||||
|
||||
try {
|
||||
await expect(program.parseAsync(['node', 'bird', 'about', 'pablotovar__'])).rejects.toThrow('exit 1');
|
||||
expect(errorSpy).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Failed to fetch account information: Missing about_profile in response'),
|
||||
);
|
||||
} finally {
|
||||
exitSpy.mockRestore();
|
||||
errorSpy.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
const baseCtx = {
|
||||
resolveTimeoutFromOptions: () => undefined,
|
||||
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||
resolveProfileNameFromOptions: () => undefined,
|
||||
p: () => '',
|
||||
printTweets: () => undefined,
|
||||
} as unknown as CliContext;
|
||||
@@ -208,4 +209,44 @@ describe('users commands', () => {
|
||||
expect(payload.nextCursor).toBeNull();
|
||||
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' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,6 +17,8 @@ describe('root help output', () => {
|
||||
|
||||
expect(help).toContain('following');
|
||||
expect(help).toContain('followers');
|
||||
expect(help).toContain('user');
|
||||
expect(help).toContain('profiles');
|
||||
expect(help).toContain('likes');
|
||||
|
||||
expect(help).toContain('bird <tweet-id-or-url>');
|
||||
@@ -46,6 +48,7 @@ describe('root help output', () => {
|
||||
cmd.outputHelp();
|
||||
|
||||
expect(help).toContain('--relay-base-url');
|
||||
expect(help).toContain('--profile-name');
|
||||
expect(help).not.toContain('--auth-token');
|
||||
expect(help).not.toContain('--ct0');
|
||||
expect(help).toContain('--timeout');
|
||||
|
||||
@@ -1,8 +1,15 @@
|
||||
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', () => {
|
||||
it('exposes primary library surface', () => {
|
||||
expect(typeof TwitterClient).toBe('function');
|
||||
});
|
||||
|
||||
it('exposes search product types', () => {
|
||||
const product: SearchProduct = 'Top';
|
||||
const options: SearchFetchOptions = { product };
|
||||
|
||||
expect(options.product).toBe('Top');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -247,6 +247,28 @@ d('live CLI (Twitter/X) all commands', () => {
|
||||
expect(Array.isArray(bookmarkTweets)).toBe(true);
|
||||
});
|
||||
|
||||
it('bookmarks full-chain-only with ancestor branches returns JSON array', async () => {
|
||||
const bookmarks = await runBird(
|
||||
[
|
||||
...baseArgs,
|
||||
'--cookie-timeout',
|
||||
cookieTimeoutArg,
|
||||
'bookmarks',
|
||||
'-n',
|
||||
'1',
|
||||
'--full-chain-only',
|
||||
'--include-ancestor-branches',
|
||||
'--json',
|
||||
],
|
||||
{
|
||||
timeoutMs: 45_000,
|
||||
},
|
||||
);
|
||||
expect(bookmarks.exitCode).toBe(0);
|
||||
const bookmarkTweets = parseJson<Array<{ id?: string }>>(bookmarks.stdout);
|
||||
expect(Array.isArray(bookmarkTweets)).toBe(true);
|
||||
});
|
||||
|
||||
it('likes returns JSON array', async () => {
|
||||
const likes = await runBird([...baseArgs, 'likes', '-n', '10', '--json'], {
|
||||
timeoutMs: 45_000,
|
||||
@@ -364,4 +386,62 @@ d('live CLI (Twitter/X) all commands', () => {
|
||||
const snapshot = parseJson<{ cached?: boolean; ids?: Record<string, string> }>(queryIds.stdout);
|
||||
expect(typeof snapshot.cached).toBe('boolean');
|
||||
});
|
||||
|
||||
it('engagement mutations work (opt-in)', async () => {
|
||||
const engagementTweetId = (process.env.BIRD_LIVE_ENGAGEMENT_TWEET_ID ?? '').trim();
|
||||
if (!engagementTweetId) {
|
||||
return;
|
||||
}
|
||||
if (!TWEET_ID_REGEX.test(engagementTweetId)) {
|
||||
throw new Error(`Invalid BIRD_LIVE_ENGAGEMENT_TWEET_ID (expected digits): "${engagementTweetId}"`);
|
||||
}
|
||||
|
||||
const cookieTimeoutMs = Number.parseInt(cookieTimeoutArg, 10);
|
||||
const { cookies, warnings } = await resolveCredentials({
|
||||
authToken,
|
||||
ct0,
|
||||
cookieTimeoutMs: Number.isFinite(cookieTimeoutMs) ? cookieTimeoutMs : undefined,
|
||||
});
|
||||
for (const warning of warnings) {
|
||||
console.error(`${warning}`);
|
||||
}
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
throw new Error('Missing live credentials for engagement test.');
|
||||
}
|
||||
|
||||
const originalNodeEnv = process.env.NODE_ENV;
|
||||
process.env.NODE_ENV = LIVE_NODE_ENV;
|
||||
try {
|
||||
const timeoutMs = Number.parseInt(timeoutArg, 10);
|
||||
const client = new TwitterClient({
|
||||
cookies,
|
||||
timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : undefined,
|
||||
});
|
||||
|
||||
// Cleanup (best-effort) to make the mutation sequence deterministic.
|
||||
await client.unbookmark(engagementTweetId);
|
||||
await client.unlike(engagementTweetId);
|
||||
await client.unretweet(engagementTweetId);
|
||||
|
||||
const like = await client.like(engagementTweetId);
|
||||
expect(like.success).toBe(true);
|
||||
const retweet = await client.retweet(engagementTweetId);
|
||||
expect(retweet.success).toBe(true);
|
||||
const bookmark = await client.bookmark(engagementTweetId);
|
||||
expect(bookmark.success).toBe(true);
|
||||
|
||||
const unbookmark = await client.unbookmark(engagementTweetId);
|
||||
expect(unbookmark.success).toBe(true);
|
||||
const unlike = await client.unlike(engagementTweetId);
|
||||
expect(unlike.success).toBe(true);
|
||||
const unretweet = await client.unretweet(engagementTweetId);
|
||||
expect(unretweet.success).toBe(true);
|
||||
} finally {
|
||||
if (originalNodeEnv === undefined) {
|
||||
delete process.env.NODE_ENV;
|
||||
} else {
|
||||
process.env.NODE_ENV = originalNodeEnv;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -149,6 +149,23 @@ d('live CLI (Twitter/X)', () => {
|
||||
expect(whoamiStdout).toContain('credentials:');
|
||||
});
|
||||
|
||||
it('follow/unfollow works (opt-in)', async () => {
|
||||
const followHandle = (process.env.BIRD_LIVE_FOLLOW_HANDLE ?? '').trim();
|
||||
if (!followHandle) {
|
||||
return;
|
||||
}
|
||||
|
||||
const follow = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'follow', followHandle], {
|
||||
timeoutMs: 45_000,
|
||||
});
|
||||
expect(follow.exitCode).toBe(0);
|
||||
|
||||
const unfollow = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'unfollow', followHandle], {
|
||||
timeoutMs: 45_000,
|
||||
});
|
||||
expect(unfollow.exitCode).toBe(0);
|
||||
});
|
||||
|
||||
it('read returns tweet JSON', async () => {
|
||||
const read = await runBird([...baseArgs, 'read', tweetId, '--json'], {
|
||||
timeoutMs: 45_000,
|
||||
@@ -311,4 +328,62 @@ d('live CLI (Twitter/X)', () => {
|
||||
// This verifies the article content is being extracted, not just a stub
|
||||
expect(tweet.text?.length).toBeGreaterThan(500);
|
||||
});
|
||||
|
||||
it('engagement mutations work (opt-in)', async () => {
|
||||
const engagementTweetId = (process.env.BIRD_LIVE_ENGAGEMENT_TWEET_ID ?? '').trim();
|
||||
if (!engagementTweetId) {
|
||||
return;
|
||||
}
|
||||
if (!TWEET_ID_REGEX.test(engagementTweetId)) {
|
||||
throw new Error(`Invalid BIRD_LIVE_ENGAGEMENT_TWEET_ID (expected digits): "${engagementTweetId}"`);
|
||||
}
|
||||
|
||||
const cookieTimeoutMs = Number.parseInt(cookieTimeoutArg, 10);
|
||||
const { cookies, warnings } = await resolveCredentials({
|
||||
authToken,
|
||||
ct0,
|
||||
cookieTimeoutMs: Number.isFinite(cookieTimeoutMs) ? cookieTimeoutMs : undefined,
|
||||
});
|
||||
for (const warning of warnings) {
|
||||
console.error(`${warning}`);
|
||||
}
|
||||
if (!cookies.authToken || !cookies.ct0) {
|
||||
throw new Error('Missing live credentials for engagement test.');
|
||||
}
|
||||
|
||||
const originalNodeEnv = process.env.NODE_ENV;
|
||||
process.env.NODE_ENV = LIVE_NODE_ENV;
|
||||
try {
|
||||
const timeoutMs = Number.parseInt(timeoutArg, 10);
|
||||
const client = new TwitterClient({
|
||||
cookies,
|
||||
timeoutMs: Number.isFinite(timeoutMs) ? timeoutMs : undefined,
|
||||
});
|
||||
|
||||
// Cleanup (best-effort) to make the mutation sequence deterministic.
|
||||
await client.unbookmark(engagementTweetId);
|
||||
await client.unlike(engagementTweetId);
|
||||
await client.unretweet(engagementTweetId);
|
||||
|
||||
const like = await client.like(engagementTweetId);
|
||||
expect(like.success).toBe(true);
|
||||
const retweet = await client.retweet(engagementTweetId);
|
||||
expect(retweet.success).toBe(true);
|
||||
const bookmark = await client.bookmark(engagementTweetId);
|
||||
expect(bookmark.success).toBe(true);
|
||||
|
||||
const unbookmark = await client.unbookmark(engagementTweetId);
|
||||
expect(unbookmark.success).toBe(true);
|
||||
const unlike = await client.unlike(engagementTweetId);
|
||||
expect(unlike.success).toBe(true);
|
||||
const unretweet = await client.unretweet(engagementTweetId);
|
||||
expect(unretweet.success).toBe(true);
|
||||
} finally {
|
||||
if (originalNodeEnv === undefined) {
|
||||
delete process.env.NODE_ENV;
|
||||
} else {
|
||||
process.env.NODE_ENV = originalNodeEnv;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -120,10 +120,10 @@ describe('runtime-features', () => {
|
||||
it('includes required lists API feature flags', () => {
|
||||
const features = buildListsFeatures();
|
||||
expect(features.responsive_web_graphql_exclude_directive_enabled).toBe(true);
|
||||
expect(features.blue_business_profile_image_shape_enabled).toBe(false);
|
||||
expect(features.blue_business_profile_image_shape_enabled).toBe(true);
|
||||
expect(features.responsive_web_text_conversations_enabled).toBe(false);
|
||||
expect(features.tweetypie_unmention_optimization_enabled).toBe(true);
|
||||
expect(features.vibe_api_enabled).toBe(false);
|
||||
expect(features.interactive_text_enabled).toBe(false);
|
||||
expect(features.vibe_api_enabled).toBe(true);
|
||||
expect(features.interactive_text_enabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { filterFullChain } from '../src/lib/thread-filters.js';
|
||||
import type { TweetData } from '../src/lib/twitter-client-types.js';
|
||||
|
||||
const makeTweet = (id: string, createdAt: string, inReplyToStatusId?: string, conversationId = '1'): TweetData => ({
|
||||
id,
|
||||
text: id,
|
||||
author: { username: 'alice', name: 'Alice' },
|
||||
createdAt,
|
||||
inReplyToStatusId,
|
||||
conversationId,
|
||||
});
|
||||
|
||||
describe('filterFullChain', () => {
|
||||
it('returns ancestors + descendants from the bookmark only', () => {
|
||||
const root = makeTweet('1', '2020-01-01T00:00:00Z');
|
||||
const replyA = makeTweet('2', '2020-01-02T00:00:00Z', '1');
|
||||
const bookmark = makeTweet('3', '2020-01-03T00:00:00Z', '2');
|
||||
const childA = makeTweet('4', '2020-01-04T00:00:00Z', '3');
|
||||
const childB = makeTweet('7', '2020-01-05T00:00:00Z', '4');
|
||||
const siblingOfAncestor = makeTweet('5', '2020-01-06T00:00:00Z', '2');
|
||||
const siblingOfRoot = makeTweet('6', '2020-01-07T00:00:00Z', '1');
|
||||
|
||||
const tweets = [siblingOfAncestor, childB, root, siblingOfRoot, bookmark, childA, replyA];
|
||||
|
||||
const result = filterFullChain(tweets, bookmark);
|
||||
expect(result.map((tweet) => tweet.id)).toEqual(['1', '2', '3', '4', '7']);
|
||||
});
|
||||
|
||||
it('includes ancestor branches when requested', () => {
|
||||
const root = makeTweet('1', '2020-01-01T00:00:00Z');
|
||||
const replyA = makeTweet('2', '2020-01-02T00:00:00Z', '1');
|
||||
const bookmark = makeTweet('3', '2020-01-03T00:00:00Z', '2');
|
||||
const childA = makeTweet('4', '2020-01-04T00:00:00Z', '3');
|
||||
const childB = makeTweet('7', '2020-01-05T00:00:00Z', '4');
|
||||
const siblingOfAncestor = makeTweet('5', '2020-01-06T00:00:00Z', '2');
|
||||
const siblingOfRoot = makeTweet('6', '2020-01-07T00:00:00Z', '1');
|
||||
|
||||
const tweets = [siblingOfRoot, childA, replyA, childB, bookmark, root, siblingOfAncestor];
|
||||
|
||||
const result = filterFullChain(tweets, bookmark, { includeAncestorBranches: true });
|
||||
expect(result.map((tweet) => tweet.id)).toEqual(['1', '2', '3', '4', '7', '5', '6']);
|
||||
});
|
||||
});
|
||||
@@ -124,6 +124,41 @@ describe('TwitterClient core coverage', () => {
|
||||
expect(headers).toEqual({});
|
||||
});
|
||||
|
||||
it('adds x-profile-name header when profileName is set', () => {
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, profileName: 'work' });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
|
||||
expect(clientPrivate.getHeaders()).toEqual({ 'x-profile-name': 'work' });
|
||||
});
|
||||
|
||||
it('ignores blank profileName values', () => {
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, profileName: ' ' });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
|
||||
expect(clientPrivate.getHeaders()).toEqual({});
|
||||
});
|
||||
|
||||
it('adds x-profile-name to JSON headers when profileName is set', () => {
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, profileName: 'work' });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate & {
|
||||
getJsonHeaders: () => Record<string, string>;
|
||||
};
|
||||
|
||||
expect(clientPrivate.getJsonHeaders()).toEqual({
|
||||
'content-type': 'application/json',
|
||||
'x-profile-name': 'work',
|
||||
});
|
||||
});
|
||||
|
||||
it('adds x-profile-name to upload headers when profileName is set', () => {
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, profileName: 'work' });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate & {
|
||||
getUploadHeaders: () => Record<string, string>;
|
||||
};
|
||||
|
||||
expect(clientPrivate.getUploadHeaders()).toEqual({ 'x-profile-name': 'work' });
|
||||
});
|
||||
|
||||
describe('fetchUserArticlePlainText failures', () => {
|
||||
it('returns empty object when response is not ok', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(makeResponse({ ok: false, status: 500 }));
|
||||
|
||||
@@ -107,6 +107,24 @@ describe('TwitterClient getCurrentUser', () => {
|
||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('reads top-level id_str from verify_credentials responses', async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
id_str: '12345',
|
||||
screen_name: 'tester',
|
||||
name: 'Test User',
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getCurrentUser();
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.user).toEqual({ id: '12345', username: 'tester', name: 'Test User' });
|
||||
});
|
||||
|
||||
it('continues on fetch errors and still succeeds via later API endpoint', async () => {
|
||||
mockFetch
|
||||
.mockRejectedValueOnce(new Error('boom'))
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('TwitterClient engagement', () => {
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch = vi.fn();
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
});
|
||||
|
||||
describe('like', () => {
|
||||
it('successfully likes a tweet', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ data: { favorite_tweet: 'Done' } }),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.like('1234567890');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(options.method).toBe('POST');
|
||||
expect(String(url)).toContain('/FavoriteTweet');
|
||||
const body = JSON.parse(options.body);
|
||||
expect(body.variables.tweet_id).toBe('1234567890');
|
||||
});
|
||||
|
||||
it('returns error on HTTP failure', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 403,
|
||||
text: async () => 'Forbidden',
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.like('1234567890');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 403');
|
||||
});
|
||||
|
||||
it('returns error on GraphQL errors', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
errors: [{ message: 'You have already favorited this Tweet.' }],
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.like('1234567890');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('already favorited');
|
||||
});
|
||||
|
||||
it('retries on 404 with refreshed query IDs', async () => {
|
||||
mockFetch.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'Not found' }).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ data: { favorite_tweet: 'Done' } }),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.like('1234567890');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('unlike', () => {
|
||||
it('successfully unlikes a tweet', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ data: { unfavorite_tweet: 'Done' } }),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.unlike('1234567890');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(options.method).toBe('POST');
|
||||
expect(String(url)).toContain('/UnfavoriteTweet');
|
||||
});
|
||||
});
|
||||
|
||||
describe('retweet', () => {
|
||||
it('successfully retweets a tweet', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ data: { create_retweet: { retweet_results: { result: {} } } } }),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.retweet('1234567890');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(options.method).toBe('POST');
|
||||
expect(String(url)).toContain('/CreateRetweet');
|
||||
});
|
||||
});
|
||||
|
||||
describe('unretweet', () => {
|
||||
it('successfully unretweets a tweet', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ data: { unretweet: { source_tweet_results: {} } } }),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.unretweet('1234567890');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(options.method).toBe('POST');
|
||||
expect(String(url)).toContain('/DeleteRetweet');
|
||||
const body = JSON.parse(options.body);
|
||||
expect(body.variables.tweet_id).toBe('1234567890');
|
||||
expect(body.variables.source_tweet_id).toBe('1234567890');
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookmark', () => {
|
||||
it('successfully bookmarks a tweet', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({ data: { tweet_bookmark_put: 'Done' } }),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.bookmark('1234567890');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(options.method).toBe('POST');
|
||||
expect(String(url)).toContain('/CreateBookmark');
|
||||
});
|
||||
});
|
||||
|
||||
describe('error handling', () => {
|
||||
it('catches network errors', async () => {
|
||||
mockFetch.mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.like('1234567890');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Network error');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -145,6 +145,121 @@ describe('TwitterClient home timeline', () => {
|
||||
});
|
||||
|
||||
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 () => {
|
||||
// First page
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
|
||||
@@ -118,11 +118,11 @@ describe('TwitterClient lists owned', () => {
|
||||
const [url] = mockFetch.mock.calls[0];
|
||||
const parsedFeatures = JSON.parse(new URL(url as string).searchParams.get('features') as string);
|
||||
expect(parsedFeatures.responsive_web_graphql_exclude_directive_enabled).toBe(true);
|
||||
expect(parsedFeatures.blue_business_profile_image_shape_enabled).toBe(false);
|
||||
expect(parsedFeatures.blue_business_profile_image_shape_enabled).toBe(true);
|
||||
expect(parsedFeatures.responsive_web_text_conversations_enabled).toBe(false);
|
||||
expect(parsedFeatures.tweetypie_unmention_optimization_enabled).toBe(true);
|
||||
expect(parsedFeatures.vibe_api_enabled).toBe(false);
|
||||
expect(parsedFeatures.interactive_text_enabled).toBe(false);
|
||||
expect(parsedFeatures.vibe_api_enabled).toBe(true);
|
||||
expect(parsedFeatures.interactive_text_enabled).toBe(true);
|
||||
});
|
||||
|
||||
it('handles private lists correctly', async () => {
|
||||
|
||||
@@ -83,8 +83,12 @@ describe('TwitterClient search', () => {
|
||||
expect(body.queryId).toBeDefined();
|
||||
const urlVars = new URL(url as string).searchParams.get('variables');
|
||||
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.product).toBe('Latest');
|
||||
});
|
||||
|
||||
it('refreshes query IDs when all search endpoints 404', async () => {
|
||||
@@ -186,7 +190,7 @@ describe('TwitterClient search', () => {
|
||||
});
|
||||
|
||||
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.tweets?.map((tweet) => tweet.id)).toEqual(['1', '2', '3']);
|
||||
@@ -194,13 +198,15 @@ describe('TwitterClient search', () => {
|
||||
|
||||
const firstVars = JSON.parse(
|
||||
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(
|
||||
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(secondVars.cursor).toBe('cursor-1');
|
||||
expect(firstVars.product).toBe('Top');
|
||||
expect(secondVars.product).toBe('Top');
|
||||
});
|
||||
|
||||
it('stops paginating when the cursor repeats', async () => {
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('TwitterClient getUserAboutAccount', () => {
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch = vi.fn();
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
});
|
||||
|
||||
it('returns account information for a valid user', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: {
|
||||
user_result_by_screen_name: {
|
||||
result: {
|
||||
about_profile: {
|
||||
account_based_in: 'Germany',
|
||||
source: 'Twitter',
|
||||
created_country_accurate: true,
|
||||
location_accurate: true,
|
||||
learn_more_url: 'https://help.twitter.com/about-account',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('testuser');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.aboutProfile).toBeDefined();
|
||||
expect(result.aboutProfile?.accountBasedIn).toBe('Germany');
|
||||
expect(result.aboutProfile?.source).toBe('Twitter');
|
||||
expect(result.aboutProfile?.createdCountryAccurate).toBe(true);
|
||||
expect(result.aboutProfile?.locationAccurate).toBe(true);
|
||||
expect(result.aboutProfile?.learnMoreUrl).toBe('https://help.twitter.com/about-account');
|
||||
});
|
||||
|
||||
it('handles username with @ prefix', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: {
|
||||
user_result_by_screen_name: {
|
||||
result: {
|
||||
about_profile: {
|
||||
account_based_in: 'United States',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('@testuser');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.aboutProfile?.accountBasedIn).toBe('United States');
|
||||
});
|
||||
|
||||
it('returns error for invalid username', async () => {
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Invalid username');
|
||||
});
|
||||
|
||||
it('handles missing about_profile in response', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: {
|
||||
user_result_by_screen_name: {
|
||||
result: {},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('testuser');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Missing about_profile');
|
||||
});
|
||||
|
||||
it('handles GraphQL errors in response', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
errors: [{ message: 'User not found' }],
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('testuser');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('User not found');
|
||||
});
|
||||
|
||||
it('handles HTTP 404 error', async () => {
|
||||
mockFetch.mockResolvedValue({
|
||||
ok: false,
|
||||
status: 404,
|
||||
text: async () => 'Not Found',
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('testuser');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 404');
|
||||
});
|
||||
|
||||
it('handles non-404 HTTP errors', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 500,
|
||||
text: async () => 'Internal Server Error',
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('testuser');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('handles network errors', async () => {
|
||||
mockFetch.mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('testuser');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Network error');
|
||||
});
|
||||
|
||||
it('handles partial about_profile data', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: {
|
||||
user_result_by_screen_name: {
|
||||
result: {
|
||||
about_profile: {
|
||||
account_based_in: 'Japan',
|
||||
// Other fields missing
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||
const result = await client.getUserAboutAccount('testuser');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.aboutProfile?.accountBasedIn).toBe('Japan');
|
||||
expect(result.aboutProfile?.source).toBeUndefined();
|
||||
expect(result.aboutProfile?.createdCountryAccurate).toBeUndefined();
|
||||
expect(result.aboutProfile?.locationAccurate).toBeUndefined();
|
||||
expect(result.aboutProfile?.learnMoreUrl).toBeUndefined();
|
||||
});
|
||||
|
||||
it('makes proper GraphQL request with correct parameters', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: {
|
||||
user_result_by_screen_name: {
|
||||
result: {
|
||||
about_profile: {
|
||||
account_based_in: 'Canada',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ relayBaseUrl: 'http://relay.test', profileName: 'test-profile' });
|
||||
await client.getUserAboutAccount('testuser');
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
const [url, options] = mockFetch.mock.calls[0] as [string, RequestInit];
|
||||
|
||||
expect(url).toContain('http://relay.test/i/api/graphql/');
|
||||
expect(url).toContain('/AboutAccountQuery?');
|
||||
expect(url).toContain('variables=');
|
||||
expect(url).toContain('testuser');
|
||||
expect(options.method).toBe('GET');
|
||||
expect(options.headers).toMatchObject({
|
||||
'x-profile-name': 'test-profile',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -163,4 +163,184 @@ describe('TwitterClient getUserIdByUsername', () => {
|
||||
expect(result.userId).toBe('99999');
|
||||
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' },
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,3 +5,4 @@
|
||||
- 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.
|
||||
- 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.
|
||||
|
||||
Reference in New Issue
Block a user