Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61f6efd816 | ||
|
|
69238834f2 | ||
|
|
0e5c62b250 | ||
|
|
96535c33f9 | ||
|
|
fd78705954 | ||
|
|
6503bb1b76 | ||
|
|
1f6e228272 | ||
|
|
b771e827aa | ||
|
|
afdcad4f25 | ||
|
|
35b8774b1c | ||
|
|
57c8e8e793 | ||
|
|
afa7063a72 | ||
|
|
bc744a3bf9 | ||
|
|
9cfeda13b2 | ||
|
|
35f8fa1a38 | ||
|
|
a782ca5d3a | ||
|
|
e23c20a6a2 | ||
|
|
f351414046 | ||
|
|
731c149c85 | ||
|
|
c96ce5238f | ||
|
|
fb092f5cec | ||
|
|
57d1498f1d | ||
|
|
abc6db411d | ||
|
|
cbf99a12ab | ||
|
|
28695d2ef0 | ||
|
|
316cdf77be | ||
|
|
e0b960db1a | ||
|
|
b51258c4e8 | ||
|
|
d5a527d5fb | ||
|
|
e4d2773d46 | ||
|
|
16f21800b5 | ||
|
|
90037ce880 | ||
|
|
c7e2ec0495 | ||
|
|
762738484a | ||
|
|
2d1f784415 | ||
|
|
c7acdbd3fd | ||
|
|
da5d81d11c | ||
|
|
9dd9efa4e3 | ||
|
|
436d4dfb89 | ||
|
|
5c0d5d1068 | ||
|
|
0536006012 | ||
|
|
2f0d239b62 | ||
|
|
11cc9fbd27 | ||
|
|
64b0460c4d | ||
|
|
21701bad5a | ||
|
|
7b5f4b3f2d | ||
|
|
4eac0927c1 | ||
|
|
df98e827f6 | ||
|
|
46255e8a38 | ||
|
|
c115232135 | ||
|
|
dec78547fe | ||
|
|
baede65f77 | ||
|
|
138b643d8a | ||
|
|
5fc6f53871 | ||
|
|
ba22d86f70 | ||
|
|
15aa24d2b1 | ||
|
|
a48aa6db88 | ||
|
|
d40c048333 | ||
|
|
0475a2e1b6 | ||
|
|
cf78fce646 | ||
|
|
de49a66601 | ||
|
|
b29b446d18 | ||
|
|
94773c66dc | ||
|
|
92742cac38 | ||
|
|
5bb9e48252 | ||
|
|
73b8cff1b2 | ||
|
|
ba7b00eb29 | ||
|
|
05e54350c7 | ||
|
|
6cf177f92f | ||
|
|
ebcd1618f9 | ||
|
|
8fc208ca31 | ||
|
|
803bd25b0c | ||
|
|
bda980fa4d | ||
|
|
0a4699711f | ||
|
|
837b09fcad | ||
|
|
bbc90dbe08 | ||
|
|
e39b430beb | ||
|
|
f4e7b9c51c | ||
|
|
092be1a782 | ||
|
|
39a477265c | ||
|
|
ad125348d6 | ||
|
|
e782b08a5e | ||
|
|
ad1d5f24cd | ||
|
|
892fe25970 | ||
|
|
d1de42e91b | ||
|
|
ec09010122 | ||
|
|
3c2107d5d1 | ||
|
|
2e03bd8c07 | ||
|
|
7548fd5ed1 | ||
|
|
f048c3d968 | ||
|
|
7c74b42bef | ||
|
|
1284c3ae02 | ||
|
|
3dce3dd247 | ||
|
|
b8009939a2 | ||
|
|
f08c94e2a8 |
@@ -8,7 +8,7 @@ on:
|
|||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-24.04
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
@@ -29,10 +29,13 @@ jobs:
|
|||||||
uses: actions/setup-node@v4
|
uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 22
|
node-version: 22
|
||||||
cache: 'pnpm'
|
cache: pnpm
|
||||||
|
|
||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: pnpm install --frozen-lockfile
|
run: pnpm install --frozen-lockfile --config.auto-install-peers=true
|
||||||
|
|
||||||
|
- name: Build dist
|
||||||
|
run: pnpm run build:dist
|
||||||
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: pnpm test
|
run: pnpm test
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
name: Publish npm package
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
tags:
|
||||||
|
- 'v*'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish:
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: write
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 10
|
||||||
|
|
||||||
|
- name: Setup Node.js
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: 22
|
||||||
|
cache: pnpm
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pnpm install --frozen-lockfile --config.auto-install-peers=true
|
||||||
|
|
||||||
|
- name: Build package
|
||||||
|
run: pnpm run build:dist
|
||||||
|
|
||||||
|
- name: Publish to Gitea Packages
|
||||||
|
run: |
|
||||||
|
npm config set @yuta:registry "$GITEA_NPM_REGISTRY"
|
||||||
|
npm config set -- "//${GITEA_NPM_REGISTRY#*//}:_authToken" "$NODE_AUTH_TOKEN"
|
||||||
|
npm publish --access public
|
||||||
|
env:
|
||||||
|
GITEA_NPM_REGISTRY: ${{ gitea.server_url }}/api/packages/${{ gitea.repository_owner }}/npm/
|
||||||
|
NODE_AUTH_TOKEN: ${{ secrets.PACKAGE_TOKEN }}
|
||||||
@@ -1,5 +1,34 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 0.7.0 — 2026-06-24
|
||||||
|
|
||||||
|
### 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.
|
||||||
|
- `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.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Library typing: `SearchResult` is now a discriminated union (so `error` only exists when `success: false`).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- 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.
|
||||||
|
|
||||||
## 0.6.0 — 2026-01-05
|
## 0.6.0 — 2026-01-05
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
@@ -12,6 +41,9 @@
|
|||||||
### Changed
|
### Changed
|
||||||
- Feature flags can be overridden at runtime via `features.json` (refreshable via `query-ids`).
|
- Feature flags can be overridden at runtime via `features.json` (refreshable via `query-ids`).
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- GraphQL feature flags now include `post_ctas_fetch_enabled` to avoid 400s (#38) — thanks @philipp-spiess.
|
||||||
|
|
||||||
## 0.5.1 — 2026-01-01
|
## 0.5.1 — 2026-01-01
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -1,23 +1,29 @@
|
|||||||
# bird 🐦 — fast X CLI for tweeting, replying, and reading
|
# bird 🐦 — fast X CLI for tweeting, replying, and reading
|
||||||
|
|
||||||
`bird` is a fast X CLI for tweeting, replying, and reading via X/Twitter GraphQL (cookie auth).
|
`bird` is a fast X CLI for tweeting, replying, and reading via X/Twitter GraphQL through twitter safe relay.
|
||||||
|
|
||||||
## Disclaimer
|
## Disclaimer
|
||||||
|
|
||||||
This project uses X/Twitter’s **undocumented** web GraphQL API (and cookie auth). X can change endpoints, query IDs,
|
This project uses X/Twitter’s [**documented**](https://github.com/fa0311/TwitterInternalAPIDocument) internal web
|
||||||
and anti-bot behavior at any time — **expect this to break without notice**.
|
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**.
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|
||||||
|
Gitea Packages:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
npm install -g @steipete/bird
|
npm config set @yuta:registry=https://git.yutakobayashi.com/api/packages/yuta/npm/
|
||||||
# or
|
npm install -g @yuta/bird
|
||||||
pnpm add -g @steipete/bird
|
|
||||||
# or
|
|
||||||
bun add -g @steipete/bird
|
|
||||||
|
|
||||||
# one-shot (no install)
|
# one-shot (no install)
|
||||||
bunx @steipete/bird whoami
|
npx -y @yuta/bird whoami
|
||||||
|
```
|
||||||
|
|
||||||
|
Nix flakes:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
nix run git+https://git.yutakobayashi.com/yuta/bird -- --help
|
||||||
```
|
```
|
||||||
|
|
||||||
Homebrew (macOS, prebuilt Bun binary):
|
Homebrew (macOS, prebuilt Bun binary):
|
||||||
@@ -29,6 +35,9 @@ brew install steipete/tap/bird
|
|||||||
## Quickstart
|
## Quickstart
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
# Point bird at your running twitter safe relay
|
||||||
|
export TWITTER_RELAY_BASE_URL=http://localhost:6900
|
||||||
|
|
||||||
# Show the logged-in account
|
# Show the logged-in account
|
||||||
bird whoami
|
bird whoami
|
||||||
|
|
||||||
@@ -42,12 +51,18 @@ bird 1234567890123456789 --json
|
|||||||
# Thread + replies
|
# Thread + replies
|
||||||
bird thread https://x.com/user/status/1234567890123456789
|
bird thread https://x.com/user/status/1234567890123456789
|
||||||
bird replies 1234567890123456789
|
bird replies 1234567890123456789
|
||||||
|
bird replies 1234567890123456789 --max-pages 3 --json
|
||||||
|
bird thread 1234567890123456789 --max-pages 3 --json
|
||||||
|
|
||||||
# Search + mentions
|
# Search + mentions
|
||||||
bird search "from:steipete" -n 5
|
bird search "from:steipete" -n 5
|
||||||
bird mentions -n 5
|
bird mentions -n 5
|
||||||
bird mentions --user @steipete -n 5
|
bird mentions --user @steipete -n 5
|
||||||
|
|
||||||
|
# User tweets (profile timeline)
|
||||||
|
bird user-tweets @steipete -n 20
|
||||||
|
bird user-tweets @steipete -n 50 --json
|
||||||
|
|
||||||
# Bookmarks
|
# Bookmarks
|
||||||
bird bookmarks -n 5
|
bird bookmarks -n 5
|
||||||
bird bookmarks --folder-id 123456789123456789 -n 5 # https://x.com/i/bookmarks/<folder-id>
|
bird bookmarks --folder-id 123456789123456789 -n 5 # https://x.com/i/bookmarks/<folder-id>
|
||||||
@@ -59,6 +74,15 @@ bird unbookmark https://x.com/user/status/1234567890123456789
|
|||||||
# Likes
|
# Likes
|
||||||
bird likes -n 5
|
bird likes -n 5
|
||||||
|
|
||||||
|
# News and trending topics (AI-curated from Explore tabs)
|
||||||
|
bird news --ai-only -n 10
|
||||||
|
bird news --sports -n 5
|
||||||
|
|
||||||
|
# Lists
|
||||||
|
bird list-timeline 1234567890 -n 20
|
||||||
|
bird list-timeline https://x.com/i/lists/1234567890 --all --json
|
||||||
|
bird list-timeline 1234567890 --max-pages 3 --json
|
||||||
|
|
||||||
# Following (who you follow)
|
# Following (who you follow)
|
||||||
bird following -n 20
|
bird following -n 20
|
||||||
bird following --user 12345678 -n 10 # by user ID
|
bird following --user 12345678 -n 10 # by user ID
|
||||||
@@ -71,16 +95,65 @@ bird followers --user 12345678 -n 10 # by user ID
|
|||||||
bird query-ids --fresh
|
bird query-ids --fresh
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## News & Trending
|
||||||
|
|
||||||
|
Fetch AI-curated news and trending topics from X's Explore page tabs:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Fetch 10 news items from all tabs (default: For You, News, Sports, Entertainment)
|
||||||
|
bird news -n 10
|
||||||
|
|
||||||
|
# Fetch only AI-curated news (filters out regular trends)
|
||||||
|
bird news --ai-only -n 20
|
||||||
|
|
||||||
|
# Fetch from specific tabs
|
||||||
|
bird news --news-only --ai-only -n 10
|
||||||
|
bird news --sports -n 15
|
||||||
|
bird news --entertainment --ai-only -n 5
|
||||||
|
|
||||||
|
# Include related tweets for each news item
|
||||||
|
bird news --with-tweets --tweets-per-item 3 -n 10
|
||||||
|
|
||||||
|
# Combine multiple tab filters
|
||||||
|
bird news --sports --entertainment -n 20
|
||||||
|
|
||||||
|
# JSON output
|
||||||
|
bird news --json -n 5
|
||||||
|
bird news --json-full --ai-only -n 10 # includes raw API response
|
||||||
|
```
|
||||||
|
|
||||||
|
Tab options (can be combined):
|
||||||
|
- `--for-you` — Fetch from For You tab only
|
||||||
|
- `--news-only` — Fetch from News tab only
|
||||||
|
- `--sports` — Fetch from Sports tab only
|
||||||
|
- `--entertainment` — Fetch from Entertainment tab only
|
||||||
|
- `--trending-only` — Fetch from Trending tab only
|
||||||
|
|
||||||
|
By default, the command fetches from For You, News, Sports, and Entertainment tabs (Trending excluded to reduce noise). Headlines are automatically deduplicated across tabs.
|
||||||
|
|
||||||
## Library
|
## Library
|
||||||
|
|
||||||
`bird` can be used as a library (same GraphQL client as the CLI):
|
`bird` can be used as a library (same GraphQL client as the CLI):
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { TwitterClient, resolveCredentials } from '@steipete/bird';
|
import { TwitterClient } from '@yuta/bird';
|
||||||
|
|
||||||
const { cookies } = await resolveCredentials({ cookieSource: 'safari' });
|
const client = new TwitterClient({
|
||||||
const client = new TwitterClient({ cookies });
|
relayBaseUrl: process.env.TWITTER_RELAY_BASE_URL
|
||||||
const result = await client.search('from:steipete', 50);
|
});
|
||||||
|
|
||||||
|
// Search for tweets
|
||||||
|
const searchResult = await client.search('from:steipete', 50);
|
||||||
|
|
||||||
|
// Fetch news and trending topics from all tabs (default: For You, News, Sports, Entertainment)
|
||||||
|
const newsResult = await client.getNews(10, { aiOnly: true });
|
||||||
|
|
||||||
|
// Fetch from specific tabs with related tweets
|
||||||
|
const sportsNews = await client.getNews(10, {
|
||||||
|
aiOnly: true,
|
||||||
|
withTweets: true,
|
||||||
|
tabs: ['sports', 'entertainment']
|
||||||
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
@@ -91,25 +164,32 @@ const result = await client.search('from:steipete', 50);
|
|||||||
- `bird query-ids [--fresh] [--json]` — inspect or refresh cached GraphQL query IDs.
|
- `bird query-ids [--fresh] [--json]` — inspect or refresh cached GraphQL query IDs.
|
||||||
- `bird read <tweet-id-or-url> [--json]` — fetch tweet content as text or JSON.
|
- `bird read <tweet-id-or-url> [--json]` — fetch tweet content as text or JSON.
|
||||||
- `bird <tweet-id-or-url> [--json]` — shorthand for `read` when only a URL or ID is provided.
|
- `bird <tweet-id-or-url> [--json]` — shorthand for `read` when only a URL or ID is provided.
|
||||||
- `bird replies <tweet-id-or-url> [--json]` — list replies to a tweet.
|
- `bird replies <tweet-id-or-url> [--all] [--max-pages n] [--cursor string] [--delay ms] [--json]` — list replies to a tweet.
|
||||||
- `bird thread <tweet-id-or-url> [--json]` — show the full conversation thread.
|
- `bird thread <tweet-id-or-url> [--all] [--max-pages n] [--cursor string] [--delay ms] [--json]` — show the full conversation thread.
|
||||||
- `bird search "<query>" [-n count] [--json]` — search for tweets matching a query.
|
- `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 mentions [-n count] [--user @handle] [--json]` — find tweets mentioning a user (defaults to the authenticated user).
|
- `bird mentions [-n count] [--user @handle] [--json]` — find tweets mentioning a user (defaults to the authenticated user).
|
||||||
|
- `bird user-tweets <@handle> [-n count] [--cursor string] [--max-pages n] [--delay ms] [--json]` — get tweets from a user's profile timeline.
|
||||||
- `bird 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] [--json]` — list your bookmarked tweets (or a specific bookmark folder); `--max-pages` requires `--all`.
|
||||||
- `bird unbookmark <tweet-id-or-url...>` — remove one or more bookmarks by tweet ID or URL.
|
- `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] [--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.
|
||||||
|
- `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 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 followers [--user <userId>] [-n count] [--json]` — list users that follow you (or another user).
|
||||||
- `bird whoami` — print which Twitter account your cookies belong to.
|
- `bird whoami` — print which Twitter account your relay belongs to.
|
||||||
- `bird check` — show which credentials are available and where they were sourced from.
|
- `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.
|
||||||
|
|
||||||
Global options:
|
Global options:
|
||||||
- `--auth-token <token>`: set the `auth_token` cookie manually.
|
- `--relay-base-url <url>`: twitter safe relay base URL (defaults to `TWITTER_RELAY_BASE_URL`).
|
||||||
- `--ct0 <token>`: set the `ct0` cookie manually.
|
|
||||||
- `--cookie-source <safari|chrome|firefox>`: choose browser cookie source (repeatable; order matters).
|
|
||||||
- `--chrome-profile <name>`: Chrome profile for cookie extraction.
|
|
||||||
- `--firefox-profile <name>`: Firefox profile for cookie extraction.
|
|
||||||
- `--cookie-timeout <ms>`: cookie extraction timeout for keychain/OS helpers (milliseconds).
|
|
||||||
- `--timeout <ms>`: abort requests after the given timeout (milliseconds).
|
- `--timeout <ms>`: abort requests after the given timeout (milliseconds).
|
||||||
- `--quote-depth <n>`: max quoted tweet depth in JSON output (default: 1; 0 disables).
|
- `--quote-depth <n>`: max quoted tweet depth in JSON output (default: 1; 0 disables).
|
||||||
- `--plain`: stable output (no emoji, no color).
|
- `--plain`: stable output (no emoji, no color).
|
||||||
@@ -120,23 +200,14 @@ Global options:
|
|||||||
|
|
||||||
## Authentication (GraphQL)
|
## Authentication (GraphQL)
|
||||||
|
|
||||||
GraphQL mode uses your existing X/Twitter web session (no password prompt). It sends requests to internal
|
`bird` does not handle Twitter authentication locally. It sends Twitter API-compatible requests to twitter safe relay,
|
||||||
X endpoints and authenticates via cookies (`auth_token`, `ct0`).
|
and the relay handles authentication.
|
||||||
|
|
||||||
Write operations:
|
Write operations:
|
||||||
- `tweet`/`reply` primarily use GraphQL (`CreateTweet`).
|
- `tweet`/`reply` primarily use GraphQL (`CreateTweet`).
|
||||||
- If GraphQL returns error `226` (“automated request”), `bird` falls back to the legacy `statuses/update.json` endpoint.
|
- If GraphQL returns error `226` (“automated request”), `bird` falls back to the legacy `statuses/update.json` endpoint.
|
||||||
|
|
||||||
`bird` resolves credentials in this order:
|
Configure the relay URL with `TWITTER_RELAY_BASE_URL` or `--relay-base-url`.
|
||||||
|
|
||||||
1. CLI flags: `--auth-token`, `--ct0`
|
|
||||||
2. Environment variables: `AUTH_TOKEN`, `CT0` (fallback: `TWITTER_AUTH_TOKEN`, `TWITTER_CT0`)
|
|
||||||
3. Browser cookies via `@steipete/sweet-cookie` (override via `--cookie-source` order)
|
|
||||||
|
|
||||||
Browser cookie sources:
|
|
||||||
- Safari: `~/Library/Cookies/Cookies.binarycookies` (fallback: `~/Library/Containers/com.apple.Safari/Data/Library/Cookies/Cookies.binarycookies`)
|
|
||||||
- Chrome: `~/Library/Application Support/Google/Chrome/<Profile>/Cookies`
|
|
||||||
- Firefox: `~/Library/Application Support/Firefox/Profiles/<profile>/cookies.sqlite`
|
|
||||||
|
|
||||||
## Config (JSON5)
|
## Config (JSON5)
|
||||||
|
|
||||||
@@ -149,23 +220,21 @@ Example `~/.config/bird/config.json5`:
|
|||||||
|
|
||||||
```json5
|
```json5
|
||||||
{
|
{
|
||||||
// Cookie source order for browser extraction (string or array)
|
relayBaseUrl: "http://localhost:6900",
|
||||||
cookieSource: ["firefox", "safari"],
|
|
||||||
firefoxProfile: "default-release",
|
|
||||||
cookieTimeoutMs: 30000,
|
|
||||||
timeoutMs: 20000,
|
timeoutMs: 20000,
|
||||||
quoteDepth: 1
|
quoteDepth: 1
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Environment shortcuts:
|
Environment shortcuts:
|
||||||
|
- `TWITTER_RELAY_BASE_URL`
|
||||||
- `BIRD_TIMEOUT_MS`
|
- `BIRD_TIMEOUT_MS`
|
||||||
- `BIRD_COOKIE_TIMEOUT_MS`
|
|
||||||
- `BIRD_QUOTE_DEPTH`
|
- `BIRD_QUOTE_DEPTH`
|
||||||
|
|
||||||
## Output
|
## Output
|
||||||
|
|
||||||
- `--json` prints raw tweet objects for read/replies/thread/search/mentions/bookmarks/likes.
|
- `--json` prints raw tweet objects for read/replies/thread/search/mentions/user-tweets/bookmarks/likes.
|
||||||
|
- When using `--json` with pagination (`--all`, `--cursor`, `--max-pages`, or for `user-tweets` when `-n > 20`), output is `{ tweets, nextCursor }`.
|
||||||
- `read` returns full text for Notes and Articles when present.
|
- `read` returns full text for Notes and Articles when present.
|
||||||
- Use `--plain` for stable, script-friendly output (no emoji, no color).
|
- Use `--plain` for stable, script-friendly output (no emoji, no color).
|
||||||
|
|
||||||
@@ -198,8 +267,23 @@ When using `--json` with `following`/`followers`, user objects include:
|
|||||||
| `followersCount` | number? | Followers count |
|
| `followersCount` | number? | Followers count |
|
||||||
| `followingCount` | number? | Following count |
|
| `followingCount` | number? | Following count |
|
||||||
| `isBlueVerified` | boolean? | Blue verified flag |
|
| `isBlueVerified` | boolean? | Blue verified flag |
|
||||||
| `profileImageUrl` | string? | Profile image URL |
|
| `profileImageUrl` | string? | Profile image URL |
|
||||||
| `createdAt` | string? | Account creation timestamp |
|
| `createdAt` | string? | Account creation timestamp |
|
||||||
|
|
||||||
|
When using `--json` with `news`/`trending`, news objects include:
|
||||||
|
|
||||||
|
| Field | Type | Description |
|
||||||
|
|-------|------|-------------|
|
||||||
|
| `id` | string | Unique identifier for the news item |
|
||||||
|
| `headline` | string | News headline or trend title |
|
||||||
|
| `category` | string? | Category (e.g., "AI · Technology", "Trending", "News") |
|
||||||
|
| `timeAgo` | string? | Relative time (e.g., "2h ago") |
|
||||||
|
| `postCount` | number? | Number of posts |
|
||||||
|
| `description` | string? | Item description |
|
||||||
|
| `url` | string? | URL to the trend or news article |
|
||||||
|
| `tweets` | array? | Related tweets (only when `--with-tweets` is used) |
|
||||||
|
| `_raw` | object? | Raw API response (only when `--json-full` is used) |
|
||||||
|
|
||||||
|
|
||||||
## Query IDs (GraphQL)
|
## Query IDs (GraphQL)
|
||||||
|
|
||||||
@@ -240,7 +324,7 @@ Exit codes:
|
|||||||
|
|
||||||
- Attach media with `--media` (repeatable) and optional `--alt` per item.
|
- Attach media with `--media` (repeatable) and optional `--alt` per item.
|
||||||
- Up to 4 images/GIFs, or 1 video (no mixing). Supported: jpg, jpeg, png, webp, gif, mp4, mov.
|
- Up to 4 images/GIFs, or 1 video (no mixing). Supported: jpg, jpeg, png, webp, gif, mp4, mov.
|
||||||
- Images/GIFs + 1 video supported (uploads via Twitter legacy upload endpoint + cookies; video may take longer to process).
|
- Images/GIFs + 1 video supported (uploads via Twitter legacy upload endpoint through the relay; video may take longer to process).
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
@@ -256,6 +340,8 @@ pnpm install
|
|||||||
pnpm run build # dist/ + bun binary
|
pnpm run build # dist/ + bun binary
|
||||||
pnpm run build:dist # dist/ only
|
pnpm run build:dist # dist/ only
|
||||||
pnpm run build:binary
|
pnpm run build:binary
|
||||||
|
nix build .#bird
|
||||||
|
nix run .# -- --help
|
||||||
|
|
||||||
pnpm run dev tweet "Test"
|
pnpm run dev tweet "Test"
|
||||||
pnpm run dev -- --plain check
|
pnpm run dev -- --plain check
|
||||||
|
|||||||
+1
-2
@@ -35,9 +35,8 @@
|
|||||||
<p class="lede lede--small">That path doesn’t exist. The CLI does.</p>
|
<p class="lede lede--small">That path doesn’t exist. The CLI does.</p>
|
||||||
<div class="cta">
|
<div class="cta">
|
||||||
<a class="btn btn--hot" href="./">Go home</a>
|
<a class="btn btn--hot" href="./">Go home</a>
|
||||||
<a class="btn btn--ghost" href="https://github.com/steipete/bird">Open GitHub</a>
|
<a class="btn btn--ghost" href="https://git.yutakobayashi.com/yuta/bird">Open Gitea</a>
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
</body>
|
</body>
|
||||||
</html>
|
</html>
|
||||||
|
|
||||||
|
|||||||
+23
-22
@@ -9,7 +9,7 @@
|
|||||||
<title>bird.fast — fast X CLI</title>
|
<title>bird.fast — fast X CLI</title>
|
||||||
<meta
|
<meta
|
||||||
name="description"
|
name="description"
|
||||||
content="bird is a fast X CLI for tweeting, replying, and reading via the X/Twitter GraphQL API (cookie auth)."
|
content="bird is a fast X CLI for tweeting, replying, and reading via the X/Twitter GraphQL API through twitter safe relay."
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<link rel="canonical" href="https://bird.fast/" />
|
<link rel="canonical" href="https://bird.fast/" />
|
||||||
@@ -53,7 +53,7 @@
|
|||||||
<nav class="nav">
|
<nav class="nav">
|
||||||
<a class="nav__link" href="#install">Install</a>
|
<a class="nav__link" href="#install">Install</a>
|
||||||
<a class="nav__link" href="#commands">Commands</a>
|
<a class="nav__link" href="#commands">Commands</a>
|
||||||
<a class="nav__link" href="https://github.com/steipete/bird">GitHub</a>
|
<a class="nav__link" href="https://git.yutakobayashi.com/yuta/bird">Gitea</a>
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -74,7 +74,7 @@
|
|||||||
|
|
||||||
<div class="cta" data-reveal>
|
<div class="cta" data-reveal>
|
||||||
<a class="btn btn--hot" href="#install">Install</a>
|
<a class="btn btn--hot" href="#install">Install</a>
|
||||||
<a class="btn btn--ghost" href="https://github.com/steipete/bird#quickstart">Quickstart</a>
|
<a class="btn btn--ghost" href="https://git.yutakobayashi.com/yuta/bird#quickstart">Quickstart</a>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="terminal" data-reveal>
|
<div class="terminal" data-reveal>
|
||||||
@@ -85,7 +85,7 @@
|
|||||||
<span class="terminal__label">copy & run</span>
|
<span class="terminal__label">copy & run</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="terminal__body">
|
<div class="terminal__body">
|
||||||
<pre><code id="installCmd">npm install -g @steipete/bird
|
<pre><code id="installCmd">npm install -g @yuta/bird
|
||||||
|
|
||||||
bird whoami
|
bird whoami
|
||||||
bird tweet "hi from bird.fast"</code></pre>
|
bird tweet "hi from bird.fast"</code></pre>
|
||||||
@@ -97,17 +97,17 @@ bird tweet "hi from bird.fast"</code></pre>
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="badges" data-reveal>
|
<div class="badges" data-reveal>
|
||||||
<a class="badge" href="https://www.npmjs.com/package/@steipete/bird">
|
<a class="badge" href="https://www.npmjs.com/package/@yuta/bird">
|
||||||
<span class="badge__k">npm</span>
|
<span class="badge__k">npm</span>
|
||||||
<span class="badge__v">@steipete/bird</span>
|
<span class="badge__v">@yuta/bird</span>
|
||||||
</a>
|
</a>
|
||||||
<a class="badge" href="https://github.com/steipete/bird">
|
<a class="badge" href="https://git.yutakobayashi.com/yuta/bird">
|
||||||
<span class="badge__k">repo</span>
|
<span class="badge__k">repo</span>
|
||||||
<span class="badge__v">steipete/bird</span>
|
<span class="badge__v">yuta/bird</span>
|
||||||
</a>
|
</a>
|
||||||
<a class="badge" href="https://github.com/steipete/bird#authentication-graphql">
|
<a class="badge" href="https://git.yutakobayashi.com/yuta/bird#authentication-graphql">
|
||||||
<span class="badge__k">auth</span>
|
<span class="badge__k">auth</span>
|
||||||
<span class="badge__v">cookies</span>
|
<span class="badge__v">relay</span>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -120,14 +120,14 @@ bird tweet "hi from bird.fast"</code></pre>
|
|||||||
<article class="card">
|
<article class="card">
|
||||||
<h3 class="h3">npm / pnpm / bun</h3>
|
<h3 class="h3">npm / pnpm / bun</h3>
|
||||||
<p class="p">Pick your poison. Node ≥ 20.</p>
|
<p class="p">Pick your poison. Node ≥ 20.</p>
|
||||||
<pre class="code"><code>npm install -g @steipete/bird
|
<pre class="code"><code>npm install -g @yuta/bird
|
||||||
pnpm add -g @steipete/bird
|
pnpm add -g @yuta/bird
|
||||||
bun add -g @steipete/bird</code></pre>
|
bun add -g @yuta/bird</code></pre>
|
||||||
</article>
|
</article>
|
||||||
<article class="card">
|
<article class="card">
|
||||||
<h3 class="h3">One-shot</h3>
|
<h3 class="h3">One-shot</h3>
|
||||||
<p class="p">No install. Just prove it works.</p>
|
<p class="p">No install. Just prove it works.</p>
|
||||||
<pre class="code"><code>bunx @steipete/bird whoami</code></pre>
|
<pre class="code"><code>bunx @yuta/bird whoami</code></pre>
|
||||||
</article>
|
</article>
|
||||||
<article class="card">
|
<article class="card">
|
||||||
<h3 class="h3">Homebrew (macOS)</h3>
|
<h3 class="h3">Homebrew (macOS)</h3>
|
||||||
@@ -197,22 +197,23 @@ bun add -g @steipete/bird</code></pre>
|
|||||||
<aside class="notice notice--warn" role="note" aria-label="Disclaimer">
|
<aside class="notice notice--warn" role="note" aria-label="Disclaimer">
|
||||||
<div class="notice__icon" aria-hidden="true">!</div>
|
<div class="notice__icon" aria-hidden="true">!</div>
|
||||||
<div class="notice__body">
|
<div class="notice__body">
|
||||||
<p class="notice__title">Undocumented API.</p>
|
<p class="notice__title">Documented internal API.</p>
|
||||||
<p class="notice__text">
|
<p class="notice__text">
|
||||||
bird uses X/Twitter’s private web GraphQL endpoints and rotating query IDs. X can change things anytime —
|
bird uses X/Twitter’s
|
||||||
expect breakage without notice.
|
<a href="https://github.com/fa0311/TwitterInternalAPIDocument">documented</a> internal web GraphQL
|
||||||
|
endpoints and rotating query IDs. X can change things anytime — expect breakage without notice.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
<div class="footerline">
|
<div class="footerline">
|
||||||
<a class="tiny" href="https://github.com/steipete/bird#authentication-graphql">
|
<a class="tiny" href="https://git.yutakobayashi.com/yuta/bird#authentication-graphql">
|
||||||
Authentication details
|
Authentication details
|
||||||
</a>
|
</a>
|
||||||
<span class="sep" aria-hidden="true">•</span>
|
<span class="sep" aria-hidden="true">•</span>
|
||||||
<a class="tiny" href="https://github.com/steipete/bird#config-json5">Config (JSON5)</a>
|
<a class="tiny" href="https://git.yutakobayashi.com/yuta/bird#config-json5">Config (JSON5)</a>
|
||||||
<span class="sep" aria-hidden="true">•</span>
|
<span class="sep" aria-hidden="true">•</span>
|
||||||
<a class="tiny" href="https://github.com/steipete/bird/issues">Issues</a>
|
<a class="tiny" href="https://git.yutakobayashi.com/yuta/bird/issues">Issues</a>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
@@ -221,9 +222,9 @@ bun add -g @steipete/bird</code></pre>
|
|||||||
<footer class="bottom">
|
<footer class="bottom">
|
||||||
<div class="bottom__inner">
|
<div class="bottom__inner">
|
||||||
<p class="tiny">
|
<p class="tiny">
|
||||||
Made by <a href="https://steipete.me">Peter</a>. MIT licensed. Built for GitHub Pages.
|
MIT licensed.
|
||||||
</p>
|
</p>
|
||||||
<p class="tiny tiny--muted">bird.fast is the landing page; the project lives on GitHub.</p>
|
<p class="tiny tiny--muted">bird.fast is the landing page; the project lives on Gitea.</p>
|
||||||
</div>
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
|
|
||||||
|
|||||||
+31
-16
@@ -1,10 +1,12 @@
|
|||||||
# Releasing bird
|
# Releasing bird
|
||||||
|
|
||||||
Target destinations:
|
Target destinations:
|
||||||
- npm: `@steipete/bird`
|
- npm: `@yuta/bird`
|
||||||
|
- Gitea Packages: `https://git.yutakobayashi.com/api/packages/yuta/npm/`
|
||||||
|
- Nix flake: `packages.<system>.bird` and `apps.<system>.default`
|
||||||
- Homebrew: tap formula in `steipete/homebrew-tap` (e.g., `bird.rb`)
|
- Homebrew: tap formula in `steipete/homebrew-tap` (e.g., `bird.rb`)
|
||||||
|
|
||||||
## Checklist (npm + GitHub)
|
## Checklist (npm + Gitea)
|
||||||
1) Version bump
|
1) Version bump
|
||||||
- Update `package.json` `version` (semver, e.g., `0.5.0`).
|
- Update `package.json` `version` (semver, e.g., `0.5.0`).
|
||||||
- Update `CHANGELOG.md` and tag the release section.
|
- Update `CHANGELOG.md` and tag the release section.
|
||||||
@@ -13,22 +15,32 @@ Target destinations:
|
|||||||
- `pnpm install`
|
- `pnpm install`
|
||||||
- `pnpm test`
|
- `pnpm test`
|
||||||
- `pnpm run build`
|
- `pnpm run build`
|
||||||
|
- `nix build .#bird`
|
||||||
|
- `nix flake check`
|
||||||
|
|
||||||
3) Publish to npm (scoped)
|
3) Publish to npmjs (scoped)
|
||||||
- Ensure you are logged in (`npm whoami`).
|
- Ensure you are logged in (`npm whoami`).
|
||||||
- `npm publish --access public` (from repo root). Package name is `@steipete/bird`.
|
- `npm publish --access public` (from repo root). Package name is `@yuta/bird`.
|
||||||
- Verify:
|
- Verify:
|
||||||
- `npm view @steipete/bird version`
|
- `npm view @yuta/bird version`
|
||||||
- `npx -y @steipete/bird@<version> --help`
|
- `npx -y @yuta/bird@<version> --help`
|
||||||
|
|
||||||
4) Git tag & GitHub release
|
4) Publish to Gitea Packages
|
||||||
|
- Create a personal access token with package write permission and save it as the repository secret `PACKAGE_TOKEN`.
|
||||||
|
- Push a `v<version>` tag or run the `Publish npm package` workflow manually.
|
||||||
|
- The workflow writes npm auth for `https://git.yutakobayashi.com/api/packages/yuta/npm/` and publishes `@yuta/bird`.
|
||||||
|
- Verify:
|
||||||
|
- `npm view @yuta/bird version --registry=https://git.yutakobayashi.com/api/packages/yuta/npm/`
|
||||||
|
- `npm exec --yes --registry=https://git.yutakobayashi.com/api/packages/yuta/npm/ @yuta/bird@<version> -- --help`
|
||||||
|
|
||||||
|
5) Git tag & Gitea release
|
||||||
- `git tag v<version> && git push origin v<version>`
|
- `git tag v<version> && git push origin v<version>`
|
||||||
- Create GitHub release from the tag. Include changelog notes and attach optional binary (see below).
|
- Create a Gitea release from the tag. Include changelog notes and attach optional binary (see below).
|
||||||
|
|
||||||
## Optional: attach compiled binary
|
## Optional: attach compiled binary
|
||||||
If you want a single-file binary for Homebrew/GitHub assets:
|
If you want a single-file binary for Homebrew/Gitea release assets:
|
||||||
- Build: `pnpm run binary` (uses Bun to produce `./bird`).
|
- Build: `pnpm run binary` (uses Bun to produce `./bird`).
|
||||||
- Upload `bird` to the GitHub release and use it for the Homebrew tarball.
|
- Upload `bird` to the Gitea release and use it for the Homebrew tarball.
|
||||||
|
|
||||||
## Homebrew tap update (steipete/homebrew-tap)
|
## Homebrew tap update (steipete/homebrew-tap)
|
||||||
1) Package the binary
|
1) Package the binary
|
||||||
@@ -38,7 +50,7 @@ If you want a single-file binary for Homebrew/GitHub assets:
|
|||||||
2) Update formula in tap repo
|
2) Update formula in tap repo
|
||||||
- File: `homebrew-tap/bird.rb` (create if absent). Model it after `poltergeist.rb`.
|
- File: `homebrew-tap/bird.rb` (create if absent). Model it after `poltergeist.rb`.
|
||||||
- Fields to update:
|
- Fields to update:
|
||||||
- `url "https://github.com/steipete/bird/releases/download/v<version>/bird-macos-universal-v<version>.tar.gz"`
|
- `url "https://git.yutakobayashi.com/yuta/bird/releases/download/v<version>/bird-macos-universal-v<version>.tar.gz"`
|
||||||
- `sha256 "<calculated_sha>"`
|
- `sha256 "<calculated_sha>"`
|
||||||
- `version "<version>"`
|
- `version "<version>"`
|
||||||
- Install block: `bin.install "bird"`
|
- Install block: `bin.install "bird"`
|
||||||
@@ -49,11 +61,14 @@ If you want a single-file binary for Homebrew/GitHub assets:
|
|||||||
|
|
||||||
## Release order suggestion
|
## Release order suggestion
|
||||||
1) Merge to `main` and tag.
|
1) Merge to `main` and tag.
|
||||||
2) Publish npm.
|
2) Publish npmjs.
|
||||||
3) Build binary, upload to GitHub release.
|
3) Let Gitea Actions publish the package to Gitea Packages.
|
||||||
4) Update Homebrew tap with new URL/SHA.
|
4) Build binary, upload to Gitea release.
|
||||||
|
5) Update Homebrew tap with new URL/SHA.
|
||||||
|
|
||||||
## Notes
|
## Notes
|
||||||
- Scoped npm name (`@steipete/bird`) requires `--access public` on first publish.
|
- Scoped npm name (`@yuta/bird`) requires `--access public` on first publish.
|
||||||
|
- Gitea npm registry auth follows Gitea's package registry format:
|
||||||
|
`npm config set @yuta:registry=https://git.yutakobayashi.com/api/packages/yuta/npm/`.
|
||||||
- Homebrew formula assumes macOS universal binary; adjust URL/name if you ship per-arch.
|
- Homebrew formula assumes macOS universal binary; adjust URL/name if you ship per-arch.
|
||||||
- Config defaults (JSON5) and Safari/Chrome/Firefox cookie selection are documented in `README.md` — keep that in sync for each release.
|
- Config defaults (JSON5) and twitter safe relay setup are documented in `README.md` — keep that in sync for each release.
|
||||||
|
|||||||
+8
-5
@@ -8,21 +8,24 @@
|
|||||||
Runs the CLI against real Twitter/X GraphQL endpoints to verify read-only commands still work.
|
Runs the CLI against real Twitter/X GraphQL endpoints to verify read-only commands still work.
|
||||||
|
|
||||||
Requirements:
|
Requirements:
|
||||||
- Auth cookies in env:
|
- `TWITTER_RELAY_BASE_URL` pointing at a running twitter safe relay
|
||||||
- `AUTH_TOKEN` (or `TWITTER_AUTH_TOKEN`)
|
|
||||||
- `CT0` (or `TWITTER_CT0`)
|
|
||||||
- Network access
|
- Network access
|
||||||
|
|
||||||
Run:
|
Run:
|
||||||
- `pnpm test:live`
|
- `pnpm test:live`
|
||||||
|
- `pnpm bird following --all --max-pages 2 --json`
|
||||||
|
- `pnpm bird list-timeline <list-id> --all --max-pages 2 --json`
|
||||||
|
- `pnpm bird search "from:steipete" --all --max-pages 2 --json`
|
||||||
|
- `pnpm bird home --count 5 --json`
|
||||||
|
- `pnpm bird home --count 5 --following --json`
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
- Live tests are skipped unless `BIRD_LIVE=1` (set by `pnpm test:live`).
|
- Live tests are skipped unless `BIRD_LIVE=1` (set by `pnpm test:live`).
|
||||||
- Search query is configurable via `BIRD_LIVE_SEARCH_QUERY`.
|
- Search query is configurable via `BIRD_LIVE_SEARCH_QUERY`.
|
||||||
- Command timeout is configurable via `BIRD_LIVE_TIMEOUT_MS` (ms).
|
- Command timeout is configurable via `BIRD_LIVE_TIMEOUT_MS` (ms).
|
||||||
- Cookie extraction timeout is configurable via `BIRD_LIVE_COOKIE_TIMEOUT_MS` (ms).
|
|
||||||
- Spawned CLI `NODE_ENV` defaults to `production` (override with `BIRD_LIVE_NODE_ENV`).
|
- 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`.
|
- If you don't tweet, set `BIRD_LIVE_TWEET_ID` to a known tweet ID to use for `read/replies/thread`.
|
||||||
|
- Long-form article coverage: set `BIRD_LIVE_LONGFORM_TWEET_ID` to a known article tweet ID (example: `2007184284944322584` from @X; refresh by finding a tweet with `article` via `bird user-tweets X -n 20 --json`).
|
||||||
- Optional: set `BIRD_LIVE_BOOKMARK_FOLDER_ID` to exercise `bookmarks --folder-id`.
|
- Optional: set `BIRD_LIVE_BOOKMARK_FOLDER_ID` to exercise `bookmarks --folder-id`.
|
||||||
- `bird query-ids --fresh` live coverage: set `BIRD_LIVE_QUERY_IDS_FRESH=1`.
|
- `bird query-ids --fresh` live coverage: set `BIRD_LIVE_QUERY_IDS_FRESH=1`.
|
||||||
- The live suite may hit internal X endpoints (v1.1 REST) as fallback; it still uses cookie auth (no developer API key).
|
- The live suite may hit internal X endpoints (v1.1 REST) as fallback through the relay.
|
||||||
|
|||||||
Generated
+27
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"nodes": {
|
||||||
|
"nixpkgs": {
|
||||||
|
"locked": {
|
||||||
|
"lastModified": 1781577229,
|
||||||
|
"narHash": "sha256-lrp67w8AulE9Ks53n27I45ADSzbOCn4H+CNW1Ck8B+8=",
|
||||||
|
"owner": "NixOS",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"rev": "567a49d1913ce81ac6e9582e3553dd90a955875f",
|
||||||
|
"type": "github"
|
||||||
|
},
|
||||||
|
"original": {
|
||||||
|
"owner": "NixOS",
|
||||||
|
"ref": "nixos-unstable",
|
||||||
|
"repo": "nixpkgs",
|
||||||
|
"type": "github"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": {
|
||||||
|
"inputs": {
|
||||||
|
"nixpkgs": "nixpkgs"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"root": "root",
|
||||||
|
"version": 7
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
{
|
||||||
|
description = "bird - fast X CLI for tweeting, replying, and reading";
|
||||||
|
|
||||||
|
inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
|
||||||
|
|
||||||
|
outputs =
|
||||||
|
{ self, ... }@inputs:
|
||||||
|
|
||||||
|
let
|
||||||
|
supportedSystems = [
|
||||||
|
"x86_64-linux"
|
||||||
|
"aarch64-linux"
|
||||||
|
"aarch64-darwin"
|
||||||
|
];
|
||||||
|
forEachSupportedSystem =
|
||||||
|
f:
|
||||||
|
inputs.nixpkgs.lib.genAttrs supportedSystems (
|
||||||
|
system:
|
||||||
|
f {
|
||||||
|
inherit system;
|
||||||
|
pkgs = import inputs.nixpkgs {
|
||||||
|
inherit system;
|
||||||
|
overlays = [ inputs.self.overlays.default ];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
);
|
||||||
|
in
|
||||||
|
{
|
||||||
|
overlays.default = final: prev: rec {
|
||||||
|
bird = final.callPackage (
|
||||||
|
{
|
||||||
|
fetchPnpmDeps,
|
||||||
|
lib,
|
||||||
|
makeWrapper,
|
||||||
|
nodejs-slim_22,
|
||||||
|
pnpm_10,
|
||||||
|
pnpmConfigHook,
|
||||||
|
stdenv,
|
||||||
|
}:
|
||||||
|
|
||||||
|
let
|
||||||
|
packageJson = builtins.fromJSON (builtins.readFile ./package.json);
|
||||||
|
pnpm = pnpm_10.override { nodejs-slim = nodejs-slim_22; };
|
||||||
|
in
|
||||||
|
stdenv.mkDerivation (finalAttrs: {
|
||||||
|
pname = "bird";
|
||||||
|
version = packageJson.version;
|
||||||
|
|
||||||
|
src = lib.cleanSource ./.;
|
||||||
|
|
||||||
|
pnpmDeps = fetchPnpmDeps {
|
||||||
|
inherit (finalAttrs) pname version src;
|
||||||
|
inherit pnpm;
|
||||||
|
fetcherVersion = 4;
|
||||||
|
pnpmInstallFlags = [ "--config.auto-install-peers=true" ];
|
||||||
|
hash = "sha256-nB6IPSG/2XSVJVNHwtDFVL3ocwVWEzmR7o3o3rNSKP0=";
|
||||||
|
};
|
||||||
|
|
||||||
|
nativeBuildInputs = [
|
||||||
|
makeWrapper
|
||||||
|
nodejs-slim_22
|
||||||
|
pnpm
|
||||||
|
pnpmConfigHook
|
||||||
|
];
|
||||||
|
|
||||||
|
pnpmInstallFlags = [ "--config.auto-install-peers=true" ];
|
||||||
|
|
||||||
|
buildPhase = ''
|
||||||
|
runHook preBuild
|
||||||
|
|
||||||
|
./node_modules/.bin/tsc
|
||||||
|
node scripts/copy-dist-assets.js
|
||||||
|
CI=true pnpm prune --prod --config.auto-install-peers=true
|
||||||
|
find node_modules -xtype l -delete
|
||||||
|
|
||||||
|
runHook postBuild
|
||||||
|
'';
|
||||||
|
|
||||||
|
installPhase = ''
|
||||||
|
runHook preInstall
|
||||||
|
|
||||||
|
mkdir -p $out/lib/bird $out/bin
|
||||||
|
cp -r dist node_modules package.json README.md CHANGELOG.md LICENSE $out/lib/bird/
|
||||||
|
chmod +x $out/lib/bird/dist/cli.js
|
||||||
|
|
||||||
|
makeWrapper ${lib.getExe nodejs-slim_22} $out/bin/bird \
|
||||||
|
--add-flags "$out/lib/bird/dist/cli.js"
|
||||||
|
|
||||||
|
runHook postInstall
|
||||||
|
'';
|
||||||
|
|
||||||
|
meta = {
|
||||||
|
description = packageJson.description;
|
||||||
|
homepage = "https://bird.fast/";
|
||||||
|
license = lib.licenses.mit;
|
||||||
|
mainProgram = "bird";
|
||||||
|
};
|
||||||
|
})
|
||||||
|
) { };
|
||||||
|
|
||||||
|
nodejs = prev.nodejs_22;
|
||||||
|
yarn = (prev.yarn.override { inherit nodejs; });
|
||||||
|
};
|
||||||
|
|
||||||
|
packages = forEachSupportedSystem (
|
||||||
|
{ pkgs, ... }:
|
||||||
|
{
|
||||||
|
default = pkgs.bird;
|
||||||
|
bird = pkgs.bird;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
apps = forEachSupportedSystem (
|
||||||
|
{ system, ... }:
|
||||||
|
{
|
||||||
|
default = {
|
||||||
|
type = "app";
|
||||||
|
program = "${self.packages.${system}.default}/bin/bird";
|
||||||
|
meta.description = "Run bird";
|
||||||
|
};
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
checks = forEachSupportedSystem (
|
||||||
|
{ pkgs, ... }:
|
||||||
|
{
|
||||||
|
default = pkgs.bird;
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
devShells = forEachSupportedSystem (
|
||||||
|
{ pkgs, system }:
|
||||||
|
{
|
||||||
|
default = pkgs.mkShellNoCC {
|
||||||
|
packages = with pkgs; [
|
||||||
|
nodejs
|
||||||
|
pnpm
|
||||||
|
yarn
|
||||||
|
bun
|
||||||
|
self.formatter.${system}
|
||||||
|
];
|
||||||
|
};
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
formatter = forEachSupportedSystem ({ pkgs, ... }: pkgs.nixfmt);
|
||||||
|
};
|
||||||
|
}
|
||||||
+7
-3
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@steipete/bird",
|
"name": "@yuta/bird",
|
||||||
"version": "0.6.0",
|
"version": "0.7.0",
|
||||||
"description": "CLI tool for tweeting and replying via Twitter/X GraphQL API",
|
"description": "CLI tool for tweeting and replying via Twitter/X GraphQL API",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
@@ -8,6 +8,10 @@
|
|||||||
"bin": {
|
"bin": {
|
||||||
"bird": "dist/cli.js"
|
"bird": "dist/cli.js"
|
||||||
},
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://git.yutakobayashi.com/yuta/bird.git"
|
||||||
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"dist",
|
"dist",
|
||||||
"README.md",
|
"README.md",
|
||||||
@@ -23,6 +27,7 @@
|
|||||||
"test": "vitest run",
|
"test": "vitest run",
|
||||||
"test:watch": "vitest",
|
"test:watch": "vitest",
|
||||||
"test:live": "pnpm run build:dist && BIRD_LIVE=1 vitest run --no-file-parallelism tests/live/live.test.ts",
|
"test:live": "pnpm run build:dist && BIRD_LIVE=1 vitest run --no-file-parallelism tests/live/live.test.ts",
|
||||||
|
"test:live:all": "pnpm run build:dist && BIRD_LIVE=1 vitest run --no-file-parallelism tests/live/live-all.test.ts",
|
||||||
"lint": "pnpm run lint:biome && pnpm run lint:oxlint",
|
"lint": "pnpm run lint:biome && pnpm run lint:oxlint",
|
||||||
"lint:biome": "biome check .",
|
"lint:biome": "biome check .",
|
||||||
"lint:oxlint": "oxlint --type-aware --tsconfig tsconfig.oxlint.json --import-plugin --node-plugin --vitest-plugin --deny-warnings src tests scripts",
|
"lint:oxlint": "oxlint --type-aware --tsconfig tsconfig.oxlint.json --import-plugin --node-plugin --vitest-plugin --deny-warnings src tests scripts",
|
||||||
@@ -34,7 +39,6 @@
|
|||||||
"graphql:update": "tsx scripts/update-query-ids.ts"
|
"graphql:update": "tsx scripts/update-query-ids.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@steipete/sweet-cookie": "0.1.0",
|
|
||||||
"commander": "^14.0.2",
|
"commander": "^14.0.2",
|
||||||
"json5": "^2.2.3",
|
"json5": "^2.2.3",
|
||||||
"kleur": "^4.1.5"
|
"kleur": "^4.1.5"
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
diff --git a/dist/providers/chromeSqliteMac.js b/dist/providers/chromeSqliteMac.js
|
|
||||||
index 71c815f77378d03e07061976ac372b3a55a61ac4..3a85a2fce102128d7e7b69145d97bc353f663008 100644
|
|
||||||
--- a/dist/providers/chromeSqliteMac.js
|
|
||||||
+++ b/dist/providers/chromeSqliteMac.js
|
|
||||||
@@ -15,7 +15,7 @@ export async function getCookiesFromChromeSqliteMac(options, origins, allowlistN
|
|
||||||
const passwordResult = await readKeychainGenericPasswordFirst({
|
|
||||||
account: 'Chrome',
|
|
||||||
services: ['Chrome Safe Storage'],
|
|
||||||
- timeoutMs: 3_000,
|
|
||||||
+ timeoutMs: options.timeoutMs ?? 3_000,
|
|
||||||
label: 'Chrome Safe Storage',
|
|
||||||
});
|
|
||||||
if (!passwordResult.ok) {
|
|
||||||
Generated
+20
-15
@@ -1,21 +1,13 @@
|
|||||||
lockfileVersion: '9.0'
|
lockfileVersion: '9.0'
|
||||||
|
|
||||||
settings:
|
settings:
|
||||||
autoInstallPeers: false
|
autoInstallPeers: true
|
||||||
excludeLinksFromLockfile: false
|
excludeLinksFromLockfile: false
|
||||||
|
|
||||||
patchedDependencies:
|
|
||||||
'@steipete/sweet-cookie':
|
|
||||||
hash: 05180a0fa74ba5074775f965db7d4561e59ba51978bd5e955c0e4f058a4ed340
|
|
||||||
path: patches/@steipete__sweet-cookie.patch
|
|
||||||
|
|
||||||
importers:
|
importers:
|
||||||
|
|
||||||
.:
|
.:
|
||||||
dependencies:
|
dependencies:
|
||||||
'@steipete/sweet-cookie':
|
|
||||||
specifier: 0.1.0
|
|
||||||
version: 0.1.0(patch_hash=05180a0fa74ba5074775f965db7d4561e59ba51978bd5e955c0e4f058a4ed340)
|
|
||||||
commander:
|
commander:
|
||||||
specifier: ^14.0.2
|
specifier: ^14.0.2
|
||||||
version: 14.0.2
|
version: 14.0.2
|
||||||
@@ -96,24 +88,28 @@ packages:
|
|||||||
engines: {node: '>=14.21.3'}
|
engines: {node: '>=14.21.3'}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
'@biomejs/[email protected]':
|
'@biomejs/[email protected]':
|
||||||
resolution: {integrity: sha512-hhPw2V3/EpHKsileVOFynuWiKRgFEV48cLe0eA+G2wO4SzlwEhLEB9LhlSrVeu2mtSn205W283LkX7Fh48CaxA==}
|
resolution: {integrity: sha512-hhPw2V3/EpHKsileVOFynuWiKRgFEV48cLe0eA+G2wO4SzlwEhLEB9LhlSrVeu2mtSn205W283LkX7Fh48CaxA==}
|
||||||
engines: {node: '>=14.21.3'}
|
engines: {node: '>=14.21.3'}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@biomejs/[email protected]':
|
'@biomejs/[email protected]':
|
||||||
resolution: {integrity: sha512-QTfHZQh62SDFdYc2nfmZFuTm5yYb4eO1zwfB+90YxUumRCR171tS1GoTX5OD0wrv4UsziMPmrePMtkTnNyYG3g==}
|
resolution: {integrity: sha512-QTfHZQh62SDFdYc2nfmZFuTm5yYb4eO1zwfB+90YxUumRCR171tS1GoTX5OD0wrv4UsziMPmrePMtkTnNyYG3g==}
|
||||||
engines: {node: '>=14.21.3'}
|
engines: {node: '>=14.21.3'}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
'@biomejs/[email protected]':
|
'@biomejs/[email protected]':
|
||||||
resolution: {integrity: sha512-wwAkWD1MR95u+J4LkWP74/vGz+tRrIQvr8kfMMJY8KOQ8+HMVleREOcPYsQX82S7uueco60L58Wc6M1I9WA9Dw==}
|
resolution: {integrity: sha512-wwAkWD1MR95u+J4LkWP74/vGz+tRrIQvr8kfMMJY8KOQ8+HMVleREOcPYsQX82S7uueco60L58Wc6M1I9WA9Dw==}
|
||||||
engines: {node: '>=14.21.3'}
|
engines: {node: '>=14.21.3'}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@biomejs/[email protected]':
|
'@biomejs/[email protected]':
|
||||||
resolution: {integrity: sha512-o7lYc9n+CfRbHvkjPhm8s9FgbKdYZu5HCcGVMItLjz93EhgJ8AM44W+QckDqLA9MKDNFrR8nPbO4b73VC5kGGQ==}
|
resolution: {integrity: sha512-o7lYc9n+CfRbHvkjPhm8s9FgbKdYZu5HCcGVMItLjz93EhgJ8AM44W+QckDqLA9MKDNFrR8nPbO4b73VC5kGGQ==}
|
||||||
@@ -337,21 +333,25 @@ packages:
|
|||||||
resolution: {integrity: sha512-EMx92X5q+hHc3olTuj/kgkx9+yP0p/AVs4yvHbUfzZhBekXNpUWxWvg4hIKmQWn+Ee2j4o80/0ACGO0hDYJ9mg==}
|
resolution: {integrity: sha512-EMx92X5q+hHc3olTuj/kgkx9+yP0p/AVs4yvHbUfzZhBekXNpUWxWvg4hIKmQWn+Ee2j4o80/0ACGO0hDYJ9mg==}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@oxlint/[email protected]':
|
'@oxlint/[email protected]':
|
||||||
resolution: {integrity: sha512-7YCxtrPIctVYLqWrWkk8pahdCxch6PtsaucfMLC7TOlDt4nODhnQd4yzEscKqJ8Gjrw1bF4g+Ngob1gB+Qr9Fw==}
|
resolution: {integrity: sha512-7YCxtrPIctVYLqWrWkk8pahdCxch6PtsaucfMLC7TOlDt4nODhnQd4yzEscKqJ8Gjrw1bF4g+Ngob1gB+Qr9Fw==}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
'@oxlint/[email protected]':
|
'@oxlint/[email protected]':
|
||||||
resolution: {integrity: sha512-lnaJVlx5r3NWmoOMesfQXJSf78jHTn8Z+sdAf795Kgteo72+qGC1Uax2SToCJVN2J8PNG3oRV5bLriiCNR2i6Q==}
|
resolution: {integrity: sha512-lnaJVlx5r3NWmoOMesfQXJSf78jHTn8Z+sdAf795Kgteo72+qGC1Uax2SToCJVN2J8PNG3oRV5bLriiCNR2i6Q==}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@oxlint/[email protected]':
|
'@oxlint/[email protected]':
|
||||||
resolution: {integrity: sha512-AhuEU2Qdl66lSfTGu/Htirq8r/8q2YnZoG3yEXLMQWnPMn7efy8spD/N1NA7kH0Hll+cdfwgQkQqC2G4MS2lPQ==}
|
resolution: {integrity: sha512-AhuEU2Qdl66lSfTGu/Htirq8r/8q2YnZoG3yEXLMQWnPMn7efy8spD/N1NA7kH0Hll+cdfwgQkQqC2G4MS2lPQ==}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
'@oxlint/[email protected]':
|
'@oxlint/[email protected]':
|
||||||
resolution: {integrity: sha512-GlWCBjUJY2QgvBFuNRkiRJu7K/djLmM0UQKfZV8IN+UXbP/JbjZHWKRdd4LXlQmzoz7M5Hd6p+ElCej8/90FCg==}
|
resolution: {integrity: sha512-GlWCBjUJY2QgvBFuNRkiRJu7K/djLmM0UQKfZV8IN+UXbP/JbjZHWKRdd4LXlQmzoz7M5Hd6p+ElCej8/90FCg==}
|
||||||
@@ -397,56 +397,67 @@ packages:
|
|||||||
resolution: {integrity: sha512-dV3T9MyAf0w8zPVLVBptVlzaXxka6xg1f16VAQmjg+4KMSTWDvhimI/Y6mp8oHwNrmnmVl9XxJ/w/mO4uIQONA==}
|
resolution: {integrity: sha512-dV3T9MyAf0w8zPVLVBptVlzaXxka6xg1f16VAQmjg+4KMSTWDvhimI/Y6mp8oHwNrmnmVl9XxJ/w/mO4uIQONA==}
|
||||||
cpu: [arm]
|
cpu: [arm]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-wIGYC1x/hyjP+KAu9+ewDI+fi5XSNiUi9Bvg6KGAh2TsNMA3tSEs+Sh6jJ/r4BV/bx/CyWu2ue9kDnIdRyafcQ==}
|
resolution: {integrity: sha512-wIGYC1x/hyjP+KAu9+ewDI+fi5XSNiUi9Bvg6KGAh2TsNMA3tSEs+Sh6jJ/r4BV/bx/CyWu2ue9kDnIdRyafcQ==}
|
||||||
cpu: [arm]
|
cpu: [arm]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-Y+qVA0D9d0y2FRNiG9oM3Hut/DgODZbU9I8pLLPwAsU0tUKZ49cyV1tzmB/qRbSzGvY8lpgGkJuMyuhH7Ma+Vg==}
|
resolution: {integrity: sha512-Y+qVA0D9d0y2FRNiG9oM3Hut/DgODZbU9I8pLLPwAsU0tUKZ49cyV1tzmB/qRbSzGvY8lpgGkJuMyuhH7Ma+Vg==}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-juaC4bEgJsyFVfqhtGLz8mbopaWD+WeSOYr5E16y+1of6KQjc0BpwZLuxkClqY1i8sco+MdyoXPNiCkQou09+g==}
|
resolution: {integrity: sha512-juaC4bEgJsyFVfqhtGLz8mbopaWD+WeSOYr5E16y+1of6KQjc0BpwZLuxkClqY1i8sco+MdyoXPNiCkQou09+g==}
|
||||||
cpu: [arm64]
|
cpu: [arm64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-rIEC0hZ17A42iXtHX+EPJVL/CakHo+tT7W0pbzdAGuWOt2jxDFh7A/lRhsNHBcqL4T36+UiAgwO8pbmn3dE8wA==}
|
resolution: {integrity: sha512-rIEC0hZ17A42iXtHX+EPJVL/CakHo+tT7W0pbzdAGuWOt2jxDFh7A/lRhsNHBcqL4T36+UiAgwO8pbmn3dE8wA==}
|
||||||
cpu: [loong64]
|
cpu: [loong64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-T7l409NhUE552RcAOcmJHj3xyZ2h7vMWzcwQI0hvn5tqHh3oSoclf9WgTl+0QqffWFG8MEVZZP1/OBglKZx52Q==}
|
resolution: {integrity: sha512-T7l409NhUE552RcAOcmJHj3xyZ2h7vMWzcwQI0hvn5tqHh3oSoclf9WgTl+0QqffWFG8MEVZZP1/OBglKZx52Q==}
|
||||||
cpu: [ppc64]
|
cpu: [ppc64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-7OK5/GhxbnrMcxIFoYfhV/TkknarkYC1hqUw1wU2xUN3TVRLNT5FmBv4KkheSG2xZ6IEbRAhTooTV2+R5Tk0lQ==}
|
resolution: {integrity: sha512-7OK5/GhxbnrMcxIFoYfhV/TkknarkYC1hqUw1wU2xUN3TVRLNT5FmBv4KkheSG2xZ6IEbRAhTooTV2+R5Tk0lQ==}
|
||||||
cpu: [riscv64]
|
cpu: [riscv64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-GwuDBE/PsXaTa76lO5eLJTyr2k8QkPipAyOrs4V/KJufHCZBJ495VCGJol35grx9xryk4V+2zd3Ri+3v7NPh+w==}
|
resolution: {integrity: sha512-GwuDBE/PsXaTa76lO5eLJTyr2k8QkPipAyOrs4V/KJufHCZBJ495VCGJol35grx9xryk4V+2zd3Ri+3v7NPh+w==}
|
||||||
cpu: [riscv64]
|
cpu: [riscv64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-IAE1Ziyr1qNfnmiQLHBURAD+eh/zH1pIeJjeShleII7Vj8kyEm2PF77o+lf3WTHDpNJcu4IXJxNO0Zluro8bOw==}
|
resolution: {integrity: sha512-IAE1Ziyr1qNfnmiQLHBURAD+eh/zH1pIeJjeShleII7Vj8kyEm2PF77o+lf3WTHDpNJcu4IXJxNO0Zluro8bOw==}
|
||||||
cpu: [s390x]
|
cpu: [s390x]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-Pg6E+oP7GvZ4XwgRJBuSXZjcqpIW3yCBhK4BcsANvb47qMvAbCjR6E+1a/U2WXz1JJxp9/4Dno3/iSJLcm5auw==}
|
resolution: {integrity: sha512-Pg6E+oP7GvZ4XwgRJBuSXZjcqpIW3yCBhK4BcsANvb47qMvAbCjR6E+1a/U2WXz1JJxp9/4Dno3/iSJLcm5auw==}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [glibc]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-txGtluxDKTxaMDzUduGP0wdfng24y1rygUMnmlUJ88fzCCULCLn7oE5kb2+tRB+MWq1QDZT6ObT5RrR8HFRKqg==}
|
resolution: {integrity: sha512-txGtluxDKTxaMDzUduGP0wdfng24y1rygUMnmlUJ88fzCCULCLn7oE5kb2+tRB+MWq1QDZT6ObT5RrR8HFRKqg==}
|
||||||
cpu: [x64]
|
cpu: [x64]
|
||||||
os: [linux]
|
os: [linux]
|
||||||
|
libc: [musl]
|
||||||
|
|
||||||
'@rollup/[email protected]':
|
'@rollup/[email protected]':
|
||||||
resolution: {integrity: sha512-3DFiLPnTxiOQV993fMc+KO8zXHTcIjgaInrqlG8zDp1TlhYl6WgrOHuJkJQ6M8zHEcntSJsUp1XFZSY8C1DYbg==}
|
resolution: {integrity: sha512-3DFiLPnTxiOQV993fMc+KO8zXHTcIjgaInrqlG8zDp1TlhYl6WgrOHuJkJQ6M8zHEcntSJsUp1XFZSY8C1DYbg==}
|
||||||
@@ -476,10 +487,6 @@ packages:
|
|||||||
'@standard-schema/[email protected]':
|
'@standard-schema/[email protected]':
|
||||||
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==}
|
||||||
|
|
||||||
'@steipete/[email protected]':
|
|
||||||
resolution: {integrity: sha512-cF8hS6rTohAFI1NAm2/HM9omBlw6V1DpwF6q5e9FB+l274HjtyirCgCc6QK2Rtuh7uDoqWHshFQZPsceyJuVgw==}
|
|
||||||
engines: {node: '>=22'}
|
|
||||||
|
|
||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
|
||||||
|
|
||||||
@@ -1056,8 +1063,6 @@ snapshots:
|
|||||||
|
|
||||||
'@standard-schema/[email protected]': {}
|
'@standard-schema/[email protected]': {}
|
||||||
|
|
||||||
'@steipete/[email protected](patch_hash=05180a0fa74ba5074775f965db7d4561e59ba51978bd5e955c0e4f058a4ed340)': {}
|
|
||||||
|
|
||||||
'@types/[email protected]':
|
'@types/[email protected]':
|
||||||
dependencies:
|
dependencies:
|
||||||
'@types/deep-eql': 4.0.2
|
'@types/deep-eql': 4.0.2
|
||||||
|
|||||||
+2
-3
@@ -1,5 +1,4 @@
|
|||||||
|
allowBuilds:
|
||||||
|
esbuild: true
|
||||||
onlyBuiltDependencies:
|
onlyBuiltDependencies:
|
||||||
- esbuild
|
- esbuild
|
||||||
|
|
||||||
patchedDependencies:
|
|
||||||
'@steipete/sweet-cookie': patches/@steipete__sweet-cookie.patch
|
|
||||||
|
|||||||
@@ -19,6 +19,10 @@ const TARGET_OPERATIONS = [
|
|||||||
'Following',
|
'Following',
|
||||||
'Followers',
|
'Followers',
|
||||||
'Likes',
|
'Likes',
|
||||||
|
'ExploreSidebar',
|
||||||
|
'ExplorePage',
|
||||||
|
'GenericTimelineById',
|
||||||
|
'TrendHistory',
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
type OperationName = (typeof TARGET_OPERATIONS)[number];
|
type OperationName = (typeof TARGET_OPERATIONS)[number];
|
||||||
|
|||||||
@@ -0,0 +1,79 @@
|
|||||||
|
export type PaginationCmdOpts = {
|
||||||
|
all?: boolean;
|
||||||
|
maxPages?: string;
|
||||||
|
cursor?: string;
|
||||||
|
delay?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function parsePositiveIntFlag(
|
||||||
|
raw: string | undefined,
|
||||||
|
flagName: string,
|
||||||
|
): { ok: true; value: number | undefined } | { ok: false; error: string } {
|
||||||
|
if (raw === undefined) {
|
||||||
|
return { ok: true, value: undefined };
|
||||||
|
}
|
||||||
|
const value = Number.parseInt(raw, 10);
|
||||||
|
if (!Number.isFinite(value) || value <= 0) {
|
||||||
|
return { ok: false, error: `Invalid ${flagName}. Expected a positive integer.` };
|
||||||
|
}
|
||||||
|
return { ok: true, value };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseNonNegativeIntFlag(
|
||||||
|
raw: string | undefined,
|
||||||
|
flagName: string,
|
||||||
|
defaultValue: number,
|
||||||
|
): { ok: true; value: number } | { ok: false; error: string } {
|
||||||
|
const value = Number.parseInt(raw ?? String(defaultValue), 10);
|
||||||
|
if (!Number.isFinite(value) || value < 0) {
|
||||||
|
return { ok: false, error: `Invalid ${flagName}. Expected a non-negative integer.` };
|
||||||
|
}
|
||||||
|
return { ok: true, value };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parsePaginationFlags(
|
||||||
|
cmdOpts: PaginationCmdOpts,
|
||||||
|
opts?: {
|
||||||
|
maxPagesImpliesPagination?: boolean;
|
||||||
|
defaultDelayMs?: number;
|
||||||
|
includeDelay?: boolean;
|
||||||
|
},
|
||||||
|
):
|
||||||
|
| {
|
||||||
|
ok: true;
|
||||||
|
usePagination: boolean;
|
||||||
|
maxPages?: number;
|
||||||
|
cursor?: string;
|
||||||
|
pageDelayMs?: number;
|
||||||
|
}
|
||||||
|
| { ok: false; error: string } {
|
||||||
|
const maxPagesImpliesPagination = opts?.maxPagesImpliesPagination ?? false;
|
||||||
|
const includeDelay = opts?.includeDelay ?? false;
|
||||||
|
const defaultDelayMs = opts?.defaultDelayMs ?? 1000;
|
||||||
|
|
||||||
|
const maxPages = parsePositiveIntFlag(cmdOpts.maxPages, '--max-pages');
|
||||||
|
if (!maxPages.ok) {
|
||||||
|
return maxPages;
|
||||||
|
}
|
||||||
|
|
||||||
|
const usePagination = Boolean(
|
||||||
|
cmdOpts.all || cmdOpts.cursor || (maxPagesImpliesPagination && maxPages.value !== undefined),
|
||||||
|
);
|
||||||
|
|
||||||
|
let pageDelayMs: number | undefined;
|
||||||
|
if (includeDelay) {
|
||||||
|
const delay = parseNonNegativeIntFlag(cmdOpts.delay, '--delay', defaultDelayMs);
|
||||||
|
if (!delay.ok) {
|
||||||
|
return delay;
|
||||||
|
}
|
||||||
|
pageDelayMs = delay.value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
ok: true,
|
||||||
|
usePagination,
|
||||||
|
maxPages: maxPages.value,
|
||||||
|
cursor: cmdOpts.cursor,
|
||||||
|
pageDelayMs,
|
||||||
|
};
|
||||||
|
}
|
||||||
+17
-12
@@ -2,15 +2,18 @@ import { Command } from 'commander';
|
|||||||
import { registerBookmarksCommand } from '../commands/bookmarks.js';
|
import { registerBookmarksCommand } from '../commands/bookmarks.js';
|
||||||
import { registerCheckCommand } from '../commands/check.js';
|
import { registerCheckCommand } from '../commands/check.js';
|
||||||
import { registerHelpCommand } from '../commands/help.js';
|
import { registerHelpCommand } from '../commands/help.js';
|
||||||
|
import { registerHomeCommand } from '../commands/home.js';
|
||||||
import { registerListsCommand } from '../commands/lists.js';
|
import { registerListsCommand } from '../commands/lists.js';
|
||||||
|
import { registerNewsCommand } from '../commands/news.js';
|
||||||
import { registerPostCommands } from '../commands/post.js';
|
import { registerPostCommands } from '../commands/post.js';
|
||||||
import { registerQueryIdsCommand } from '../commands/query-ids.js';
|
import { registerQueryIdsCommand } from '../commands/query-ids.js';
|
||||||
import { registerReadCommands } from '../commands/read.js';
|
import { registerReadCommands } from '../commands/read.js';
|
||||||
import { registerSearchCommands } from '../commands/search.js';
|
import { registerSearchCommands } from '../commands/search.js';
|
||||||
import { registerUnbookmarkCommand } from '../commands/unbookmark.js';
|
import { registerUnbookmarkCommand } from '../commands/unbookmark.js';
|
||||||
|
import { registerUserTweetsCommand } from '../commands/user-tweets.js';
|
||||||
import { registerUserCommands } from '../commands/users.js';
|
import { registerUserCommands } from '../commands/users.js';
|
||||||
import { getCliVersion } from '../lib/version.js';
|
import { getCliVersion } from '../lib/version.js';
|
||||||
import { type CliContext, collectCookieSource } from './shared.js';
|
import type { CliContext } from './shared.js';
|
||||||
|
|
||||||
export const KNOWN_COMMANDS = new Set([
|
export const KNOWN_COMMANDS = new Set([
|
||||||
'tweet',
|
'tweet',
|
||||||
@@ -28,6 +31,10 @@ export const KNOWN_COMMANDS = new Set([
|
|||||||
'likes',
|
'likes',
|
||||||
'lists',
|
'lists',
|
||||||
'list-timeline',
|
'list-timeline',
|
||||||
|
'home',
|
||||||
|
'user-tweets',
|
||||||
|
'news',
|
||||||
|
'trending',
|
||||||
'help',
|
'help',
|
||||||
'whoami',
|
'whoami',
|
||||||
'check',
|
'check',
|
||||||
@@ -76,8 +83,8 @@ export function createProgram(ctx: CliContext): Command {
|
|||||||
'afterAll',
|
'afterAll',
|
||||||
() =>
|
() =>
|
||||||
`\n${ctx.colors.section('Examples')}\n${[
|
`\n${ctx.colors.section('Examples')}\n${[
|
||||||
formatExample('bird whoami', 'Show the logged-in account via GraphQL cookies'),
|
formatExample('bird whoami', 'Show the relay account'),
|
||||||
formatExample('bird --firefox-profile default-release whoami', 'Use Firefox profile cookies'),
|
formatExample('bird --relay-base-url http://localhost:6900 whoami', 'Use a specific twitter safe relay'),
|
||||||
formatExample('bird tweet "hello from bird"', 'Send a tweet'),
|
formatExample('bird tweet "hello from bird"', 'Send a tweet'),
|
||||||
formatExample(
|
formatExample(
|
||||||
'bird 1234567890123456789 --json',
|
'bird 1234567890123456789 --json',
|
||||||
@@ -86,7 +93,7 @@ export function createProgram(ctx: CliContext): Command {
|
|||||||
].join('\n\n')}\n\n${ctx.colors.section('Shortcuts')}\n${[
|
].join('\n\n')}\n\n${ctx.colors.section('Shortcuts')}\n${[
|
||||||
formatExample('bird <tweet-id-or-url> [--json]', 'Shorthand for `bird read <tweet-id-or-url>`'),
|
formatExample('bird <tweet-id-or-url> [--json]', 'Shorthand for `bird read <tweet-id-or-url>`'),
|
||||||
].join('\n\n')}\n\n${ctx.colors.section('JSON Output')}\n${ctx.colors.muted(
|
].join('\n\n')}\n\n${ctx.colors.section('JSON Output')}\n${ctx.colors.muted(
|
||||||
` Add ${ctx.colors.option('--json')} to: read, replies, thread, search, mentions, bookmarks, likes, following, followers, lists, list-timeline, query-ids`,
|
` Add ${ctx.colors.option('--json')} to: read, replies, thread, search, mentions, bookmarks, likes, following, followers, lists, list-timeline, user-tweets, query-ids`,
|
||||||
)}\n${ctx.colors.muted(
|
)}\n${ctx.colors.muted(
|
||||||
` Add ${ctx.colors.option('--json-full')} to include raw API response in ${ctx.colors.argument('_raw')} field (tweet commands only)`,
|
` Add ${ctx.colors.option('--json-full')} to include raw API response in ${ctx.colors.argument('_raw')} field (tweet commands only)`,
|
||||||
)}\n${ctx.colors.muted(` (Run ${ctx.colors.command('bird <command> --help')} to see per-command flags.)`)}`,
|
)}\n${ctx.colors.muted(` (Run ${ctx.colors.command('bird <command> --help')} to see per-command flags.)`)}`,
|
||||||
@@ -98,19 +105,14 @@ export function createProgram(ctx: CliContext): Command {
|
|||||||
`\n\n${ctx.colors.section('Config')}\n${ctx.colors.muted(
|
`\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)`,
|
` Reads ${ctx.colors.argument('~/.config/bird/config.json5')} and ${ctx.colors.argument('./.birdrc.json5')} (JSON5)`,
|
||||||
)}\n${ctx.colors.muted(
|
)}\n${ctx.colors.muted(
|
||||||
` Supports: chromeProfile, firefoxProfile, cookieSource, cookieTimeoutMs, timeoutMs, quoteDepth`,
|
` Supports: relayBaseUrl, timeoutMs, quoteDepth`,
|
||||||
)}\n\n${ctx.colors.section('Env')}\n${ctx.colors.muted(
|
)}\n\n${ctx.colors.section('Env')}\n${ctx.colors.muted(
|
||||||
` ${ctx.colors.option('NO_COLOR')}, ${ctx.colors.option('BIRD_TIMEOUT_MS')}, ${ctx.colors.option('BIRD_COOKIE_TIMEOUT_MS')}, ${ctx.colors.option('BIRD_QUOTE_DEPTH')}`,
|
` ${ctx.colors.option('TWITTER_RELAY_BASE_URL')}, ${ctx.colors.option('NO_COLOR')}, ${ctx.colors.option('BIRD_TIMEOUT_MS')}, ${ctx.colors.option('BIRD_QUOTE_DEPTH')}`,
|
||||||
)}`,
|
)}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
program
|
program
|
||||||
.option('--auth-token <token>', 'Twitter auth_token cookie')
|
.option('--relay-base-url <url>', 'twitter safe relay base URL', ctx.config.relayBaseUrl)
|
||||||
.option('--ct0 <token>', 'Twitter ct0 cookie')
|
|
||||||
.option('--chrome-profile <name>', 'Chrome profile name for cookie extraction', ctx.config.chromeProfile)
|
|
||||||
.option('--firefox-profile <name>', 'Firefox profile name for cookie extraction', ctx.config.firefoxProfile)
|
|
||||||
.option('--cookie-timeout <ms>', 'Cookie extraction timeout in milliseconds (keychain/OS helpers)')
|
|
||||||
.option('--cookie-source <source>', 'Cookie source for browser cookie extraction (repeatable)', collectCookieSource)
|
|
||||||
.option('--media <path>', 'Attach media file (repeatable, up to 4 images or 1 video)', collect)
|
.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('--alt <text>', 'Alt text for the corresponding --media (repeatable)', collect)
|
||||||
.option('--timeout <ms>', 'Request timeout in milliseconds')
|
.option('--timeout <ms>', 'Request timeout in milliseconds')
|
||||||
@@ -131,7 +133,10 @@ export function createProgram(ctx: CliContext): Command {
|
|||||||
registerBookmarksCommand(program, ctx);
|
registerBookmarksCommand(program, ctx);
|
||||||
registerUnbookmarkCommand(program, ctx);
|
registerUnbookmarkCommand(program, ctx);
|
||||||
registerListsCommand(program, ctx);
|
registerListsCommand(program, ctx);
|
||||||
|
registerHomeCommand(program, ctx);
|
||||||
registerUserCommands(program, ctx);
|
registerUserCommands(program, ctx);
|
||||||
|
registerUserTweetsCommand(program, ctx);
|
||||||
|
registerNewsCommand(program, ctx);
|
||||||
registerCheckCommand(program, ctx);
|
registerCheckCommand(program, ctx);
|
||||||
|
|
||||||
return program;
|
return program;
|
||||||
|
|||||||
+92
-64
@@ -4,9 +4,9 @@ import { join } from 'node:path';
|
|||||||
import type { Command } from 'commander';
|
import type { Command } from 'commander';
|
||||||
import JSON5 from 'json5';
|
import JSON5 from 'json5';
|
||||||
import kleur from 'kleur';
|
import kleur from 'kleur';
|
||||||
import { type CookieSource, resolveCredentials } from '../lib/cookies.js';
|
|
||||||
import { extractTweetId } from '../lib/extract-tweet-id.js';
|
import { extractTweetId } from '../lib/extract-tweet-id.js';
|
||||||
import {
|
import {
|
||||||
|
hyperlink,
|
||||||
labelPrefix,
|
labelPrefix,
|
||||||
type OutputConfig,
|
type OutputConfig,
|
||||||
resolveOutputConfigFromArgv,
|
resolveOutputConfigFromArgv,
|
||||||
@@ -16,10 +16,7 @@ import {
|
|||||||
import type { TweetData } from '../lib/twitter-client.js';
|
import type { TweetData } from '../lib/twitter-client.js';
|
||||||
|
|
||||||
export type BirdConfig = {
|
export type BirdConfig = {
|
||||||
chromeProfile?: string;
|
relayBaseUrl?: string;
|
||||||
firefoxProfile?: string;
|
|
||||||
cookieSource?: CookieSource | CookieSource[];
|
|
||||||
cookieTimeoutMs?: number;
|
|
||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
quoteDepth?: number;
|
quoteDepth?: number;
|
||||||
};
|
};
|
||||||
@@ -47,44 +44,23 @@ export type CliContext = {
|
|||||||
applyOutputFromCommand: (command: Command) => void;
|
applyOutputFromCommand: (command: Command) => void;
|
||||||
resolveTimeoutFromOptions: (options: { timeout?: string | number }) => number | undefined;
|
resolveTimeoutFromOptions: (options: { timeout?: string | number }) => number | undefined;
|
||||||
resolveQuoteDepthFromOptions: (options: { quoteDepth?: string | number }) => number | undefined;
|
resolveQuoteDepthFromOptions: (options: { quoteDepth?: string | number }) => number | undefined;
|
||||||
resolveCredentialsFromOptions: (opts: CredentialsOptions) => ReturnType<typeof resolveCredentials>;
|
resolveRelayBaseUrlFromOptions: (opts: RelayOptions) => string | undefined;
|
||||||
loadMedia: (opts: { media: string[]; alts: string[] }) => MediaSpec[];
|
loadMedia: (opts: { media: string[]; alts: string[] }) => MediaSpec[];
|
||||||
printTweets: (tweets: TweetData[], opts?: { json?: boolean; emptyMessage?: string; showSeparator?: boolean }) => void;
|
printTweets: (tweets: TweetData[], opts?: { json?: boolean; emptyMessage?: string; showSeparator?: boolean }) => void;
|
||||||
|
printTweetsResult: (
|
||||||
|
result: {
|
||||||
|
tweets?: TweetData[];
|
||||||
|
nextCursor?: string;
|
||||||
|
},
|
||||||
|
opts: {
|
||||||
|
json: boolean;
|
||||||
|
usePagination: boolean;
|
||||||
|
emptyMessage: string;
|
||||||
|
},
|
||||||
|
) => void;
|
||||||
extractTweetId: (tweetIdOrUrl: string) => string;
|
extractTweetId: (tweetIdOrUrl: string) => string;
|
||||||
};
|
};
|
||||||
|
|
||||||
const COOKIE_SOURCES: CookieSource[] = ['safari', 'chrome', 'firefox'];
|
|
||||||
|
|
||||||
function parseCookieSource(value: string): CookieSource {
|
|
||||||
const normalized = value.trim().toLowerCase();
|
|
||||||
if (normalized === 'safari' || normalized === 'chrome' || normalized === 'firefox') {
|
|
||||||
return normalized;
|
|
||||||
}
|
|
||||||
throw new Error(`Invalid --cookie-source "${value}". Allowed: safari, chrome, firefox.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
export const collectCookieSource = (value: string, previous: CookieSource[] = []): CookieSource[] => {
|
|
||||||
previous.push(parseCookieSource(value));
|
|
||||||
return previous;
|
|
||||||
};
|
|
||||||
|
|
||||||
function resolveCookieSourceOrder(input: unknown): CookieSource[] | undefined {
|
|
||||||
if (typeof input === 'string') {
|
|
||||||
return [parseCookieSource(input)];
|
|
||||||
}
|
|
||||||
if (Array.isArray(input)) {
|
|
||||||
const result: CookieSource[] = [];
|
|
||||||
for (const entry of input) {
|
|
||||||
if (typeof entry !== 'string') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
result.push(parseCookieSource(entry));
|
|
||||||
}
|
|
||||||
return result.length > 0 ? result : undefined;
|
|
||||||
}
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveTimeoutMs(...values: Array<string | number | undefined | null>): number | undefined {
|
function resolveTimeoutMs(...values: Array<string | number | undefined | null>): number | undefined {
|
||||||
for (const value of values) {
|
for (const value of values) {
|
||||||
if (value === undefined || value === null || value === '') {
|
if (value === undefined || value === null || value === '') {
|
||||||
@@ -158,13 +134,8 @@ function loadConfig(warn: (message: string) => void): BirdConfig {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
type CredentialsOptions = {
|
type RelayOptions = {
|
||||||
authToken?: string;
|
relayBaseUrl?: string;
|
||||||
ct0?: string;
|
|
||||||
chromeProfile?: string;
|
|
||||||
firefoxProfile?: string;
|
|
||||||
cookieSource?: CookieSource[];
|
|
||||||
cookieTimeout?: string | number;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEnv = process.env): CliContext {
|
export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEnv = process.env): CliContext {
|
||||||
@@ -256,26 +227,12 @@ export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEn
|
|||||||
return resolveTimeoutMs(options.timeout, config.timeoutMs, env.BIRD_TIMEOUT_MS);
|
return resolveTimeoutMs(options.timeout, config.timeoutMs, env.BIRD_TIMEOUT_MS);
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveCookieTimeoutFromOptions(options: { cookieTimeout?: string | number }): number | undefined {
|
|
||||||
return resolveTimeoutMs(options.cookieTimeout, config.cookieTimeoutMs, env.BIRD_COOKIE_TIMEOUT_MS);
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveQuoteDepthFromOptions(options: { quoteDepth?: string | number }): number | undefined {
|
function resolveQuoteDepthFromOptions(options: { quoteDepth?: string | number }): number | undefined {
|
||||||
return resolveQuoteDepth(options.quoteDepth, config.quoteDepth, env.BIRD_QUOTE_DEPTH);
|
return resolveQuoteDepth(options.quoteDepth, config.quoteDepth, env.BIRD_QUOTE_DEPTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
function resolveCredentialsFromOptions(opts: CredentialsOptions): ReturnType<typeof resolveCredentials> {
|
function resolveRelayBaseUrlFromOptions(opts: RelayOptions): string | undefined {
|
||||||
const cookieSource = opts.cookieSource?.length
|
return opts.relayBaseUrl || config.relayBaseUrl || env.TWITTER_RELAY_BASE_URL;
|
||||||
? opts.cookieSource
|
|
||||||
: (resolveCookieSourceOrder(config.cookieSource) ?? COOKIE_SOURCES);
|
|
||||||
return resolveCredentials({
|
|
||||||
authToken: opts.authToken,
|
|
||||||
ct0: opts.ct0,
|
|
||||||
cookieSource,
|
|
||||||
chromeProfile: opts.chromeProfile || config.chromeProfile,
|
|
||||||
firefoxProfile: opts.firefoxProfile || config.firefoxProfile,
|
|
||||||
cookieTimeoutMs: resolveCookieTimeoutFromOptions(opts),
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function loadMedia(opts: { media: string[]; alts: string[] }): MediaSpec[] {
|
function loadMedia(opts: { media: string[]; alts: string[] }): MediaSpec[] {
|
||||||
@@ -317,19 +274,89 @@ export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEn
|
|||||||
console.log(opts.emptyMessage ?? 'No tweets found.');
|
console.log(opts.emptyMessage ?? 'No tweets found.');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
const useEmoji = output.emoji && !output.plain;
|
||||||
|
const articleLabel = useEmoji ? '📰' : 'Article:';
|
||||||
|
const mediaLabel = (type: 'photo' | 'video' | 'animated_gif'): string => {
|
||||||
|
if (useEmoji) {
|
||||||
|
return type === 'video' ? '🎬' : type === 'animated_gif' ? '🔄' : '🖼️';
|
||||||
|
}
|
||||||
|
return type === 'video' ? 'VIDEO:' : type === 'animated_gif' ? 'GIF:' : 'PHOTO:';
|
||||||
|
};
|
||||||
|
const quotePrefix = useEmoji ? { top: '┌─', mid: '│ ', bot: '└─' } : { top: '> ', mid: '> ', bot: '> ' };
|
||||||
|
|
||||||
for (const tweet of tweets) {
|
for (const tweet of tweets) {
|
||||||
console.log(`\n@${tweet.author.username} (${tweet.author.name}):`);
|
console.log(`\n@${tweet.author.username} (${tweet.author.name}):`);
|
||||||
console.log(tweet.text);
|
|
||||||
|
// Display tweet text, with article indicator if present
|
||||||
|
if (tweet.article) {
|
||||||
|
// Full body mode: text starts with article title (from extractArticleText)
|
||||||
|
// Preview mode: text is short tweet intro that doesn't start with title
|
||||||
|
const hasFullBody = tweet.text.startsWith(tweet.article.title);
|
||||||
|
if (hasFullBody) {
|
||||||
|
console.log(`${articleLabel} ${tweet.text}`);
|
||||||
|
} else {
|
||||||
|
console.log(`${articleLabel} ${tweet.article.title}`);
|
||||||
|
if (tweet.article.previewText) {
|
||||||
|
console.log(` ${tweet.article.previewText}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(tweet.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Display media attachments
|
||||||
|
if (tweet.media && tweet.media.length > 0) {
|
||||||
|
for (const m of tweet.media) {
|
||||||
|
console.log(`${mediaLabel(m.type)} ${m.url}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Display quoted tweet
|
||||||
|
if (tweet.quotedTweet) {
|
||||||
|
console.log(`${quotePrefix.top} QT @${tweet.quotedTweet.author.username}:`);
|
||||||
|
const qtText = tweet.quotedTweet.article
|
||||||
|
? `${articleLabel} ${tweet.quotedTweet.article.title}`
|
||||||
|
: tweet.quotedTweet.text;
|
||||||
|
// Indent and truncate quoted tweet text
|
||||||
|
const maxLen = 280;
|
||||||
|
const truncated = qtText.length > maxLen ? `${qtText.slice(0, maxLen)}...` : qtText;
|
||||||
|
for (const line of truncated.split('\n').slice(0, 4)) {
|
||||||
|
console.log(`${quotePrefix.mid}${line}`);
|
||||||
|
}
|
||||||
|
// Display quoted tweet media
|
||||||
|
if (tweet.quotedTweet.media && tweet.quotedTweet.media.length > 0) {
|
||||||
|
for (const m of tweet.quotedTweet.media) {
|
||||||
|
console.log(`${quotePrefix.mid}${mediaLabel(m.type)} ${m.url}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
`${quotePrefix.bot} https://x.com/${tweet.quotedTweet.author.username}/status/${tweet.quotedTweet.id}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (tweet.createdAt) {
|
if (tweet.createdAt) {
|
||||||
console.log(`${l('date')}${tweet.createdAt}`);
|
console.log(`${l('date')}${tweet.createdAt}`);
|
||||||
}
|
}
|
||||||
console.log(`${l('url')}https://x.com/${tweet.author.username}/status/${tweet.id}`);
|
const tweetUrl = `https://x.com/${tweet.author.username}/status/${tweet.id}`;
|
||||||
|
console.log(`${l('url')}${hyperlink(tweetUrl, tweetUrl, output)}`);
|
||||||
if (opts.showSeparator ?? true) {
|
if (opts.showSeparator ?? true) {
|
||||||
console.log('─'.repeat(50));
|
console.log('─'.repeat(50));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function printTweetsResult(
|
||||||
|
result: { tweets?: TweetData[]; nextCursor?: string },
|
||||||
|
opts: { json: boolean; usePagination: boolean; emptyMessage: string },
|
||||||
|
) {
|
||||||
|
const tweets = result.tweets ?? [];
|
||||||
|
if (opts.json && opts.usePagination) {
|
||||||
|
console.log(JSON.stringify({ tweets, nextCursor: result.nextCursor ?? null }, null, 2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
printTweets(tweets, { json: opts.json, emptyMessage: opts.emptyMessage });
|
||||||
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
isTty,
|
isTty,
|
||||||
getOutput: () => output,
|
getOutput: () => output,
|
||||||
@@ -340,9 +367,10 @@ export function createCliContext(normalizedArgs: string[], env: NodeJS.ProcessEn
|
|||||||
applyOutputFromCommand,
|
applyOutputFromCommand,
|
||||||
resolveTimeoutFromOptions,
|
resolveTimeoutFromOptions,
|
||||||
resolveQuoteDepthFromOptions,
|
resolveQuoteDepthFromOptions,
|
||||||
resolveCredentialsFromOptions,
|
resolveRelayBaseUrlFromOptions,
|
||||||
loadMedia,
|
loadMedia,
|
||||||
printTweets,
|
printTweets,
|
||||||
|
printTweetsResult,
|
||||||
extractTweetId,
|
extractTweetId,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-23
@@ -1,4 +1,5 @@
|
|||||||
import type { Command } from 'commander';
|
import type { Command } from 'commander';
|
||||||
|
import { parsePositiveIntFlag } from '../cli/pagination.js';
|
||||||
import type { CliContext } from '../cli/shared.js';
|
import type { CliContext } from '../cli/shared.js';
|
||||||
import { extractBookmarkFolderId } from '../lib/extract-bookmark-folder-id.js';
|
import { extractBookmarkFolderId } from '../lib/extract-bookmark-folder-id.js';
|
||||||
import { TwitterClient } from '../lib/twitter-client.js';
|
import { TwitterClient } from '../lib/twitter-client.js';
|
||||||
@@ -27,20 +28,15 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
|||||||
const opts = program.opts();
|
const opts = program.opts();
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||||
const maxPages = cmdOpts.maxPages ? Number.parseInt(cmdOpts.maxPages, 10) : undefined;
|
const maxPagesParsed = parsePositiveIntFlag(cmdOpts.maxPages, '--max-pages');
|
||||||
|
if (!maxPagesParsed.ok) {
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
console.error(`${ctx.p('err')}${maxPagesParsed.error}`);
|
||||||
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
const maxPages = maxPagesParsed.value;
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
const usePagination = Boolean(cmdOpts.all || cmdOpts.cursor);
|
||||||
if (maxPages !== undefined && !usePagination) {
|
if (maxPages !== undefined && !usePagination) {
|
||||||
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
|
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@@ -49,12 +45,8 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
|||||||
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
|
||||||
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs });
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||||
const folderId = cmdOpts.folderId ? extractBookmarkFolderId(cmdOpts.folderId) : null;
|
const folderId = cmdOpts.folderId ? extractBookmarkFolderId(cmdOpts.folderId) : null;
|
||||||
if (cmdOpts.folderId && !folderId) {
|
if (cmdOpts.folderId && !folderId) {
|
||||||
console.error(`${ctx.p('err')}Invalid --folder-id. Expected numeric ID or https://x.com/i/bookmarks/<id>.`);
|
console.error(`${ctx.p('err')}Invalid --folder-id. Expected numeric ID or https://x.com/i/bookmarks/<id>.`);
|
||||||
@@ -71,14 +63,10 @@ export function registerBookmarksCommand(program: Command, ctx: CliContext): voi
|
|||||||
? await client.getAllBookmarks(paginationOptions)
|
? await client.getAllBookmarks(paginationOptions)
|
||||||
: await client.getBookmarks(count, timelineOptions);
|
: await client.getBookmarks(count, timelineOptions);
|
||||||
|
|
||||||
if (result.success && result.tweets) {
|
if (result.success) {
|
||||||
const emptyMessage = folderId ? 'No bookmarks found in folder.' : 'No bookmarks found.';
|
const emptyMessage = folderId ? 'No bookmarks found in folder.' : 'No bookmarks found.';
|
||||||
const isJson = cmdOpts.json || cmdOpts.jsonFull;
|
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||||
if (isJson && usePagination) {
|
ctx.printTweetsResult(result, { json: isJson, usePagination, emptyMessage });
|
||||||
console.log(JSON.stringify({ tweets: result.tweets, nextCursor: result.nextCursor ?? null }, null, 2));
|
|
||||||
} else {
|
|
||||||
ctx.printTweets(result.tweets, { json: isJson, emptyMessage });
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
console.error(`${ctx.p('err')}Failed to fetch bookmarks: ${result.error}`);
|
console.error(`${ctx.p('err')}Failed to fetch bookmarks: ${result.error}`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
|||||||
+21
-33
@@ -1,47 +1,35 @@
|
|||||||
import type { Command } from 'commander';
|
import type { Command } from 'commander';
|
||||||
import type { CliContext } from '../cli/shared.js';
|
import type { CliContext } from '../cli/shared.js';
|
||||||
|
import { TwitterClient } from '../lib/twitter-client.js';
|
||||||
|
|
||||||
export function registerCheckCommand(program: Command, ctx: CliContext): void {
|
export function registerCheckCommand(program: Command, ctx: CliContext): void {
|
||||||
program
|
program
|
||||||
.command('check')
|
.command('check')
|
||||||
.description('Check credential availability')
|
.description('Check twitter safe relay availability')
|
||||||
.action(async () => {
|
.action(async () => {
|
||||||
const opts = program.opts();
|
const opts = program.opts();
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
console.log(`${ctx.p('info')}Credential check`);
|
console.log(`${ctx.p('info')}Relay check`);
|
||||||
console.log('─'.repeat(40));
|
console.log('-'.repeat(40));
|
||||||
|
|
||||||
if (cookies.authToken) {
|
if (!relayBaseUrl) {
|
||||||
console.log(`${ctx.p('ok')}auth_token: ${cookies.authToken.slice(0, 10)}...`);
|
console.log(`${ctx.p('err')}TWITTER_RELAY_BASE_URL: not set`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`${ctx.p('ok')}relay: ${relayBaseUrl}`);
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||||
|
const result = await client.getCurrentUser();
|
||||||
|
|
||||||
|
if (result.success && result.user) {
|
||||||
|
console.log(`${ctx.l('user')}@${result.user.username} (${result.user.name})`);
|
||||||
|
console.log(`${ctx.l('userId')}${result.user.id}`);
|
||||||
|
console.log(`\n${ctx.p('ok')}Ready to use twitter safe relay.`);
|
||||||
} else {
|
} else {
|
||||||
console.log(`${ctx.p('err')}auth_token: not found`);
|
console.log(`${ctx.p('err')}Relay check failed: ${result.error ?? 'Unknown error'}`);
|
||||||
}
|
|
||||||
|
|
||||||
if (cookies.ct0) {
|
|
||||||
console.log(`${ctx.p('ok')}ct0: ${cookies.ct0.slice(0, 10)}...`);
|
|
||||||
} else {
|
|
||||||
console.log(`${ctx.p('err')}ct0: not found`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cookies.source) {
|
|
||||||
console.log(`${ctx.l('source')}${cookies.source}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (warnings.length > 0) {
|
|
||||||
console.log(`\n${ctx.p('warn')}Warnings:`);
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.log(` - ${warning}`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cookies.authToken && cookies.ct0) {
|
|
||||||
console.log(`\n${ctx.p('ok')}Ready to tweet!`);
|
|
||||||
} else {
|
|
||||||
console.log(`\n${ctx.p('err')}Missing credentials. Options:`);
|
|
||||||
console.log(' 1. Login to x.com in Safari/Chrome/Firefox');
|
|
||||||
console.log(' 2. Set AUTH_TOKEN and CT0 environment variables');
|
|
||||||
console.log(' 3. Use --auth-token and --ct0 flags');
|
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
import type { Command } from 'commander';
|
||||||
|
import type { CliContext } from '../cli/shared.js';
|
||||||
|
import { TwitterClient } from '../lib/twitter-client.js';
|
||||||
|
|
||||||
|
export function registerHomeCommand(program: Command, ctx: CliContext): void {
|
||||||
|
program
|
||||||
|
.command('home')
|
||||||
|
.description('Get your home timeline ("For You" feed)')
|
||||||
|
.option('-n, --count <number>', 'Number of tweets to fetch', '20')
|
||||||
|
.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 }) => {
|
||||||
|
const opts = program.opts();
|
||||||
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(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 includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
|
|
||||||
|
const result = cmdOpts.following
|
||||||
|
? await client.getHomeLatestTimeline(count, { includeRaw })
|
||||||
|
: await client.getHomeTimeline(count, { includeRaw });
|
||||||
|
|
||||||
|
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 });
|
||||||
|
} else {
|
||||||
|
console.error(`${ctx.p('err')}Failed to fetch home timeline: ${result.error}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
+61
-43
@@ -2,8 +2,10 @@
|
|||||||
// ABOUTME: Supports listing owned lists, memberships, and list timelines.
|
// ABOUTME: Supports listing owned lists, memberships, and list timelines.
|
||||||
|
|
||||||
import type { Command } from 'commander';
|
import type { Command } from 'commander';
|
||||||
|
import { parsePaginationFlags } from '../cli/pagination.js';
|
||||||
import type { CliContext } from '../cli/shared.js';
|
import type { CliContext } from '../cli/shared.js';
|
||||||
import { extractListId } from '../lib/extract-list-id.js';
|
import { extractListId } from '../lib/extract-list-id.js';
|
||||||
|
import { hyperlink } from '../lib/output.js';
|
||||||
import type { TwitterList } from '../lib/twitter-client.js';
|
import type { TwitterList } from '../lib/twitter-client.js';
|
||||||
import { TwitterClient } from '../lib/twitter-client.js';
|
import { TwitterClient } from '../lib/twitter-client.js';
|
||||||
|
|
||||||
@@ -23,7 +25,8 @@ function printLists(lists: TwitterList[], ctx: CliContext): void {
|
|||||||
if (list.owner) {
|
if (list.owner) {
|
||||||
console.log(` ${ctx.colors.muted(`Owner: @${list.owner.username}`)}`);
|
console.log(` ${ctx.colors.muted(`Owner: @${list.owner.username}`)}`);
|
||||||
}
|
}
|
||||||
console.log(` ${ctx.colors.accent(`https://x.com/i/lists/${list.id}`)}`);
|
const listUrl = `https://x.com/i/lists/${list.id}`;
|
||||||
|
console.log(` ${ctx.colors.accent(hyperlink(listUrl, listUrl, ctx.getOutput()))}`);
|
||||||
console.log('──────────────────────────────────────────────────');
|
console.log('──────────────────────────────────────────────────');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -39,19 +42,9 @@ export function registerListsCommand(program: Command, ctx: CliContext): void {
|
|||||||
const opts = program.opts();
|
const opts = program.opts();
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
const count = Number.parseInt(cmdOpts.count || '100', 10);
|
const count = Number.parseInt(cmdOpts.count || '100', 10);
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||||
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs });
|
|
||||||
|
|
||||||
const result = cmdOpts.memberOf ? await client.getListMemberships(count) : await client.getOwnedLists(count);
|
const result = cmdOpts.memberOf ? await client.getListMemberships(count) : await client.getOwnedLists(count);
|
||||||
|
|
||||||
@@ -76,42 +69,67 @@ export function registerListsCommand(program: Command, ctx: CliContext): void {
|
|||||||
.command('list-timeline <list-id-or-url>')
|
.command('list-timeline <list-id-or-url>')
|
||||||
.description('Get tweets from a list timeline')
|
.description('Get tweets from a list timeline')
|
||||||
.option('-n, --count <number>', 'Number of tweets to fetch', '20')
|
.option('-n, --count <number>', 'Number of tweets to fetch', '20')
|
||||||
|
.option('--all', 'Fetch all tweets from list (paged). WARNING: your account might get banned using this flag')
|
||||||
|
.option('--max-pages <number>', 'Fetch N pages (implies --all)')
|
||||||
|
.option('--cursor <string>', 'Resume pagination from a cursor')
|
||||||
.option('--json', 'Output as JSON')
|
.option('--json', 'Output as JSON')
|
||||||
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
||||||
.action(async (listIdOrUrl: string, cmdOpts: { count?: string; json?: boolean; jsonFull?: boolean }) => {
|
.action(
|
||||||
const opts = program.opts();
|
async (
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
listIdOrUrl: string,
|
||||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
cmdOpts: {
|
||||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
count?: string;
|
||||||
|
json?: boolean;
|
||||||
|
jsonFull?: boolean;
|
||||||
|
all?: boolean;
|
||||||
|
maxPages?: string;
|
||||||
|
cursor?: string;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const opts = program.opts();
|
||||||
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||||
|
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
||||||
|
|
||||||
const listId = extractListId(listIdOrUrl);
|
const pagination = parsePaginationFlags(cmdOpts, { maxPagesImpliesPagination: true });
|
||||||
if (!listId) {
|
if (!pagination.ok) {
|
||||||
console.error(`${ctx.p('err')}Invalid list ID or URL. Expected numeric ID or https://x.com/i/lists/<id>.`);
|
console.error(`${ctx.p('err')}${pagination.error}`);
|
||||||
process.exit(2);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const listId = extractListId(listIdOrUrl);
|
||||||
|
if (!listId) {
|
||||||
|
console.error(`${ctx.p('err')}Invalid list ID or URL. Expected numeric ID or https://x.com/i/lists/<id>.`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
for (const warning of warnings) {
|
const usePagination = pagination.usePagination;
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
if (!usePagination && (!Number.isFinite(count) || count <= 0)) {
|
||||||
}
|
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
process.exit(1);
|
const timelineOptions = { includeRaw };
|
||||||
}
|
const paginationOptions = { includeRaw, maxPages: pagination.maxPages, cursor: pagination.cursor };
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
const result = usePagination
|
||||||
const result = await client.getListTimeline(listId, count, { includeRaw: cmdOpts.jsonFull });
|
? await client.getAllListTimeline(listId, paginationOptions)
|
||||||
|
: await client.getListTimeline(listId, count, timelineOptions);
|
||||||
|
|
||||||
if (result.success && result.tweets) {
|
if (result.success) {
|
||||||
ctx.printTweets(result.tweets, {
|
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||||
json: cmdOpts.json || cmdOpts.jsonFull,
|
ctx.printTweetsResult(result, {
|
||||||
emptyMessage: 'No tweets found in this list.',
|
json: isJson,
|
||||||
});
|
usePagination,
|
||||||
} else {
|
emptyMessage: 'No tweets found in this list.',
|
||||||
console.error(`${ctx.p('err')}Failed to fetch list timeline: ${result.error}`);
|
});
|
||||||
process.exit(1);
|
} else {
|
||||||
}
|
console.error(`${ctx.p('err')}Failed to fetch list timeline: ${result.error}`);
|
||||||
});
|
process.exit(1);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,162 @@
|
|||||||
|
import type { Command } from 'commander';
|
||||||
|
import type { CliContext } from '../cli/shared.js';
|
||||||
|
import { TwitterClient } from '../lib/twitter-client.js';
|
||||||
|
import type { ExploreTab, NewsItem } from '../lib/twitter-client-news.js';
|
||||||
|
|
||||||
|
function formatPostCount(count: number): string {
|
||||||
|
if (count >= 1_000_000) {
|
||||||
|
return `${(count / 1_000_000).toFixed(1)}M`;
|
||||||
|
}
|
||||||
|
if (count >= 1_000) {
|
||||||
|
return `${(count / 1_000).toFixed(1)}K`;
|
||||||
|
}
|
||||||
|
return String(count);
|
||||||
|
}
|
||||||
|
|
||||||
|
function printNewsItems(
|
||||||
|
items: NewsItem[],
|
||||||
|
ctx: CliContext,
|
||||||
|
opts: { json?: boolean; emptyMessage?: string; tweetLimit?: number } = {},
|
||||||
|
): void {
|
||||||
|
if (opts.json) {
|
||||||
|
console.log(JSON.stringify(items, null, 2));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (items.length === 0) {
|
||||||
|
console.log(opts.emptyMessage ?? 'No news items found.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
const categoryLabel = item.category ? `[${item.category}]` : '';
|
||||||
|
console.log(`\n${ctx.colors.accent(categoryLabel)} ${ctx.colors.command(item.headline)}`);
|
||||||
|
|
||||||
|
if (item.description) {
|
||||||
|
console.log(` ${ctx.colors.muted(item.description)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const meta: string[] = [];
|
||||||
|
if (item.timeAgo) {
|
||||||
|
meta.push(item.timeAgo);
|
||||||
|
}
|
||||||
|
if (item.postCount) {
|
||||||
|
meta.push(`${formatPostCount(item.postCount)} posts`);
|
||||||
|
}
|
||||||
|
if (meta.length > 0) {
|
||||||
|
console.log(` ${ctx.colors.muted(meta.join(' | '))}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (item.url) {
|
||||||
|
console.log(` ${ctx.l('url')}${item.url}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Print related tweets if available
|
||||||
|
if (item.tweets && item.tweets.length > 0) {
|
||||||
|
console.log(` ${ctx.colors.section('Related tweets:')}`);
|
||||||
|
const tweetLimit = opts.tweetLimit ?? item.tweets.length;
|
||||||
|
for (const tweet of item.tweets.slice(0, tweetLimit)) {
|
||||||
|
console.log(
|
||||||
|
` @${tweet.author.username}: ${tweet.text.slice(0, 100)}${tweet.text.length > 100 ? '...' : ''}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(ctx.colors.muted('─'.repeat(50)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function registerNewsCommand(program: Command, ctx: CliContext): void {
|
||||||
|
program
|
||||||
|
.command('news')
|
||||||
|
.alias('trending')
|
||||||
|
.description('Fetch AI-curated news and trending topics from Explore tabs')
|
||||||
|
.option('-n, --count <number>', 'Number of items to fetch', '10')
|
||||||
|
.option('--ai-only', 'Show only AI-curated news items')
|
||||||
|
.option('--with-tweets', 'Also fetch related tweets for each news item')
|
||||||
|
.option('--tweets-per-item <number>', 'Number of tweets to fetch per news item (default: 5)', '5')
|
||||||
|
.option('--for-you', 'Fetch only from For You tab')
|
||||||
|
.option('--news-only', 'Fetch only from News tab')
|
||||||
|
.option('--sports', 'Fetch only from Sports tab')
|
||||||
|
.option('--entertainment', 'Fetch only from Entertainment tab')
|
||||||
|
.option('--trending-only', 'Fetch only from Trending tab')
|
||||||
|
.option('--json', 'Output as JSON')
|
||||||
|
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
||||||
|
.action(
|
||||||
|
async (cmdOpts: {
|
||||||
|
count?: string;
|
||||||
|
aiOnly?: boolean;
|
||||||
|
withTweets?: boolean;
|
||||||
|
tweetsPerItem?: string;
|
||||||
|
forYou?: boolean;
|
||||||
|
newsOnly?: boolean;
|
||||||
|
sports?: boolean;
|
||||||
|
entertainment?: boolean;
|
||||||
|
trendingOnly?: boolean;
|
||||||
|
json?: boolean;
|
||||||
|
jsonFull?: boolean;
|
||||||
|
}) => {
|
||||||
|
const opts = program.opts();
|
||||||
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||||
|
const count = Number.parseInt(cmdOpts.count || '10', 10);
|
||||||
|
const tweetsPerItem = Number.parseInt(cmdOpts.tweetsPerItem || '5', 10);
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
|
if (Number.isNaN(count) || count < 1) {
|
||||||
|
console.error(`${ctx.p('err')}--count must be a positive number`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Number.isNaN(tweetsPerItem) || tweetsPerItem < 1) {
|
||||||
|
console.error(`${ctx.p('err')}--tweets-per-item must be a positive number`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine which tabs to fetch from
|
||||||
|
const tabs: ExploreTab[] = [];
|
||||||
|
if (cmdOpts.forYou) {
|
||||||
|
tabs.push('forYou');
|
||||||
|
}
|
||||||
|
if (cmdOpts.newsOnly) {
|
||||||
|
tabs.push('news');
|
||||||
|
}
|
||||||
|
if (cmdOpts.sports) {
|
||||||
|
tabs.push('sports');
|
||||||
|
}
|
||||||
|
if (cmdOpts.entertainment) {
|
||||||
|
tabs.push('entertainment');
|
||||||
|
}
|
||||||
|
if (cmdOpts.trendingOnly) {
|
||||||
|
tabs.push('trending');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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 includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
|
const withTweets = cmdOpts.withTweets ?? false;
|
||||||
|
const aiOnly = cmdOpts.aiOnly ?? false;
|
||||||
|
|
||||||
|
const result = await client.getNews(count, {
|
||||||
|
includeRaw,
|
||||||
|
withTweets,
|
||||||
|
tweetsPerItem,
|
||||||
|
aiOnly,
|
||||||
|
tabs: tabsToFetch,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
printNewsItems(result.items, ctx, {
|
||||||
|
json: cmdOpts.json || cmdOpts.jsonFull,
|
||||||
|
emptyMessage: 'No news items found.',
|
||||||
|
tweetLimit: withTweets ? tweetsPerItem : undefined,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
console.error(`${ctx.p('err')}Failed to fetch news: ${result.error}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
+4
-34
@@ -40,23 +40,8 @@ export function registerPostCommands(program: Command, ctx: CliContext): void {
|
|||||||
console.error(`${ctx.p('err')}${error instanceof Error ? error.message : String(error)}`);
|
console.error(`${ctx.p('err')}${error instanceof Error ? error.message : String(error)}`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cookies.source) {
|
|
||||||
console.error(`${ctx.l('source')}${cookies.source}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
|
||||||
const mediaIds = await uploadMediaOrExit(client, media, ctx);
|
const mediaIds = await uploadMediaOrExit(client, media, ctx);
|
||||||
const result = await client.tweet(text, mediaIds);
|
const result = await client.tweet(text, mediaIds);
|
||||||
|
|
||||||
@@ -86,25 +71,10 @@ export function registerPostCommands(program: Command, ctx: CliContext): void {
|
|||||||
process.exit(1);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
|
||||||
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cookies.source) {
|
|
||||||
console.error(`${ctx.l('source')}${cookies.source}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
console.error(`${ctx.p('info')}Replying to tweet: ${tweetId}`);
|
console.error(`${ctx.p('info')}Replying to tweet: ${tweetId}`);
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
const mediaIds = await uploadMediaOrExit(client, media, ctx);
|
const mediaIds = await uploadMediaOrExit(client, media, ctx);
|
||||||
const result = await client.reply(text, tweetId, mediaIds);
|
const result = await client.reply(text, tweetId, mediaIds);
|
||||||
|
|
||||||
|
|||||||
+116
-66
@@ -1,4 +1,5 @@
|
|||||||
import type { Command } from 'commander';
|
import type { Command } from 'commander';
|
||||||
|
import { parsePaginationFlags } from '../cli/pagination.js';
|
||||||
import type { CliContext } from '../cli/shared.js';
|
import type { CliContext } from '../cli/shared.js';
|
||||||
import { formatStatsLine } from '../lib/output.js';
|
import { formatStatsLine } from '../lib/output.js';
|
||||||
import { TwitterClient } from '../lib/twitter-client.js';
|
import { TwitterClient } from '../lib/twitter-client.js';
|
||||||
@@ -16,19 +17,9 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
|||||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||||
|
|
||||||
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
|
||||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
const result = await client.getTweet(tweetId, { includeRaw });
|
const result = await client.getTweet(tweetId, { includeRaw });
|
||||||
|
|
||||||
@@ -36,11 +27,7 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
|||||||
if (cmdOpts.json || cmdOpts.jsonFull) {
|
if (cmdOpts.json || cmdOpts.jsonFull) {
|
||||||
console.log(JSON.stringify(result.tweet, null, 2));
|
console.log(JSON.stringify(result.tweet, null, 2));
|
||||||
} else {
|
} else {
|
||||||
console.log(`@${result.tweet.author.username} (${result.tweet.author.name}):`);
|
ctx.printTweets([result.tweet], { showSeparator: false });
|
||||||
console.log(result.tweet.text);
|
|
||||||
if (result.tweet.createdAt) {
|
|
||||||
console.log(`\n${ctx.l('date')}${result.tweet.createdAt}`);
|
|
||||||
}
|
|
||||||
console.log(formatStatsLine(result.tweet, ctx.getOutput()));
|
console.log(formatStatsLine(result.tweet, ctx.getOutput()));
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -53,72 +40,135 @@ export function registerReadCommands(program: Command, ctx: CliContext): void {
|
|||||||
.command('replies')
|
.command('replies')
|
||||||
.description('List replies to a tweet (by ID or URL)')
|
.description('List replies to a tweet (by ID or URL)')
|
||||||
.argument('<tweet-id-or-url>', 'Tweet ID or URL')
|
.argument('<tweet-id-or-url>', 'Tweet ID or URL')
|
||||||
|
.option('--all', 'Fetch all replies (paged)')
|
||||||
|
.option('--max-pages <number>', 'Fetch N pages (implies pagination)')
|
||||||
|
.option('--delay <ms>', 'Delay in ms between page fetches', '1000')
|
||||||
|
.option('--cursor <string>', 'Resume pagination from a cursor')
|
||||||
.option('--json', 'Output as JSON')
|
.option('--json', 'Output as JSON')
|
||||||
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
||||||
.action(async (tweetIdOrUrl: string, cmdOpts: { json?: boolean; jsonFull?: boolean }) => {
|
.action(
|
||||||
const opts = program.opts();
|
async (
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
tweetIdOrUrl: string,
|
||||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
cmdOpts: {
|
||||||
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
all?: boolean;
|
||||||
|
maxPages?: string;
|
||||||
|
delay?: string;
|
||||||
|
cursor?: string;
|
||||||
|
json?: boolean;
|
||||||
|
jsonFull?: boolean;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const opts = program.opts();
|
||||||
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||||
|
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
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);
|
||||||
|
|
||||||
for (const warning of warnings) {
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
const result = pagination.usePagination
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
? await client.getRepliesPaged(tweetId, {
|
||||||
process.exit(1);
|
includeRaw,
|
||||||
}
|
maxPages: pagination.maxPages,
|
||||||
|
cursor: pagination.cursor,
|
||||||
|
pageDelayMs: pagination.pageDelayMs,
|
||||||
|
})
|
||||||
|
: await client.getReplies(tweetId, { includeRaw });
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
if (result.tweets) {
|
||||||
const result = await client.getReplies(tweetId, { includeRaw });
|
ctx.printTweetsResult(result, {
|
||||||
|
json: isJson,
|
||||||
|
usePagination: pagination.usePagination,
|
||||||
|
emptyMessage: 'No replies found.',
|
||||||
|
});
|
||||||
|
|
||||||
if (result.success && result.tweets) {
|
// Show pagination hint if there's more
|
||||||
ctx.printTweets(result.tweets, { json: cmdOpts.json || cmdOpts.jsonFull, emptyMessage: 'No replies found.' });
|
if (result.nextCursor && !isJson) {
|
||||||
} else {
|
console.error(`${ctx.p('info')}More replies available. Use --cursor "${result.nextCursor}" to continue.`);
|
||||||
console.error(`${ctx.p('err')}Failed to fetch replies: ${result.error}`);
|
}
|
||||||
process.exit(1);
|
}
|
||||||
}
|
|
||||||
});
|
if (!result.success) {
|
||||||
|
console.error(`${ctx.p('err')}Failed to fetch replies: ${result.error}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('thread')
|
.command('thread')
|
||||||
.description('Show the full conversation thread containing the tweet')
|
.description('Show the full conversation thread containing the tweet')
|
||||||
.argument('<tweet-id-or-url>', 'Tweet ID or URL')
|
.argument('<tweet-id-or-url>', 'Tweet ID or URL')
|
||||||
|
.option('--all', 'Fetch all thread tweets (paged)')
|
||||||
|
.option('--max-pages <number>', 'Fetch N pages (implies pagination)')
|
||||||
|
.option('--delay <ms>', 'Delay in ms between page fetches', '1000')
|
||||||
|
.option('--cursor <string>', 'Resume pagination from a cursor')
|
||||||
.option('--json', 'Output as JSON')
|
.option('--json', 'Output as JSON')
|
||||||
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
||||||
.action(async (tweetIdOrUrl: string, cmdOpts: { json?: boolean; jsonFull?: boolean }) => {
|
.action(
|
||||||
const opts = program.opts();
|
async (
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
tweetIdOrUrl: string,
|
||||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
cmdOpts: {
|
||||||
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
all?: boolean;
|
||||||
|
maxPages?: string;
|
||||||
|
delay?: string;
|
||||||
|
cursor?: string;
|
||||||
|
json?: boolean;
|
||||||
|
jsonFull?: boolean;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const opts = program.opts();
|
||||||
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||||
|
const tweetId = ctx.extractTweetId(tweetIdOrUrl);
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
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);
|
||||||
|
|
||||||
for (const warning of warnings) {
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
const result = pagination.usePagination
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
? await client.getThreadPaged(tweetId, {
|
||||||
process.exit(1);
|
includeRaw,
|
||||||
}
|
maxPages: pagination.maxPages,
|
||||||
|
cursor: pagination.cursor,
|
||||||
|
pageDelayMs: pagination.pageDelayMs,
|
||||||
|
})
|
||||||
|
: await client.getThread(tweetId, { includeRaw });
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
if (result.tweets) {
|
||||||
const result = await client.getThread(tweetId, { includeRaw });
|
ctx.printTweetsResult(result, {
|
||||||
|
json: isJson,
|
||||||
|
usePagination: pagination.usePagination,
|
||||||
|
emptyMessage: 'No thread tweets found.',
|
||||||
|
});
|
||||||
|
|
||||||
if (result.success && result.tweets) {
|
// Show pagination hint if there's more
|
||||||
ctx.printTweets(result.tweets, {
|
if (result.nextCursor && !isJson) {
|
||||||
json: cmdOpts.json || cmdOpts.jsonFull,
|
console.error(
|
||||||
emptyMessage: 'No thread tweets found.',
|
`${ctx.p('info')}More thread tweets available. Use --cursor "${result.nextCursor}" to continue.`,
|
||||||
});
|
);
|
||||||
} else {
|
}
|
||||||
console.error(`${ctx.p('err')}Failed to fetch thread: ${result.error}`);
|
}
|
||||||
process.exit(1);
|
|
||||||
}
|
if (!result.success) {
|
||||||
});
|
console.error(`${ctx.p('err')}Failed to fetch thread: ${result.error}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+61
-39
@@ -9,36 +9,65 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
|||||||
.description('Search for tweets')
|
.description('Search for tweets')
|
||||||
.argument('<query>', 'Search query (e.g., "@clawdbot" or "from:clawdbot")')
|
.argument('<query>', 'Search query (e.g., "@clawdbot" or "from:clawdbot")')
|
||||||
.option('-n, --count <number>', 'Number of tweets to fetch', '10')
|
.option('-n, --count <number>', 'Number of tweets to fetch', '10')
|
||||||
|
.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')
|
||||||
.option('--json', 'Output as JSON')
|
.option('--json', 'Output as JSON')
|
||||||
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
||||||
.action(async (query: string, cmdOpts: { count?: string; json?: boolean; jsonFull?: boolean }) => {
|
.action(
|
||||||
const opts = program.opts();
|
async (
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
query: string,
|
||||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
cmdOpts: {
|
||||||
const count = Number.parseInt(cmdOpts.count || '10', 10);
|
count?: string;
|
||||||
|
all?: boolean;
|
||||||
|
maxPages?: string;
|
||||||
|
cursor?: string;
|
||||||
|
json?: boolean;
|
||||||
|
jsonFull?: boolean;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const opts = program.opts();
|
||||||
|
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 { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||||
|
if (maxPages !== undefined && !usePagination) {
|
||||||
|
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (!usePagination && (!Number.isFinite(count) || count <= 0)) {
|
||||||
|
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||||
|
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
for (const warning of warnings) {
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
}
|
const searchOptions = { includeRaw };
|
||||||
|
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||||
|
const result = usePagination
|
||||||
|
? await client.getAllSearchResults(query, paginationOptions)
|
||||||
|
: await client.search(query, count, searchOptions);
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
if (result.success) {
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||||
process.exit(1);
|
ctx.printTweetsResult(result, {
|
||||||
}
|
json: isJson,
|
||||||
|
usePagination: Boolean(usePagination),
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
emptyMessage: 'No tweets found.',
|
||||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
});
|
||||||
const result = await client.search(query, count, { includeRaw });
|
} else {
|
||||||
|
console.error(`${ctx.p('err')}Search failed: ${result.error}`);
|
||||||
if (result.success && result.tweets) {
|
process.exit(1);
|
||||||
ctx.printTweets(result.tweets, { json: cmdOpts.json || cmdOpts.jsonFull, emptyMessage: 'No tweets found.' });
|
}
|
||||||
} else {
|
},
|
||||||
console.error(`${ctx.p('err')}Search failed: ${result.error}`);
|
);
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('mentions')
|
.command('mentions')
|
||||||
@@ -60,19 +89,9 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
|||||||
}
|
}
|
||||||
|
|
||||||
let query: string | null = fromUserOpt.query;
|
let query: string | null = fromUserOpt.query;
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
|
||||||
|
|
||||||
if (!query) {
|
if (!query) {
|
||||||
const who = await client.getCurrentUser();
|
const who = await client.getCurrentUser();
|
||||||
@@ -90,8 +109,11 @@ export function registerSearchCommands(program: Command, ctx: CliContext): void
|
|||||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
const result = await client.search(query, count, { includeRaw });
|
const result = await client.search(query, count, { includeRaw });
|
||||||
|
|
||||||
if (result.success && result.tweets) {
|
if (result.success) {
|
||||||
ctx.printTweets(result.tweets, { json: cmdOpts.json || cmdOpts.jsonFull, emptyMessage: 'No mentions found.' });
|
ctx.printTweets(result.tweets, {
|
||||||
|
json: cmdOpts.json || cmdOpts.jsonFull,
|
||||||
|
emptyMessage: 'No mentions found.',
|
||||||
|
});
|
||||||
} else {
|
} else {
|
||||||
console.error(`${ctx.p('err')}Failed to fetch mentions: ${result.error}`);
|
console.error(`${ctx.p('err')}Failed to fetch mentions: ${result.error}`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
|||||||
@@ -10,19 +10,9 @@ export function registerUnbookmarkCommand(program: Command, ctx: CliContext): vo
|
|||||||
.action(async (tweetIdOrUrls: string[]) => {
|
.action(async (tweetIdOrUrls: string[]) => {
|
||||||
const opts = program.opts();
|
const opts = program.opts();
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||||
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs });
|
|
||||||
let failures = 0;
|
let failures = 0;
|
||||||
|
|
||||||
for (const input of tweetIdOrUrls) {
|
for (const input of tweetIdOrUrls) {
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
import type { Command } from 'commander';
|
||||||
|
import { parseNonNegativeIntFlag, parsePositiveIntFlag } from '../cli/pagination.js';
|
||||||
|
import type { CliContext } from '../cli/shared.js';
|
||||||
|
import { normalizeHandle } from '../lib/normalize-handle.js';
|
||||||
|
import { TwitterClient } from '../lib/twitter-client.js';
|
||||||
|
|
||||||
|
export function registerUserTweetsCommand(program: Command, ctx: CliContext): void {
|
||||||
|
const formatExample = (cmd: string, desc: string): string =>
|
||||||
|
` ${ctx.colors.command(cmd)}\n ${ctx.colors.muted(desc)}`;
|
||||||
|
|
||||||
|
program
|
||||||
|
.command('user-tweets')
|
||||||
|
.description("Get tweets from a user's profile timeline")
|
||||||
|
.argument('<handle>', 'Username to fetch tweets from (e.g., @steipete or steipete)')
|
||||||
|
.option('-n, --count <number>', 'Number of tweets to fetch', '20')
|
||||||
|
.option('--max-pages <number>', 'Stop after N pages (max: 10)')
|
||||||
|
.option('--delay <ms>', 'Delay in ms between page fetches', '1000')
|
||||||
|
.option('--cursor <string>', 'Resume pagination from a cursor')
|
||||||
|
.option('--json', 'Output as JSON')
|
||||||
|
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
||||||
|
.addHelpText(
|
||||||
|
'after',
|
||||||
|
() =>
|
||||||
|
`\n${ctx.colors.section('Command Examples')}\n${[
|
||||||
|
formatExample('bird user-tweets @steipete', 'Get recent tweets from a user'),
|
||||||
|
formatExample('bird user-tweets steipete -n 10', 'Get 10 tweets (@ is optional)'),
|
||||||
|
formatExample('bird user-tweets @steipete -n 50', 'Fetch 50 tweets (paged)'),
|
||||||
|
formatExample('bird user-tweets @steipete --max-pages 3 -n 200', 'Safety cap (max 3 pages)'),
|
||||||
|
formatExample('bird user-tweets @steipete --json', 'Output as JSON'),
|
||||||
|
formatExample('bird user-tweets @steipete --cursor "DAABCg..."', 'Resume from cursor'),
|
||||||
|
].join('\n')}`,
|
||||||
|
)
|
||||||
|
.action(
|
||||||
|
async (
|
||||||
|
handle: string,
|
||||||
|
cmdOpts: {
|
||||||
|
count?: string;
|
||||||
|
maxPages?: string;
|
||||||
|
delay?: string;
|
||||||
|
cursor?: string;
|
||||||
|
json?: boolean;
|
||||||
|
jsonFull?: boolean;
|
||||||
|
},
|
||||||
|
) => {
|
||||||
|
const opts = program.opts();
|
||||||
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const quoteDepth = ctx.resolveQuoteDepthFromOptions(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}`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
const maxPages = maxPagesParsed.value;
|
||||||
|
|
||||||
|
const delayParsed = parseNonNegativeIntFlag(cmdOpts.delay, '--delay', 1000);
|
||||||
|
if (!delayParsed.ok) {
|
||||||
|
console.error(`${ctx.p('err')}${delayParsed.error}`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
const pageDelayMs = delayParsed.value;
|
||||||
|
|
||||||
|
// Validate inputs
|
||||||
|
if (!Number.isFinite(count) || count <= 0) {
|
||||||
|
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
const pageSize = 20;
|
||||||
|
const hardMaxPages = 10;
|
||||||
|
const hardMaxTweets = pageSize * hardMaxPages;
|
||||||
|
if (count > hardMaxTweets) {
|
||||||
|
console.error(
|
||||||
|
`${ctx.p('err')}Invalid --count. Max ${hardMaxTweets} tweets per run (safety cap: ${hardMaxPages} pages). Use --cursor to continue.`,
|
||||||
|
);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
if (maxPages !== undefined && maxPages > hardMaxPages) {
|
||||||
|
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer (max: ${hardMaxPages}).`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Normalize handle (strip @ if present)
|
||||||
|
const username = normalizeHandle(handle);
|
||||||
|
if (!username) {
|
||||||
|
console.error(`${ctx.p('err')}Invalid handle: ${handle}`);
|
||||||
|
process.exit(2);
|
||||||
|
}
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
|
|
||||||
|
// Look up user ID from username
|
||||||
|
console.error(`${ctx.p('info')}Looking up @${username}...`);
|
||||||
|
const userLookup = await client.getUserIdByUsername(username);
|
||||||
|
if (!userLookup.success || !userLookup.userId) {
|
||||||
|
console.error(`${ctx.p('err')}${userLookup.error || `Could not find user @${username}`}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const displayName = userLookup.name
|
||||||
|
? `${userLookup.name} (@${userLookup.username})`
|
||||||
|
: `@${userLookup.username}`;
|
||||||
|
console.error(`${ctx.p('info')}Fetching tweets from ${displayName}...`);
|
||||||
|
|
||||||
|
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
|
const wantsPaginationOutput = Boolean(cmdOpts.cursor) || maxPages !== undefined || count > pageSize;
|
||||||
|
const result = await client.getUserTweetsPaged(userLookup.userId, count, {
|
||||||
|
includeRaw,
|
||||||
|
maxPages,
|
||||||
|
cursor: cmdOpts.cursor,
|
||||||
|
pageDelayMs,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||||
|
ctx.printTweetsResult(result, {
|
||||||
|
json: isJson,
|
||||||
|
usePagination: wantsPaginationOutput,
|
||||||
|
emptyMessage: `No tweets found for @${username}.`,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Show pagination hint if there's more
|
||||||
|
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 tweets: ${result.error}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
+311
-125
@@ -1,52 +1,111 @@
|
|||||||
import type { Command } from 'commander';
|
import type { Command } from 'commander';
|
||||||
import type { CliContext } from '../cli/shared.js';
|
import type { CliContext } from '../cli/shared.js';
|
||||||
import { TwitterClient } from '../lib/twitter-client.js';
|
import { TwitterClient } from '../lib/twitter-client.js';
|
||||||
|
import type { TwitterUser } from '../lib/twitter-client-types.js';
|
||||||
|
|
||||||
export function registerUserCommands(program: Command, ctx: CliContext): void {
|
export function registerUserCommands(program: Command, ctx: CliContext): void {
|
||||||
program
|
program
|
||||||
.command('following')
|
.command('following')
|
||||||
.description('Get users that you (or another user) follow')
|
.description('Get users that you (or another user) follow')
|
||||||
.option('--user <userId>', 'User ID to get following for (defaults to current user)')
|
.option('--user <userId>', 'User ID to get following for (defaults to current user)')
|
||||||
.option('-n, --count <number>', 'Number of users to fetch', '20')
|
.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')
|
.option('--json', 'Output as JSON')
|
||||||
.action(async (cmdOpts: { user?: string; count?: string; json?: boolean }) => {
|
.action(
|
||||||
const opts = program.opts();
|
async (cmdOpts: {
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
user?: string;
|
||||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
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;
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||||
|
if (maxPages !== undefined && !cmdOpts.all) {
|
||||||
for (const warning of warnings) {
|
console.error(`${ctx.p('err')}--max-pages requires --all.`);
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, 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);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
userId = currentUser.user.id;
|
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 result = await client.getFollowing(userId, count);
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||||
|
|
||||||
if (result.success && result.users) {
|
let userId = cmdOpts.user;
|
||||||
if (cmdOpts.json) {
|
if (!userId) {
|
||||||
console.log(JSON.stringify(result.users, null, 2));
|
const currentUser = await client.getCurrentUser();
|
||||||
} else {
|
if (!currentUser.success || !currentUser.user?.id) {
|
||||||
if (result.users.length === 0) {
|
console.error(`${ctx.p('err')}Failed to get current user: ${currentUser.error || 'Unknown error'}`);
|
||||||
console.log('No users found.');
|
process.exit(1);
|
||||||
} else {
|
}
|
||||||
|
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) {
|
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})`);
|
console.log(`@${user.username} (${user.name})`);
|
||||||
if (user.description) {
|
if (user.description) {
|
||||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||||
@@ -57,57 +116,146 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
|||||||
console.log('──────────────────────────────────────────────────');
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
},
|
||||||
console.error(`${ctx.p('err')}Failed to fetch following: ${result.error}`);
|
);
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('followers')
|
.command('followers')
|
||||||
.description('Get users that follow you (or another user)')
|
.description('Get users that follow you (or another user)')
|
||||||
.option('--user <userId>', 'User ID to get followers for (defaults to current user)')
|
.option('--user <userId>', 'User ID to get followers for (defaults to current user)')
|
||||||
.option('-n, --count <number>', 'Number of users to fetch', '20')
|
.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')
|
.option('--json', 'Output as JSON')
|
||||||
.action(async (cmdOpts: { user?: string; count?: string; json?: boolean }) => {
|
.action(
|
||||||
const opts = program.opts();
|
async (cmdOpts: {
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
user?: string;
|
||||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
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;
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||||
|
if (maxPages !== undefined && !cmdOpts.all) {
|
||||||
for (const warning of warnings) {
|
console.error(`${ctx.p('err')}--max-pages requires --all.`);
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, 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);
|
process.exit(1);
|
||||||
}
|
}
|
||||||
userId = currentUser.user.id;
|
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 result = await client.getFollowers(userId, count);
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs });
|
||||||
|
|
||||||
if (result.success && result.users) {
|
let userId = cmdOpts.user;
|
||||||
if (cmdOpts.json) {
|
if (!userId) {
|
||||||
console.log(JSON.stringify(result.users, null, 2));
|
const currentUser = await client.getCurrentUser();
|
||||||
} else {
|
if (!currentUser.success || !currentUser.user?.id) {
|
||||||
if (result.users.length === 0) {
|
console.error(`${ctx.p('err')}Failed to get current user: ${currentUser.error || 'Unknown error'}`);
|
||||||
console.log('No users found.');
|
process.exit(1);
|
||||||
} else {
|
}
|
||||||
|
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) {
|
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})`);
|
console.log(`@${user.username} (${user.name})`);
|
||||||
if (user.description) {
|
if (user.description) {
|
||||||
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
console.log(` ${user.description.slice(0, 100)}${user.description.length > 100 ? '...' : ''}`);
|
||||||
@@ -118,84 +266,122 @@ export function registerUserCommands(program: Command, ctx: CliContext): void {
|
|||||||
console.log('──────────────────────────────────────────────────');
|
console.log('──────────────────────────────────────────────────');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
// Single page fetch
|
||||||
|
const result = await client.getFollowers(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 followers: ${result.error}`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
},
|
||||||
console.error(`${ctx.p('err')}Failed to fetch followers: ${result.error}`);
|
);
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('likes')
|
.command('likes')
|
||||||
.description('Get your liked tweets')
|
.description('Get your liked tweets')
|
||||||
.option('-n, --count <number>', 'Number of likes to fetch', '20')
|
.option('-n, --count <number>', 'Number of likes to fetch', '20')
|
||||||
|
.option('--all', 'Fetch all likes (paged)')
|
||||||
|
.option('--max-pages <number>', 'Stop after N pages when using --all')
|
||||||
|
.option('--cursor <string>', 'Resume pagination from a cursor')
|
||||||
.option('--json', 'Output as JSON')
|
.option('--json', 'Output as JSON')
|
||||||
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
.option('--json-full', 'Output as JSON with full raw API response in _raw field')
|
||||||
.action(async (cmdOpts: { count?: string; json?: boolean; jsonFull?: boolean }) => {
|
.action(
|
||||||
const opts = program.opts();
|
async (cmdOpts: {
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
count?: string;
|
||||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
json?: boolean;
|
||||||
const count = Number.parseInt(cmdOpts.count || '20', 10);
|
jsonFull?: boolean;
|
||||||
|
all?: boolean;
|
||||||
|
maxPages?: string;
|
||||||
|
cursor?: string;
|
||||||
|
}) => {
|
||||||
|
const opts = program.opts();
|
||||||
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
|
const quoteDepth = ctx.resolveQuoteDepthFromOptions(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 { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const usePagination = cmdOpts.all || cmdOpts.cursor;
|
||||||
|
if (maxPages !== undefined && !usePagination) {
|
||||||
|
console.error(`${ctx.p('err')}--max-pages requires --all or --cursor.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (!usePagination && (!Number.isFinite(count) || count <= 0)) {
|
||||||
|
console.error(`${ctx.p('err')}Invalid --count. Expected a positive integer.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (maxPages !== undefined && (!Number.isFinite(maxPages) || maxPages <= 0)) {
|
||||||
|
console.error(`${ctx.p('err')}Invalid --max-pages. Expected a positive integer.`);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
for (const warning of warnings) {
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
const includeRaw = cmdOpts.jsonFull ?? false;
|
||||||
}
|
const timelineOptions = { includeRaw };
|
||||||
|
const paginationOptions = { includeRaw, maxPages, cursor: cmdOpts.cursor };
|
||||||
|
const result = usePagination
|
||||||
|
? await client.getAllLikes(paginationOptions)
|
||||||
|
: await client.getLikes(count, timelineOptions);
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
if (result.success) {
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
const isJson = Boolean(cmdOpts.json || cmdOpts.jsonFull);
|
||||||
process.exit(1);
|
ctx.printTweetsResult(result, {
|
||||||
}
|
json: isJson,
|
||||||
|
usePagination: Boolean(usePagination),
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
emptyMessage: 'No liked tweets found.',
|
||||||
const includeRaw = cmdOpts.jsonFull ?? false;
|
});
|
||||||
const result = await client.getLikes(count, { includeRaw });
|
} else {
|
||||||
|
console.error(`${ctx.p('err')}Failed to fetch likes: ${result.error}`);
|
||||||
if (result.success && result.tweets) {
|
process.exit(1);
|
||||||
ctx.printTweets(result.tweets, {
|
}
|
||||||
json: cmdOpts.json || cmdOpts.jsonFull,
|
},
|
||||||
emptyMessage: 'No liked tweets found.',
|
);
|
||||||
});
|
|
||||||
} else {
|
|
||||||
console.error(`${ctx.p('err')}Failed to fetch likes: ${result.error}`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
program
|
program
|
||||||
.command('whoami')
|
.command('whoami')
|
||||||
.description('Show which Twitter account the current credentials belong to')
|
.description('Show which Twitter account the relay belongs to')
|
||||||
.action(async () => {
|
.action(async () => {
|
||||||
const opts = program.opts();
|
const opts = program.opts();
|
||||||
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
const timeoutMs = ctx.resolveTimeoutFromOptions(opts);
|
||||||
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
const quoteDepth = ctx.resolveQuoteDepthFromOptions(opts);
|
||||||
|
const relayBaseUrl = ctx.resolveRelayBaseUrlFromOptions(opts);
|
||||||
|
|
||||||
const { cookies, warnings } = await ctx.resolveCredentialsFromOptions(opts);
|
const client = new TwitterClient({ relayBaseUrl, timeoutMs, quoteDepth });
|
||||||
|
|
||||||
for (const warning of warnings) {
|
|
||||||
console.error(`${ctx.p('warn')}${warning}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken || !cookies.ct0) {
|
|
||||||
console.error(`${ctx.p('err')}Missing required credentials`);
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (cookies.source) {
|
|
||||||
console.error(`${ctx.l('source')}${cookies.source}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies, timeoutMs, quoteDepth });
|
|
||||||
const result = await client.getCurrentUser();
|
const result = await client.getCurrentUser();
|
||||||
|
|
||||||
const credentialSource = cookies.source ?? 'env/auto-detected cookies';
|
|
||||||
|
|
||||||
if (result.success && result.user) {
|
if (result.success && result.user) {
|
||||||
console.log(`${ctx.l('user')}@${result.user.username} (${result.user.name})`);
|
console.log(`${ctx.l('user')}@${result.user.username} (${result.user.name})`);
|
||||||
console.log(`${ctx.l('userId')}${result.user.id}`);
|
console.log(`${ctx.l('userId')}${result.user.id}`);
|
||||||
console.log(`${ctx.l('engine')}graphql`);
|
console.log(`${ctx.l('engine')}twitter-safe-relay`);
|
||||||
console.log(`${ctx.l('credentials')}${credentialSource}`);
|
console.log(`${ctx.l('credentials')}${relayBaseUrl ?? 'TWITTER_RELAY_BASE_URL'}`);
|
||||||
} else {
|
} else {
|
||||||
console.error(`${ctx.p('err')}Failed to determine current user: ${result.error ?? 'Unknown error'}`);
|
console.error(`${ctx.p('err')}Failed to determine current user: ${result.error ?? 'Unknown error'}`);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
|
|||||||
@@ -1,235 +0,0 @@
|
|||||||
/**
|
|
||||||
* Browser cookie extraction for Twitter authentication.
|
|
||||||
* Delegates to @steipete/sweet-cookie for Safari/Chrome/Firefox reads.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { getCookies } from '@steipete/sweet-cookie';
|
|
||||||
|
|
||||||
export interface TwitterCookies {
|
|
||||||
authToken: string | null;
|
|
||||||
ct0: string | null;
|
|
||||||
cookieHeader: string | null;
|
|
||||||
source: string | null;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface CookieExtractionResult {
|
|
||||||
cookies: TwitterCookies;
|
|
||||||
warnings: string[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export type CookieSource = 'safari' | 'chrome' | 'firefox';
|
|
||||||
|
|
||||||
const TWITTER_COOKIE_NAMES = ['auth_token', 'ct0'] as const;
|
|
||||||
const TWITTER_URL = 'https://x.com/';
|
|
||||||
const TWITTER_ORIGINS: string[] = ['https://x.com/', 'https://twitter.com/'];
|
|
||||||
const DEFAULT_COOKIE_TIMEOUT_MS = 30_000;
|
|
||||||
|
|
||||||
function normalizeValue(value: unknown): string | null {
|
|
||||||
if (typeof value !== 'string') {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const trimmed = value.trim();
|
|
||||||
return trimmed.length > 0 ? trimmed : null;
|
|
||||||
}
|
|
||||||
|
|
||||||
function cookieHeader(authToken: string, ct0: string): string {
|
|
||||||
return `auth_token=${authToken}; ct0=${ct0}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildEmpty(): TwitterCookies {
|
|
||||||
return { authToken: null, ct0: null, cookieHeader: null, source: null };
|
|
||||||
}
|
|
||||||
|
|
||||||
function readEnvCookie(cookies: TwitterCookies, keys: readonly string[], field: 'authToken' | 'ct0'): void {
|
|
||||||
if (cookies[field]) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
for (const key of keys) {
|
|
||||||
const value = normalizeValue(process.env[key]);
|
|
||||||
if (!value) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
cookies[field] = value;
|
|
||||||
if (!cookies.source) {
|
|
||||||
cookies.source = `env ${key}`;
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function resolveSources(cookieSource?: CookieSource | CookieSource[]): CookieSource[] {
|
|
||||||
if (Array.isArray(cookieSource)) {
|
|
||||||
return cookieSource;
|
|
||||||
}
|
|
||||||
if (cookieSource) {
|
|
||||||
return [cookieSource];
|
|
||||||
}
|
|
||||||
return ['safari', 'chrome', 'firefox'];
|
|
||||||
}
|
|
||||||
|
|
||||||
function labelForSource(source: CookieSource, profile?: string): string {
|
|
||||||
if (source === 'safari') {
|
|
||||||
return 'Safari';
|
|
||||||
}
|
|
||||||
if (source === 'chrome') {
|
|
||||||
return profile ? `Chrome profile "${profile}"` : 'Chrome default profile';
|
|
||||||
}
|
|
||||||
return profile ? `Firefox profile "${profile}"` : 'Firefox default profile';
|
|
||||||
}
|
|
||||||
|
|
||||||
function pickCookieValue(
|
|
||||||
cookies: Array<{ name?: string; value?: string; domain?: string }>,
|
|
||||||
name: (typeof TWITTER_COOKIE_NAMES)[number],
|
|
||||||
): string | null {
|
|
||||||
const matches = cookies.filter((c) => c?.name === name && typeof c.value === 'string');
|
|
||||||
if (matches.length === 0) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
const preferred = matches.find((c) => (c.domain ?? '').endsWith('x.com'));
|
|
||||||
if (preferred?.value) {
|
|
||||||
return preferred.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
const twitter = matches.find((c) => (c.domain ?? '').endsWith('twitter.com'));
|
|
||||||
if (twitter?.value) {
|
|
||||||
return twitter.value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return matches[0]?.value ?? null;
|
|
||||||
}
|
|
||||||
|
|
||||||
async function readTwitterCookiesFromBrowser(options: {
|
|
||||||
source: CookieSource;
|
|
||||||
chromeProfile?: string;
|
|
||||||
firefoxProfile?: string;
|
|
||||||
cookieTimeoutMs?: number;
|
|
||||||
}): Promise<CookieExtractionResult> {
|
|
||||||
const warnings: string[] = [];
|
|
||||||
const out = buildEmpty();
|
|
||||||
|
|
||||||
const { cookies, warnings: providerWarnings } = await getCookies({
|
|
||||||
url: TWITTER_URL,
|
|
||||||
origins: TWITTER_ORIGINS,
|
|
||||||
names: [...TWITTER_COOKIE_NAMES],
|
|
||||||
browsers: [options.source],
|
|
||||||
mode: 'merge',
|
|
||||||
chromeProfile: options.chromeProfile,
|
|
||||||
firefoxProfile: options.firefoxProfile,
|
|
||||||
timeoutMs: options.cookieTimeoutMs,
|
|
||||||
});
|
|
||||||
warnings.push(...providerWarnings);
|
|
||||||
|
|
||||||
const authToken = pickCookieValue(cookies, 'auth_token');
|
|
||||||
const ct0 = pickCookieValue(cookies, 'ct0');
|
|
||||||
if (authToken) {
|
|
||||||
out.authToken = authToken;
|
|
||||||
}
|
|
||||||
if (ct0) {
|
|
||||||
out.ct0 = ct0;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (out.authToken && out.ct0) {
|
|
||||||
out.cookieHeader = cookieHeader(out.authToken, out.ct0);
|
|
||||||
out.source = labelForSource(
|
|
||||||
options.source,
|
|
||||||
options.source === 'chrome' ? options.chromeProfile : options.firefoxProfile,
|
|
||||||
);
|
|
||||||
return { cookies: out, warnings };
|
|
||||||
}
|
|
||||||
|
|
||||||
if (options.source === 'safari') {
|
|
||||||
warnings.push('No Twitter cookies found in Safari. Make sure you are logged into x.com in Safari.');
|
|
||||||
} else if (options.source === 'chrome') {
|
|
||||||
warnings.push('No Twitter cookies found in Chrome. Make sure you are logged into x.com in Chrome.');
|
|
||||||
} else {
|
|
||||||
warnings.push(
|
|
||||||
'No Twitter cookies found in Firefox. Make sure you are logged into x.com in Firefox and the profile exists.',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
return { cookies: out, warnings };
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function extractCookiesFromSafari(): Promise<CookieExtractionResult> {
|
|
||||||
return readTwitterCookiesFromBrowser({ source: 'safari' });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function extractCookiesFromChrome(profile?: string): Promise<CookieExtractionResult> {
|
|
||||||
return readTwitterCookiesFromBrowser({ source: 'chrome', chromeProfile: profile });
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function extractCookiesFromFirefox(profile?: string): Promise<CookieExtractionResult> {
|
|
||||||
return readTwitterCookiesFromBrowser({ source: 'firefox', firefoxProfile: profile });
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Resolve Twitter credentials from multiple sources.
|
|
||||||
* Priority: CLI args > environment variables > browsers (ordered).
|
|
||||||
*/
|
|
||||||
export async function resolveCredentials(options: {
|
|
||||||
authToken?: string;
|
|
||||||
ct0?: string;
|
|
||||||
cookieSource?: CookieSource | CookieSource[];
|
|
||||||
chromeProfile?: string;
|
|
||||||
firefoxProfile?: string;
|
|
||||||
cookieTimeoutMs?: number;
|
|
||||||
}): Promise<CookieExtractionResult> {
|
|
||||||
const warnings: string[] = [];
|
|
||||||
const cookies = buildEmpty();
|
|
||||||
const cookieTimeoutMs =
|
|
||||||
typeof options.cookieTimeoutMs === 'number' &&
|
|
||||||
Number.isFinite(options.cookieTimeoutMs) &&
|
|
||||||
options.cookieTimeoutMs > 0
|
|
||||||
? options.cookieTimeoutMs
|
|
||||||
: process.platform === 'darwin'
|
|
||||||
? DEFAULT_COOKIE_TIMEOUT_MS
|
|
||||||
: undefined;
|
|
||||||
|
|
||||||
if (options.authToken) {
|
|
||||||
cookies.authToken = options.authToken;
|
|
||||||
cookies.source = 'CLI argument';
|
|
||||||
}
|
|
||||||
if (options.ct0) {
|
|
||||||
cookies.ct0 = options.ct0;
|
|
||||||
if (!cookies.source) {
|
|
||||||
cookies.source = 'CLI argument';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
readEnvCookie(cookies, ['AUTH_TOKEN', 'TWITTER_AUTH_TOKEN'], 'authToken');
|
|
||||||
readEnvCookie(cookies, ['CT0', 'TWITTER_CT0'], 'ct0');
|
|
||||||
|
|
||||||
if (cookies.authToken && cookies.ct0) {
|
|
||||||
cookies.cookieHeader = cookieHeader(cookies.authToken, cookies.ct0);
|
|
||||||
return { cookies, warnings };
|
|
||||||
}
|
|
||||||
|
|
||||||
const sourcesToTry = resolveSources(options.cookieSource);
|
|
||||||
for (const source of sourcesToTry) {
|
|
||||||
const res = await readTwitterCookiesFromBrowser({
|
|
||||||
source,
|
|
||||||
chromeProfile: options.chromeProfile,
|
|
||||||
firefoxProfile: options.firefoxProfile,
|
|
||||||
cookieTimeoutMs,
|
|
||||||
});
|
|
||||||
warnings.push(...res.warnings);
|
|
||||||
if (res.cookies.authToken && res.cookies.ct0) {
|
|
||||||
return { cookies: res.cookies, warnings };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!cookies.authToken) {
|
|
||||||
warnings.push(
|
|
||||||
'Missing auth_token - provide via --auth-token, AUTH_TOKEN env var, or login to x.com in Safari/Chrome/Firefox',
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if (!cookies.ct0) {
|
|
||||||
warnings.push('Missing ct0 - provide via --ct0, CT0 env var, or login to x.com in Safari/Chrome/Firefox');
|
|
||||||
}
|
|
||||||
if (cookies.authToken && cookies.ct0) {
|
|
||||||
cookies.cookieHeader = cookieHeader(cookies.authToken, cookies.ct0);
|
|
||||||
}
|
|
||||||
|
|
||||||
return { cookies, warnings };
|
|
||||||
}
|
|
||||||
+2
-9
@@ -1,12 +1,3 @@
|
|||||||
export {
|
|
||||||
type CookieExtractionResult,
|
|
||||||
type CookieSource,
|
|
||||||
extractCookiesFromChrome,
|
|
||||||
extractCookiesFromFirefox,
|
|
||||||
extractCookiesFromSafari,
|
|
||||||
resolveCredentials,
|
|
||||||
type TwitterCookies,
|
|
||||||
} from './cookies.js';
|
|
||||||
export { runtimeQueryIds } from './runtime-query-ids.js';
|
export { runtimeQueryIds } from './runtime-query-ids.js';
|
||||||
export {
|
export {
|
||||||
type CurrentUserResult,
|
type CurrentUserResult,
|
||||||
@@ -18,6 +9,8 @@ export {
|
|||||||
type TwitterClientOptions,
|
type TwitterClientOptions,
|
||||||
type TwitterUser,
|
type TwitterUser,
|
||||||
} from './twitter-client.js';
|
} 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 } from './twitter-client-search.js';
|
||||||
export type { TimelineFetchOptions } from './twitter-client-timelines.js';
|
export type { TimelineFetchOptions } from './twitter-client-timelines.js';
|
||||||
export type { TweetFetchOptions } from './twitter-client-tweet-detail.js';
|
export type { TweetFetchOptions } from './twitter-client-tweet-detail.js';
|
||||||
|
|||||||
+23
-3
@@ -2,6 +2,7 @@ export type OutputConfig = {
|
|||||||
plain: boolean;
|
plain: boolean;
|
||||||
emoji: boolean;
|
emoji: boolean;
|
||||||
color: boolean;
|
color: boolean;
|
||||||
|
hyperlinks: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type StatusKind = 'ok' | 'warn' | 'err' | 'info' | 'hint';
|
export type StatusKind = 'ok' | 'warn' | 'err' | 'info' | 'hint';
|
||||||
@@ -33,8 +34,9 @@ export function resolveOutputConfigFromArgv(argv: string[], env: NodeJS.ProcessE
|
|||||||
const plain = argv.includes('--plain');
|
const plain = argv.includes('--plain');
|
||||||
const emoji = !plain && !argv.includes('--no-emoji');
|
const emoji = !plain && !argv.includes('--no-emoji');
|
||||||
const color = !plain && !argv.includes('--no-color') && defaultColor;
|
const color = !plain && !argv.includes('--no-color') && defaultColor;
|
||||||
|
const hyperlinks = !plain && isTty;
|
||||||
|
|
||||||
return { plain, emoji, color };
|
return { plain, emoji, color, hyperlinks };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function resolveOutputConfigFromCommander(
|
export function resolveOutputConfigFromCommander(
|
||||||
@@ -48,8 +50,9 @@ export function resolveOutputConfigFromCommander(
|
|||||||
const plain = Boolean(opts.plain);
|
const plain = Boolean(opts.plain);
|
||||||
const emoji = !plain && (opts.emoji ?? true);
|
const emoji = !plain && (opts.emoji ?? true);
|
||||||
const color = !plain && (opts.color ?? true) && defaultColor;
|
const color = !plain && (opts.color ?? true) && defaultColor;
|
||||||
|
const hyperlinks = !plain && isTty;
|
||||||
|
|
||||||
return { plain, emoji, color };
|
return { plain, emoji, color, hyperlinks };
|
||||||
}
|
}
|
||||||
|
|
||||||
export function statusPrefix(kind: StatusKind, cfg: OutputConfig): string {
|
export function statusPrefix(kind: StatusKind, cfg: OutputConfig): string {
|
||||||
@@ -93,6 +96,23 @@ export function formatTweetUrl(tweetId: string): string {
|
|||||||
return `https://x.com/i/status/${tweetId}`;
|
return `https://x.com/i/status/${tweetId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wraps a URL in OSC 8 escape sequences to make it clickable in supported terminals.
|
||||||
|
* Falls back to plain text when not in a TTY or when hyperlinks are disabled.
|
||||||
|
*/
|
||||||
|
export function hyperlink(url: string, text?: string, cfg?: OutputConfig): string {
|
||||||
|
const displayText = text ?? url;
|
||||||
|
// Only use hyperlinks when explicitly enabled (requires TTY and not plain mode)
|
||||||
|
if (!cfg?.hyperlinks) {
|
||||||
|
return displayText;
|
||||||
|
}
|
||||||
|
const safeUrl = url.replaceAll('\x1b', '').replaceAll('\x07', '');
|
||||||
|
const safeText = displayText.replaceAll('\x1b', '').replaceAll('\x07', '');
|
||||||
|
// OSC 8 hyperlink: \x1b]8;;URL\x07TEXT\x1b]8;;\x07
|
||||||
|
return `\x1b]8;;${safeUrl}\x07${safeText}\x1b]8;;\x07`;
|
||||||
|
}
|
||||||
|
|
||||||
export function formatTweetUrlLine(tweetId: string, cfg: OutputConfig): string {
|
export function formatTweetUrlLine(tweetId: string, cfg: OutputConfig): string {
|
||||||
return `${labelPrefix('url', cfg)}${formatTweetUrl(tweetId)}`;
|
const url = formatTweetUrl(tweetId);
|
||||||
|
return `${labelPrefix('url', cfg)}${hyperlink(url, url, cfg)}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
export type CursorPage<T> =
|
||||||
|
| {
|
||||||
|
success: true;
|
||||||
|
items: T[];
|
||||||
|
cursor?: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
success: false;
|
||||||
|
error: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type CursorPaginationResult<T> =
|
||||||
|
| {
|
||||||
|
success: true;
|
||||||
|
items: T[];
|
||||||
|
nextCursor?: string;
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
success: false;
|
||||||
|
error: string;
|
||||||
|
items?: T[];
|
||||||
|
nextCursor?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function paginateCursor<T>(opts: {
|
||||||
|
cursor?: string;
|
||||||
|
maxPages?: number;
|
||||||
|
pageDelayMs?: number;
|
||||||
|
sleep: (ms: number) => Promise<void>;
|
||||||
|
getKey: (item: T) => string;
|
||||||
|
fetchPage: (cursor?: string) => Promise<CursorPage<T>>;
|
||||||
|
}): Promise<CursorPaginationResult<T>> {
|
||||||
|
const { maxPages, pageDelayMs = 1000 } = opts;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const items: T[] = [];
|
||||||
|
let cursor: string | undefined = opts.cursor;
|
||||||
|
let pagesFetched = 0;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
if (pagesFetched > 0 && pageDelayMs > 0) {
|
||||||
|
await opts.sleep(pageDelayMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
const page = await opts.fetchPage(cursor);
|
||||||
|
if (!page.success) {
|
||||||
|
if (items.length > 0) {
|
||||||
|
return { success: false, error: page.error, items, nextCursor: cursor };
|
||||||
|
}
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
pagesFetched += 1;
|
||||||
|
|
||||||
|
for (const item of page.items) {
|
||||||
|
const key = opts.getKey(item);
|
||||||
|
if (seen.has(key)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(key);
|
||||||
|
items.push(item);
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageCursor = page.cursor;
|
||||||
|
if (!pageCursor || pageCursor === cursor) {
|
||||||
|
return { success: true, items, nextCursor: undefined };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxPages !== undefined && pagesFetched >= maxPages) {
|
||||||
|
return { success: true, items, nextCursor: pageCursor };
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor = pageCursor;
|
||||||
|
}
|
||||||
|
}
|
||||||
+10
-10
@@ -1,17 +1,17 @@
|
|||||||
{
|
{
|
||||||
"CreateTweet": "Uf3io9zVp1DsYxrmL5FJ7g",
|
"CreateTweet": "nmdAQXJDxw6-0KKF2on7eA",
|
||||||
"CreateRetweet": "LFho5rIi4xcKO90p9jwG7A",
|
"CreateRetweet": "LFho5rIi4xcKO90p9jwG7A",
|
||||||
"FavoriteTweet": "lI07N6Otwv1PhnEgXILM7A",
|
"FavoriteTweet": "lI07N6Otwv1PhnEgXILM7A",
|
||||||
"DeleteBookmark": "Wlmlj2-xzyS1GN3a6cj-mQ",
|
"DeleteBookmark": "Wlmlj2-xzyS1GN3a6cj-mQ",
|
||||||
"TweetDetail": "97JF30KziU00483E_8elBA",
|
"TweetDetail": "_NvJCnIjOW__EP5-RF197A",
|
||||||
"SearchTimeline": "M1jEez78PEfVfbQLvlWMvQ",
|
"SearchTimeline": "6AAys3t42mosm_yTI_QENg",
|
||||||
"Bookmarks": "RV1g3b8n_SGOHwkqKYSCFw",
|
"Bookmarks": "RV1g3b8n_SGOHwkqKYSCFw",
|
||||||
"BookmarkFolderTimeline": "KJIQpsvxrTfRIlbaRIySHQ",
|
"BookmarkFolderTimeline": "KJIQpsvxrTfRIlbaRIySHQ",
|
||||||
"Following": "BEkNpEt5pNETESoqMsTEGA",
|
"Following": "mWYeougg_ocJS2Vr1Vt28w",
|
||||||
"Followers": "kuFUYP9eV1FPoEy4N-pi7w",
|
"Followers": "SFYY3WsgwjlXSLlfnEUE4A",
|
||||||
"Likes": "JR2gceKucIKcVNB_9JkhsA",
|
"Likes": "ETJflBunfqNa1uE1mBPCaw",
|
||||||
"ListOwnerships": "wQcOSjSQ8NtgxIwvYl1lMg",
|
"ExploreSidebar": "lpSN4M6qpimkF4nRFPE3nQ",
|
||||||
"ListMemberships": "BlEXXdARdSeL_0KyKHHvvg",
|
"ExplorePage": "kheAINB_4pzRDqkzG3K-ng",
|
||||||
"ListLatestTweetsTimeline": "2TemLyqrMpTeAmysdbnVqw",
|
"GenericTimelineById": "uGSr7alSjR9v6QJAIaqSKQ",
|
||||||
"ListByRestId": "wXzyA5vM_aVkBL9G8Vp3kw"
|
"TrendHistory": "Sj4T-jSB9pr0Mxtsc1UKZQ"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import { randomBytes, randomUUID } from 'node:crypto';
|
|
||||||
import { runtimeQueryIds } from './runtime-query-ids.js';
|
import { runtimeQueryIds } from './runtime-query-ids.js';
|
||||||
import { type OperationName, QUERY_IDS, TARGET_QUERY_ID_OPERATIONS } from './twitter-client-constants.js';
|
import { type OperationName, QUERY_IDS, TARGET_QUERY_ID_OPERATIONS } from './twitter-client-constants.js';
|
||||||
import type { CurrentUserResult, TwitterClientOptions } from './twitter-client-types.js';
|
import type { CurrentUserResult, TwitterClientOptions } from './twitter-client-types.js';
|
||||||
import { normalizeQuoteDepth } from './twitter-client-utils.js';
|
import { normalizeQuoteDepth } from './twitter-client-utils.js';
|
||||||
|
|
||||||
|
const TRAILING_SLASHES = /\/+$/;
|
||||||
|
|
||||||
// biome-ignore lint/suspicious/noExplicitAny: TS mixin base constructor requirement.
|
// biome-ignore lint/suspicious/noExplicitAny: TS mixin base constructor requirement.
|
||||||
export type Constructor<T = object> = new (...args: any[]) => T;
|
export type Constructor<T = object> = new (...args: any[]) => T;
|
||||||
// biome-ignore lint/suspicious/noExplicitAny: TS mixin base constructor requirement.
|
// biome-ignore lint/suspicious/noExplicitAny: TS mixin base constructor requirement.
|
||||||
@@ -13,34 +14,23 @@ export type Mixin<TBase extends AbstractConstructor<TwitterClientBase>, TAdded>
|
|||||||
) => TwitterClientBase & TAdded;
|
) => TwitterClientBase & TAdded;
|
||||||
|
|
||||||
export abstract class TwitterClientBase {
|
export abstract class TwitterClientBase {
|
||||||
protected authToken: string;
|
protected relayBaseUrl: string;
|
||||||
protected ct0: string;
|
|
||||||
protected cookieHeader: string;
|
|
||||||
protected userAgent: string;
|
|
||||||
protected timeoutMs?: number;
|
protected timeoutMs?: number;
|
||||||
protected quoteDepth: number;
|
protected quoteDepth: number;
|
||||||
protected clientUuid: string;
|
|
||||||
protected clientDeviceId: string;
|
|
||||||
protected clientUserId?: string;
|
protected clientUserId?: string;
|
||||||
|
|
||||||
constructor(options: TwitterClientOptions) {
|
constructor(options: TwitterClientOptions) {
|
||||||
if (!options.cookies.authToken || !options.cookies.ct0) {
|
this.relayBaseUrl = this.normalizeRelayBaseUrl(options.relayBaseUrl ?? process.env.TWITTER_RELAY_BASE_URL);
|
||||||
throw new Error('Both authToken and ct0 cookies are required');
|
|
||||||
}
|
|
||||||
this.authToken = options.cookies.authToken;
|
|
||||||
this.ct0 = options.cookies.ct0;
|
|
||||||
this.cookieHeader = options.cookies.cookieHeader || `auth_token=${this.authToken}; ct0=${this.ct0}`;
|
|
||||||
this.userAgent =
|
|
||||||
options.userAgent ||
|
|
||||||
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36';
|
|
||||||
this.timeoutMs = options.timeoutMs;
|
this.timeoutMs = options.timeoutMs;
|
||||||
this.quoteDepth = normalizeQuoteDepth(options.quoteDepth);
|
this.quoteDepth = normalizeQuoteDepth(options.quoteDepth);
|
||||||
this.clientUuid = randomUUID();
|
|
||||||
this.clientDeviceId = randomUUID();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected abstract getCurrentUser(): Promise<CurrentUserResult>;
|
protected abstract getCurrentUser(): Promise<CurrentUserResult>;
|
||||||
|
|
||||||
|
protected async sleep(ms: number): Promise<void> {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
protected async getQueryId(operationName: OperationName): Promise<string> {
|
protected async getQueryId(operationName: OperationName): Promise<string> {
|
||||||
const cached = await runtimeQueryIds.getQueryId(operationName);
|
const cached = await runtimeQueryIds.getQueryId(operationName);
|
||||||
return cached ?? QUERY_IDS[operationName];
|
return cached ?? QUERY_IDS[operationName];
|
||||||
@@ -68,63 +58,46 @@ export abstract class TwitterClientBase {
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected async fetchWithTimeout(url: string, init: RequestInit): Promise<Response> {
|
protected async fetchWithTimeout(url: string, init: RequestInit): Promise<Response> {
|
||||||
|
const relayUrl = this.toRelayUrl(url);
|
||||||
if (!this.timeoutMs || this.timeoutMs <= 0) {
|
if (!this.timeoutMs || this.timeoutMs <= 0) {
|
||||||
return fetch(url, init);
|
return fetch(relayUrl, init);
|
||||||
}
|
}
|
||||||
|
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
|
const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);
|
||||||
try {
|
try {
|
||||||
return await fetch(url, { ...init, signal: controller.signal });
|
return await fetch(relayUrl, { ...init, signal: controller.signal });
|
||||||
} finally {
|
} finally {
|
||||||
clearTimeout(timeoutId);
|
clearTimeout(timeoutId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
protected getHeaders(): Record<string, string> {
|
protected getHeaders(): Record<string, string> {
|
||||||
return this.getJsonHeaders();
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
protected createTransactionId(): string {
|
private normalizeRelayBaseUrl(value: string | undefined): string {
|
||||||
return randomBytes(16).toString('hex');
|
const trimmed = value?.trim();
|
||||||
}
|
if (!trimmed) {
|
||||||
|
throw new Error('TWITTER_RELAY_BASE_URL is required');
|
||||||
protected getBaseHeaders(): Record<string, string> {
|
|
||||||
const headers: Record<string, string> = {
|
|
||||||
accept: '*/*',
|
|
||||||
'accept-language': 'en-US,en;q=0.9',
|
|
||||||
authorization:
|
|
||||||
'Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA',
|
|
||||||
'x-csrf-token': this.ct0,
|
|
||||||
'x-twitter-auth-type': 'OAuth2Session',
|
|
||||||
'x-twitter-active-user': 'yes',
|
|
||||||
'x-twitter-client-language': 'en',
|
|
||||||
'x-client-uuid': this.clientUuid,
|
|
||||||
'x-twitter-client-deviceid': this.clientDeviceId,
|
|
||||||
'x-client-transaction-id': this.createTransactionId(),
|
|
||||||
cookie: this.cookieHeader,
|
|
||||||
'user-agent': this.userAgent,
|
|
||||||
origin: 'https://x.com',
|
|
||||||
referer: 'https://x.com/',
|
|
||||||
};
|
|
||||||
|
|
||||||
if (this.clientUserId) {
|
|
||||||
headers['x-twitter-client-user-id'] = this.clientUserId;
|
|
||||||
}
|
}
|
||||||
|
return trimmed.replace(TRAILING_SLASHES, '');
|
||||||
|
}
|
||||||
|
|
||||||
return headers;
|
private toRelayUrl(url: string): string {
|
||||||
|
const parsed = new URL(url);
|
||||||
|
if (!['x.com', 'twitter.com', 'api.twitter.com', 'upload.twitter.com'].includes(parsed.hostname)) {
|
||||||
|
throw new Error(`Unsupported Twitter API host: ${parsed.hostname}`);
|
||||||
|
}
|
||||||
|
return `${this.relayBaseUrl}${parsed.pathname}${parsed.search}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
protected getJsonHeaders(): Record<string, string> {
|
protected getJsonHeaders(): Record<string, string> {
|
||||||
return {
|
return { 'content-type': 'application/json' };
|
||||||
...this.getBaseHeaders(),
|
|
||||||
'content-type': 'application/json',
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected getUploadHeaders(): Record<string, string> {
|
protected getUploadHeaders(): Record<string, string> {
|
||||||
// Note: do not set content-type; URLSearchParams/FormData need to set it (incl boundary) themselves.
|
return {};
|
||||||
return this.getBaseHeaders();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
protected async ensureClientUserId(): Promise<void> {
|
protected async ensureClientUserId(): Promise<void> {
|
||||||
|
|||||||
@@ -22,7 +22,6 @@ export function withBookmarks<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
let urlWithOperation = `${TWITTER_API_BASE}/${queryId}/DeleteBookmark`;
|
let urlWithOperation = `${TWITTER_API_BASE}/${queryId}/DeleteBookmark`;
|
||||||
|
|
||||||
const buildBody = () => JSON.stringify({ variables, queryId });
|
const buildBody = () => JSON.stringify({ variables, queryId });
|
||||||
const buildHeaders = () => ({ ...this.getHeaders(), referer: `https://x.com/i/status/${tweetId}` });
|
|
||||||
let body = buildBody();
|
let body = buildBody();
|
||||||
|
|
||||||
const parseResponse = async (response: Response): Promise<BookmarkMutationResult> => {
|
const parseResponse = async (response: Response): Promise<BookmarkMutationResult> => {
|
||||||
@@ -42,7 +41,7 @@ export function withBookmarks<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
try {
|
try {
|
||||||
let response = await this.fetchWithTimeout(urlWithOperation, {
|
let response = await this.fetchWithTimeout(urlWithOperation, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: buildHeaders(),
|
headers: this.getJsonHeaders(),
|
||||||
body,
|
body,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -54,14 +53,14 @@ export function withBookmarks<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
|
|
||||||
response = await this.fetchWithTimeout(urlWithOperation, {
|
response = await this.fetchWithTimeout(urlWithOperation, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: buildHeaders(),
|
headers: this.getJsonHeaders(),
|
||||||
body,
|
body,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.status === 404) {
|
if (response.status === 404) {
|
||||||
const retry = await this.fetchWithTimeout(TWITTER_GRAPHQL_POST_URL, {
|
const retry = await this.fetchWithTimeout(TWITTER_GRAPHQL_POST_URL, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: buildHeaders(),
|
headers: this.getJsonHeaders(),
|
||||||
body,
|
body,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -6,10 +6,6 @@ export const TWITTER_GRAPHQL_POST_URL = 'https://x.com/i/api/graphql';
|
|||||||
export const TWITTER_UPLOAD_URL = 'https://upload.twitter.com/i/media/upload.json';
|
export const TWITTER_UPLOAD_URL = 'https://upload.twitter.com/i/media/upload.json';
|
||||||
export const TWITTER_MEDIA_METADATA_URL = 'https://x.com/i/api/1.1/media/metadata/create.json';
|
export const TWITTER_MEDIA_METADATA_URL = 'https://x.com/i/api/1.1/media/metadata/create.json';
|
||||||
export const TWITTER_STATUS_UPDATE_URL = 'https://x.com/i/api/1.1/statuses/update.json';
|
export const TWITTER_STATUS_UPDATE_URL = 'https://x.com/i/api/1.1/statuses/update.json';
|
||||||
export const SETTINGS_SCREEN_NAME_REGEX = /"screen_name":"([^"]+)"/;
|
|
||||||
export const SETTINGS_USER_ID_REGEX = /"user_id"\s*:\s*"(\d+)"/;
|
|
||||||
export const SETTINGS_NAME_REGEX = /"name":"([^"\\]*(?:\\.[^"\\]*)*)"/;
|
|
||||||
|
|
||||||
// Query IDs rotate frequently; the values in query-ids.json are refreshed by
|
// Query IDs rotate frequently; the values in query-ids.json are refreshed by
|
||||||
// scripts/update-query-ids.ts. The fallback values keep the client usable if
|
// scripts/update-query-ids.ts. The fallback values keep the client usable if
|
||||||
// the file is missing or incomplete.
|
// the file is missing or incomplete.
|
||||||
@@ -21,6 +17,7 @@ export const FALLBACK_QUERY_IDS = {
|
|||||||
TweetDetail: '97JF30KziU00483E_8elBA',
|
TweetDetail: '97JF30KziU00483E_8elBA',
|
||||||
SearchTimeline: 'M1jEez78PEfVfbQLvlWMvQ',
|
SearchTimeline: 'M1jEez78PEfVfbQLvlWMvQ',
|
||||||
UserArticlesTweets: '8zBy9h4L90aDL02RsBcCFg',
|
UserArticlesTweets: '8zBy9h4L90aDL02RsBcCFg',
|
||||||
|
UserTweets: 'Wms1GvIiHXAPBaCr9KblaA',
|
||||||
Bookmarks: 'RV1g3b8n_SGOHwkqKYSCFw',
|
Bookmarks: 'RV1g3b8n_SGOHwkqKYSCFw',
|
||||||
Following: 'BEkNpEt5pNETESoqMsTEGA',
|
Following: 'BEkNpEt5pNETESoqMsTEGA',
|
||||||
Followers: 'kuFUYP9eV1FPoEy4N-pi7w',
|
Followers: 'kuFUYP9eV1FPoEy4N-pi7w',
|
||||||
@@ -30,6 +27,12 @@ export const FALLBACK_QUERY_IDS = {
|
|||||||
ListMemberships: 'BlEXXdARdSeL_0KyKHHvvg',
|
ListMemberships: 'BlEXXdARdSeL_0KyKHHvvg',
|
||||||
ListLatestTweetsTimeline: '2TemLyqrMpTeAmysdbnVqw',
|
ListLatestTweetsTimeline: '2TemLyqrMpTeAmysdbnVqw',
|
||||||
ListByRestId: 'wXzyA5vM_aVkBL9G8Vp3kw',
|
ListByRestId: 'wXzyA5vM_aVkBL9G8Vp3kw',
|
||||||
|
HomeTimeline: 'edseUwk9sP5Phz__9TIRnA',
|
||||||
|
HomeLatestTimeline: 'iOEZpOdfekFsxSlPQCQtPg',
|
||||||
|
ExploreSidebar: 'lpSN4M6qpimkF4nRFPE3nQ',
|
||||||
|
ExplorePage: 'kheAINB_4pzRDqkzG3K-ng',
|
||||||
|
GenericTimelineById: 'uGSr7alSjR9v6QJAIaqSKQ',
|
||||||
|
TrendHistory: 'Sj4T-jSB9pr0Mxtsc1UKZQ',
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
export type OperationName = keyof typeof FALLBACK_QUERY_IDS;
|
export type OperationName = keyof typeof FALLBACK_QUERY_IDS;
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ export function buildArticleFeatures(): Record<string, boolean> {
|
|||||||
verified_phone_label_enabled: false,
|
verified_phone_label_enabled: false,
|
||||||
creator_subscriptions_tweet_preview_api_enabled: true,
|
creator_subscriptions_tweet_preview_api_enabled: true,
|
||||||
responsive_web_graphql_timeline_navigation_enabled: true,
|
responsive_web_graphql_timeline_navigation_enabled: true,
|
||||||
|
responsive_web_graphql_exclude_directive_enabled: true,
|
||||||
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
|
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
|
||||||
premium_content_api_read_enabled: false,
|
premium_content_api_read_enabled: false,
|
||||||
communities_web_enable_tweet_community_results_fetch: true,
|
communities_web_enable_tweet_community_results_fetch: true,
|
||||||
@@ -17,6 +18,7 @@ export function buildArticleFeatures(): Record<string, boolean> {
|
|||||||
responsive_web_grok_analyze_post_followups_enabled: false,
|
responsive_web_grok_analyze_post_followups_enabled: false,
|
||||||
responsive_web_grok_annotations_enabled: false,
|
responsive_web_grok_annotations_enabled: false,
|
||||||
responsive_web_jetfuel_frame: true,
|
responsive_web_jetfuel_frame: true,
|
||||||
|
post_ctas_fetch_enabled: true,
|
||||||
responsive_web_grok_share_attachment_enabled: true,
|
responsive_web_grok_share_attachment_enabled: true,
|
||||||
articles_preview_enabled: true,
|
articles_preview_enabled: true,
|
||||||
responsive_web_edit_tweet_api_enabled: true,
|
responsive_web_edit_tweet_api_enabled: true,
|
||||||
@@ -86,6 +88,7 @@ export function buildSearchFeatures(): Record<string, boolean> {
|
|||||||
responsive_web_grok_analyze_post_followups_enabled: false,
|
responsive_web_grok_analyze_post_followups_enabled: false,
|
||||||
responsive_web_grok_annotations_enabled: false,
|
responsive_web_grok_annotations_enabled: false,
|
||||||
responsive_web_jetfuel_frame: true,
|
responsive_web_jetfuel_frame: true,
|
||||||
|
post_ctas_fetch_enabled: true,
|
||||||
responsive_web_grok_share_attachment_enabled: true,
|
responsive_web_grok_share_attachment_enabled: true,
|
||||||
responsive_web_edit_tweet_api_enabled: true,
|
responsive_web_edit_tweet_api_enabled: true,
|
||||||
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
|
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
|
||||||
@@ -121,6 +124,7 @@ export function buildTweetCreateFeatures(): Record<string, boolean> {
|
|||||||
responsive_web_grok_analyze_post_followups_enabled: false,
|
responsive_web_grok_analyze_post_followups_enabled: false,
|
||||||
responsive_web_grok_annotations_enabled: false,
|
responsive_web_grok_annotations_enabled: false,
|
||||||
responsive_web_jetfuel_frame: true,
|
responsive_web_jetfuel_frame: true,
|
||||||
|
post_ctas_fetch_enabled: true,
|
||||||
responsive_web_grok_share_attachment_enabled: true,
|
responsive_web_grok_share_attachment_enabled: true,
|
||||||
responsive_web_edit_tweet_api_enabled: true,
|
responsive_web_edit_tweet_api_enabled: true,
|
||||||
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
|
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
|
||||||
@@ -184,6 +188,7 @@ export function buildListsFeatures(): Record<string, boolean> {
|
|||||||
verified_phone_label_enabled: false,
|
verified_phone_label_enabled: false,
|
||||||
creator_subscriptions_tweet_preview_api_enabled: true,
|
creator_subscriptions_tweet_preview_api_enabled: true,
|
||||||
responsive_web_graphql_timeline_navigation_enabled: true,
|
responsive_web_graphql_timeline_navigation_enabled: true,
|
||||||
|
responsive_web_graphql_exclude_directive_enabled: true,
|
||||||
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
|
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
|
||||||
premium_content_api_read_enabled: false,
|
premium_content_api_read_enabled: false,
|
||||||
communities_web_enable_tweet_community_results_fetch: true,
|
communities_web_enable_tweet_community_results_fetch: true,
|
||||||
@@ -192,6 +197,7 @@ export function buildListsFeatures(): Record<string, boolean> {
|
|||||||
responsive_web_grok_analyze_post_followups_enabled: false,
|
responsive_web_grok_analyze_post_followups_enabled: false,
|
||||||
responsive_web_grok_annotations_enabled: false,
|
responsive_web_grok_annotations_enabled: false,
|
||||||
responsive_web_jetfuel_frame: true,
|
responsive_web_jetfuel_frame: true,
|
||||||
|
post_ctas_fetch_enabled: true,
|
||||||
responsive_web_grok_share_attachment_enabled: true,
|
responsive_web_grok_share_attachment_enabled: true,
|
||||||
articles_preview_enabled: true,
|
articles_preview_enabled: true,
|
||||||
responsive_web_edit_tweet_api_enabled: true,
|
responsive_web_edit_tweet_api_enabled: true,
|
||||||
@@ -212,6 +218,58 @@ export function buildListsFeatures(): Record<string, boolean> {
|
|||||||
responsive_web_grok_imagine_annotation_enabled: true,
|
responsive_web_grok_imagine_annotation_enabled: true,
|
||||||
responsive_web_grok_community_note_auto_translation_is_enabled: false,
|
responsive_web_grok_community_note_auto_translation_is_enabled: false,
|
||||||
responsive_web_enhance_cards_enabled: false,
|
responsive_web_enhance_cards_enabled: false,
|
||||||
|
blue_business_profile_image_shape_enabled: false,
|
||||||
|
responsive_web_text_conversations_enabled: false,
|
||||||
|
tweetypie_unmention_optimization_enabled: true,
|
||||||
|
vibe_api_enabled: false,
|
||||||
|
interactive_text_enabled: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildHomeTimelineFeatures(): Record<string, boolean> {
|
||||||
|
return applyFeatureOverrides('homeTimeline', {
|
||||||
|
...buildTimelineFeatures(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function buildUserTweetsFeatures(): Record<string, boolean> {
|
||||||
|
return applyFeatureOverrides('userTweets', {
|
||||||
|
rweb_video_screen_enabled: false,
|
||||||
|
profile_label_improvements_pcf_label_in_post_enabled: true,
|
||||||
|
responsive_web_profile_redirect_enabled: false,
|
||||||
|
rweb_tipjar_consumption_enabled: true,
|
||||||
|
verified_phone_label_enabled: false,
|
||||||
|
creator_subscriptions_tweet_preview_api_enabled: true,
|
||||||
|
responsive_web_graphql_timeline_navigation_enabled: true,
|
||||||
|
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
|
||||||
|
premium_content_api_read_enabled: false,
|
||||||
|
communities_web_enable_tweet_community_results_fetch: true,
|
||||||
|
c9s_tweet_anatomy_moderator_badge_enabled: true,
|
||||||
|
responsive_web_grok_analyze_button_fetch_trends_enabled: false,
|
||||||
|
responsive_web_grok_analyze_post_followups_enabled: true,
|
||||||
|
responsive_web_jetfuel_frame: true,
|
||||||
|
post_ctas_fetch_enabled: true,
|
||||||
|
responsive_web_grok_share_attachment_enabled: true,
|
||||||
|
responsive_web_grok_annotations_enabled: false,
|
||||||
|
articles_preview_enabled: true,
|
||||||
|
responsive_web_edit_tweet_api_enabled: true,
|
||||||
|
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
|
||||||
|
view_counts_everywhere_api_enabled: true,
|
||||||
|
longform_notetweets_consumption_enabled: true,
|
||||||
|
responsive_web_twitter_article_tweet_consumption_enabled: true,
|
||||||
|
tweet_awards_web_tipping_enabled: false,
|
||||||
|
responsive_web_grok_show_grok_translated_post: true,
|
||||||
|
responsive_web_grok_analysis_button_from_backend: true,
|
||||||
|
creator_subscriptions_quote_tweet_preview_enabled: false,
|
||||||
|
freedom_of_speech_not_reach_fetch_enabled: true,
|
||||||
|
standardized_nudges_misinfo: true,
|
||||||
|
tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,
|
||||||
|
longform_notetweets_rich_text_read_enabled: true,
|
||||||
|
longform_notetweets_inline_media_enabled: true,
|
||||||
|
responsive_web_grok_image_annotation_enabled: true,
|
||||||
|
responsive_web_grok_imagine_annotation_enabled: true,
|
||||||
|
responsive_web_grok_community_note_auto_translation_is_enabled: false,
|
||||||
|
responsive_web_enhance_cards_enabled: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -232,6 +290,7 @@ export function buildFollowingFeatures(): Record<string, boolean> {
|
|||||||
responsive_web_grok_analyze_post_followups_enabled: false,
|
responsive_web_grok_analyze_post_followups_enabled: false,
|
||||||
responsive_web_grok_annotations_enabled: false,
|
responsive_web_grok_annotations_enabled: false,
|
||||||
responsive_web_jetfuel_frame: false,
|
responsive_web_jetfuel_frame: false,
|
||||||
|
post_ctas_fetch_enabled: true,
|
||||||
responsive_web_grok_share_attachment_enabled: false,
|
responsive_web_grok_share_attachment_enabled: false,
|
||||||
articles_preview_enabled: true,
|
articles_preview_enabled: true,
|
||||||
responsive_web_edit_tweet_api_enabled: true,
|
responsive_web_edit_tweet_api_enabled: true,
|
||||||
@@ -254,3 +313,47 @@ export function buildFollowingFeatures(): Record<string, boolean> {
|
|||||||
responsive_web_enhance_cards_enabled: false,
|
responsive_web_enhance_cards_enabled: false,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function buildExploreFeatures(): Record<string, boolean> {
|
||||||
|
return applyFeatureOverrides('explore', {
|
||||||
|
rweb_video_screen_enabled: true,
|
||||||
|
profile_label_improvements_pcf_label_in_post_enabled: true,
|
||||||
|
responsive_web_profile_redirect_enabled: true,
|
||||||
|
rweb_tipjar_consumption_enabled: true,
|
||||||
|
verified_phone_label_enabled: false,
|
||||||
|
creator_subscriptions_tweet_preview_api_enabled: true,
|
||||||
|
responsive_web_graphql_timeline_navigation_enabled: true,
|
||||||
|
responsive_web_graphql_exclude_directive_enabled: true,
|
||||||
|
responsive_web_graphql_skip_user_profile_image_extensions_enabled: false,
|
||||||
|
premium_content_api_read_enabled: false,
|
||||||
|
communities_web_enable_tweet_community_results_fetch: true,
|
||||||
|
c9s_tweet_anatomy_moderator_badge_enabled: true,
|
||||||
|
responsive_web_grok_analyze_button_fetch_trends_enabled: true,
|
||||||
|
responsive_web_grok_analyze_post_followups_enabled: true,
|
||||||
|
responsive_web_grok_annotations_enabled: true,
|
||||||
|
responsive_web_jetfuel_frame: true,
|
||||||
|
responsive_web_grok_share_attachment_enabled: true,
|
||||||
|
articles_preview_enabled: true,
|
||||||
|
responsive_web_edit_tweet_api_enabled: true,
|
||||||
|
graphql_is_translatable_rweb_tweet_is_translatable_enabled: true,
|
||||||
|
view_counts_everywhere_api_enabled: true,
|
||||||
|
longform_notetweets_consumption_enabled: true,
|
||||||
|
responsive_web_twitter_article_tweet_consumption_enabled: true,
|
||||||
|
tweet_awards_web_tipping_enabled: false,
|
||||||
|
responsive_web_grok_show_grok_translated_post: true,
|
||||||
|
responsive_web_grok_analysis_button_from_backend: true,
|
||||||
|
creator_subscriptions_quote_tweet_preview_enabled: false,
|
||||||
|
freedom_of_speech_not_reach_fetch_enabled: true,
|
||||||
|
standardized_nudges_misinfo: true,
|
||||||
|
tweet_with_visibility_results_prefer_gql_limited_actions_policy_enabled: true,
|
||||||
|
longform_notetweets_rich_text_read_enabled: true,
|
||||||
|
longform_notetweets_inline_media_enabled: true,
|
||||||
|
responsive_web_grok_image_annotation_enabled: true,
|
||||||
|
responsive_web_grok_imagine_annotation_enabled: true,
|
||||||
|
responsive_web_grok_community_note_auto_translation_is_enabled: true,
|
||||||
|
responsive_web_enhance_cards_enabled: false,
|
||||||
|
// Additional features required for ExploreSidebar
|
||||||
|
post_ctas_fetch_enabled: true,
|
||||||
|
rweb_video_timestamps_enabled: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||||
|
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
||||||
|
import { buildHomeTimelineFeatures } from './twitter-client-features.js';
|
||||||
|
import type { GraphqlTweetResult, SearchResult, TweetData } from './twitter-client-types.js';
|
||||||
|
import { extractCursorFromInstructions, parseTweetsFromInstructions } from './twitter-client-utils.js';
|
||||||
|
|
||||||
|
const QUERY_UNSPECIFIED_REGEX = /query:\s*unspecified/i;
|
||||||
|
|
||||||
|
function isQueryIdMismatch(errors: Array<{ message?: string }>): boolean {
|
||||||
|
return errors.some((error) => QUERY_UNSPECIFIED_REGEX.test(error.message ?? ''));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Options for home timeline fetch methods */
|
||||||
|
export interface HomeTimelineFetchOptions {
|
||||||
|
/** Include raw GraphQL response in `_raw` field */
|
||||||
|
includeRaw?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TwitterClientHomeMethods {
|
||||||
|
getHomeTimeline(count?: number, options?: HomeTimelineFetchOptions): Promise<SearchResult>;
|
||||||
|
getHomeLatestTimeline(count?: number, options?: HomeTimelineFetchOptions): Promise<SearchResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withHome<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||||
|
Base: TBase,
|
||||||
|
): Mixin<TBase, TwitterClientHomeMethods> {
|
||||||
|
abstract class TwitterClientHome extends Base {
|
||||||
|
// biome-ignore lint/complexity/noUselessConstructor lint/suspicious/noExplicitAny: TS mixin constructor requirement.
|
||||||
|
constructor(...args: any[]) {
|
||||||
|
super(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getHomeTimelineQueryIds(): Promise<string[]> {
|
||||||
|
const primary = await this.getQueryId('HomeTimeline');
|
||||||
|
return Array.from(new Set([primary, 'edseUwk9sP5Phz__9TIRnA']));
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getHomeLatestTimelineQueryIds(): Promise<string[]> {
|
||||||
|
const primary = await this.getQueryId('HomeLatestTimeline');
|
||||||
|
return Array.from(new Set([primary, 'iOEZpOdfekFsxSlPQCQtPg']));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the authenticated user's "For You" home timeline
|
||||||
|
*/
|
||||||
|
async getHomeTimeline(count = 20, options: HomeTimelineFetchOptions = {}): Promise<SearchResult> {
|
||||||
|
return this.fetchHomeTimeline('HomeTimeline', count, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get the authenticated user's "Following" (latest/chronological) home timeline
|
||||||
|
*/
|
||||||
|
async getHomeLatestTimeline(count = 20, options: HomeTimelineFetchOptions = {}): Promise<SearchResult> {
|
||||||
|
return this.fetchHomeTimeline('HomeLatestTimeline', count, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async fetchHomeTimeline(
|
||||||
|
operation: 'HomeTimeline' | 'HomeLatestTimeline',
|
||||||
|
count: number,
|
||||||
|
options: HomeTimelineFetchOptions,
|
||||||
|
): Promise<SearchResult> {
|
||||||
|
const { includeRaw = false } = options;
|
||||||
|
const features = buildHomeTimelineFeatures();
|
||||||
|
const pageSize = 20;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const tweets: TweetData[] = [];
|
||||||
|
let cursor: string | undefined;
|
||||||
|
|
||||||
|
const fetchPage = async (pageCount: number, pageCursor?: string) => {
|
||||||
|
let lastError: string | undefined;
|
||||||
|
let had404 = false;
|
||||||
|
const queryIds =
|
||||||
|
operation === 'HomeTimeline'
|
||||||
|
? await this.getHomeTimelineQueryIds()
|
||||||
|
: await this.getHomeLatestTimelineQueryIds();
|
||||||
|
|
||||||
|
for (const queryId of queryIds) {
|
||||||
|
const variables = {
|
||||||
|
count: pageCount,
|
||||||
|
includePromotedContent: true,
|
||||||
|
latestControlAvailable: true,
|
||||||
|
requestContext: 'launch',
|
||||||
|
withCommunity: true,
|
||||||
|
...(pageCursor ? { cursor: pageCursor } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
variables: JSON.stringify(variables),
|
||||||
|
features: JSON.stringify(features),
|
||||||
|
});
|
||||||
|
|
||||||
|
const url = `${TWITTER_API_BASE}/${queryId}/${operation}?${params.toString()}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.fetchWithTimeout(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: this.getHeaders(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 404) {
|
||||||
|
had404 = true;
|
||||||
|
lastError = `HTTP ${response.status}`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const text = await response.text();
|
||||||
|
return { success: false as const, error: `HTTP ${response.status}: ${text.slice(0, 200)}`, had404 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await response.json()) as {
|
||||||
|
data?: {
|
||||||
|
home?: {
|
||||||
|
home_timeline_urt?: {
|
||||||
|
instructions?: Array<{
|
||||||
|
entries?: Array<{
|
||||||
|
content?: {
|
||||||
|
itemContent?: {
|
||||||
|
tweet_results?: {
|
||||||
|
result?: GraphqlTweetResult;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
errors?: Array<{ message: string }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (data.errors && data.errors.length > 0) {
|
||||||
|
const errorMessage = data.errors.map((e) => e.message).join(', ');
|
||||||
|
return {
|
||||||
|
success: false as const,
|
||||||
|
error: errorMessage,
|
||||||
|
had404: had404 || isQueryIdMismatch(data.errors),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const instructions = data.data?.home?.home_timeline_urt?.instructions;
|
||||||
|
const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
|
||||||
|
const nextCursor = extractCursorFromInstructions(instructions);
|
||||||
|
|
||||||
|
return { success: true as const, tweets: pageTweets, cursor: nextCursor, had404 };
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false as const, error: lastError ?? 'Unknown error fetching home timeline', had404 };
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchWithRefresh = async (pageCount: number, pageCursor?: string) => {
|
||||||
|
const firstAttempt = await fetchPage(pageCount, pageCursor);
|
||||||
|
if (firstAttempt.success) {
|
||||||
|
return firstAttempt;
|
||||||
|
}
|
||||||
|
if (firstAttempt.had404) {
|
||||||
|
await this.refreshQueryIds();
|
||||||
|
const secondAttempt = await fetchPage(pageCount, pageCursor);
|
||||||
|
if (secondAttempt.success) {
|
||||||
|
return secondAttempt;
|
||||||
|
}
|
||||||
|
return { success: false as const, error: secondAttempt.error };
|
||||||
|
}
|
||||||
|
return { success: false as const, error: firstAttempt.error };
|
||||||
|
};
|
||||||
|
|
||||||
|
while (tweets.length < count) {
|
||||||
|
const pageCount = Math.min(pageSize, count - tweets.length);
|
||||||
|
const page = await fetchWithRefresh(pageCount, cursor);
|
||||||
|
if (!page.success) {
|
||||||
|
return { success: false, error: page.error };
|
||||||
|
}
|
||||||
|
|
||||||
|
let added = 0;
|
||||||
|
for (const tweet of page.tweets) {
|
||||||
|
if (seen.has(tweet.id)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(tweet.id);
|
||||||
|
tweets.push(tweet);
|
||||||
|
added += 1;
|
||||||
|
if (tweets.length >= count) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!page.cursor || page.cursor === cursor || page.tweets.length === 0 || added === 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cursor = page.cursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, tweets };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return TwitterClientHome;
|
||||||
|
}
|
||||||
@@ -4,14 +4,15 @@
|
|||||||
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||||
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
||||||
import { buildListsFeatures } from './twitter-client-features.js';
|
import { buildListsFeatures } from './twitter-client-features.js';
|
||||||
import type { TimelineFetchOptions } from './twitter-client-timelines.js';
|
import type { TimelineFetchOptions, TimelinePaginationOptions } from './twitter-client-timelines.js';
|
||||||
import type { GraphqlTweetResult, ListsResult, SearchResult, TwitterList } from './twitter-client-types.js';
|
import type { GraphqlTweetResult, ListsResult, SearchResult, TweetData, TwitterList } from './twitter-client-types.js';
|
||||||
import { parseTweetsFromInstructions } from './twitter-client-utils.js';
|
import { extractCursorFromInstructions, parseTweetsFromInstructions } from './twitter-client-utils.js';
|
||||||
|
|
||||||
export interface TwitterClientListMethods {
|
export interface TwitterClientListMethods {
|
||||||
getOwnedLists(count?: number): Promise<ListsResult>;
|
getOwnedLists(count?: number): Promise<ListsResult>;
|
||||||
getListMemberships(count?: number): Promise<ListsResult>;
|
getListMemberships(count?: number): Promise<ListsResult>;
|
||||||
getListTimeline(listId: string, count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
|
getListTimeline(listId: string, count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
|
||||||
|
getAllListTimeline(listId: string, options?: TimelinePaginationOptions): Promise<SearchResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface GraphqlListResult {
|
interface GraphqlListResult {
|
||||||
@@ -329,25 +330,49 @@ export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
* Get tweets from a list timeline
|
* Get tweets from a list timeline
|
||||||
*/
|
*/
|
||||||
async getListTimeline(listId: string, count = 20, options: TimelineFetchOptions = {}): Promise<SearchResult> {
|
async getListTimeline(listId: string, count = 20, options: TimelineFetchOptions = {}): Promise<SearchResult> {
|
||||||
const { includeRaw = false } = options;
|
return this.getListTimelinePaged(listId, count, options);
|
||||||
|
}
|
||||||
|
|
||||||
const variables = {
|
/**
|
||||||
listId,
|
* Get all tweets from a list timeline (paginated)
|
||||||
count,
|
*/
|
||||||
};
|
async getAllListTimeline(listId: string, options?: TimelinePaginationOptions): Promise<SearchResult> {
|
||||||
|
return this.getListTimelinePaged(listId, Number.POSITIVE_INFINITY, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Internal paginated list timeline fetcher
|
||||||
|
*/
|
||||||
|
private async getListTimelinePaged(
|
||||||
|
listId: string,
|
||||||
|
limit: number,
|
||||||
|
options: TimelinePaginationOptions = {},
|
||||||
|
): Promise<SearchResult> {
|
||||||
const features = buildListsFeatures();
|
const features = buildListsFeatures();
|
||||||
|
const pageSize = 20;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const tweets: TweetData[] = [];
|
||||||
|
let cursor: string | undefined = options.cursor;
|
||||||
|
let nextCursor: string | undefined;
|
||||||
|
let pagesFetched = 0;
|
||||||
|
const { includeRaw = false, maxPages } = options;
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
const fetchPage = async (pageCount: number, pageCursor?: string) => {
|
||||||
variables: JSON.stringify(variables),
|
|
||||||
features: JSON.stringify(features),
|
|
||||||
});
|
|
||||||
|
|
||||||
const tryOnce = async () => {
|
|
||||||
let lastError: string | undefined;
|
let lastError: string | undefined;
|
||||||
let had404 = false;
|
let had404 = false;
|
||||||
const queryIds = await this.getListTimelineQueryIds();
|
const queryIds = await this.getListTimelineQueryIds();
|
||||||
|
|
||||||
|
const variables = {
|
||||||
|
listId,
|
||||||
|
count: pageCount,
|
||||||
|
...(pageCursor ? { cursor: pageCursor } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
variables: JSON.stringify(variables),
|
||||||
|
features: JSON.stringify(features),
|
||||||
|
});
|
||||||
|
|
||||||
for (const queryId of queryIds) {
|
for (const queryId of queryIds) {
|
||||||
const url = `${TWITTER_API_BASE}/${queryId}/ListLatestTweetsTimeline?${params.toString()}`;
|
const url = `${TWITTER_API_BASE}/${queryId}/ListLatestTweetsTimeline?${params.toString()}`;
|
||||||
|
|
||||||
@@ -396,9 +421,10 @@ export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const instructions = data.data?.list?.tweets_timeline?.timeline?.instructions;
|
const instructions = data.data?.list?.tweets_timeline?.timeline?.instructions;
|
||||||
const tweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
|
const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
|
||||||
|
const nextCursor = extractCursorFromInstructions(instructions);
|
||||||
|
|
||||||
return { success: true as const, tweets, had404 };
|
return { success: true as const, tweets: pageTweets, cursor: nextCursor, had404 };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error instanceof Error ? error.message : String(error);
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
}
|
}
|
||||||
@@ -407,21 +433,58 @@ export function withLists<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
return { success: false as const, error: lastError ?? 'Unknown error fetching list timeline', had404 };
|
return { success: false as const, error: lastError ?? 'Unknown error fetching list timeline', had404 };
|
||||||
};
|
};
|
||||||
|
|
||||||
const firstAttempt = await tryOnce();
|
const fetchWithRefresh = async (pageCount: number, pageCursor?: string) => {
|
||||||
if (firstAttempt.success) {
|
const firstAttempt = await fetchPage(pageCount, pageCursor);
|
||||||
return { success: true, tweets: firstAttempt.tweets };
|
if (firstAttempt.success) {
|
||||||
}
|
return firstAttempt;
|
||||||
|
|
||||||
if (firstAttempt.had404) {
|
|
||||||
await this.refreshQueryIds();
|
|
||||||
const secondAttempt = await tryOnce();
|
|
||||||
if (secondAttempt.success) {
|
|
||||||
return { success: true, tweets: secondAttempt.tweets };
|
|
||||||
}
|
}
|
||||||
return { success: false, error: secondAttempt.error };
|
if (firstAttempt.had404) {
|
||||||
|
await this.refreshQueryIds();
|
||||||
|
const secondAttempt = await fetchPage(pageCount, pageCursor);
|
||||||
|
if (secondAttempt.success) {
|
||||||
|
return secondAttempt;
|
||||||
|
}
|
||||||
|
return { success: false as const, error: secondAttempt.error };
|
||||||
|
}
|
||||||
|
return { success: false as const, error: firstAttempt.error };
|
||||||
|
};
|
||||||
|
|
||||||
|
const unlimited = limit === Number.POSITIVE_INFINITY;
|
||||||
|
while (unlimited || tweets.length < limit) {
|
||||||
|
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - 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) {
|
||||||
|
if (seen.has(tweet.id)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(tweet.id);
|
||||||
|
tweets.push(tweet);
|
||||||
|
added += 1;
|
||||||
|
if (!unlimited && tweets.length >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageCursor = page.cursor;
|
||||||
|
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0 || added === 0) {
|
||||||
|
nextCursor = undefined;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (maxPages && pagesFetched >= maxPages) {
|
||||||
|
nextCursor = pageCursor;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cursor = pageCursor;
|
||||||
|
nextCursor = pageCursor;
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success: false, error: firstAttempt.error };
|
return { success: true, tweets, nextCursor };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,10 +28,6 @@ export function withMedia<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
private async sleep(ms: number): Promise<void> {
|
|
||||||
await new Promise((resolve) => setTimeout(resolve, ms));
|
|
||||||
}
|
|
||||||
|
|
||||||
async uploadMedia(input: { data: Uint8Array; mimeType: string; alt?: string }): Promise<UploadMediaResult> {
|
async uploadMedia(input: { data: Uint8Array; mimeType: string; alt?: string }): Promise<UploadMediaResult> {
|
||||||
const category = this.mediaCategoryForMime(input.mimeType);
|
const category = this.mediaCategoryForMime(input.mimeType);
|
||||||
if (!category) {
|
if (!category) {
|
||||||
|
|||||||
@@ -0,0 +1,430 @@
|
|||||||
|
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||||
|
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
||||||
|
import { buildExploreFeatures } from './twitter-client-features.js';
|
||||||
|
import type { SearchResult, TweetData } from './twitter-client-types.js';
|
||||||
|
|
||||||
|
const POST_COUNT_REGEX = /[\d.]+[KMB]?\s*posts?/i;
|
||||||
|
const POST_COUNT_MATCH_REGEX = /([\d.]+)([KMB]?)\s*posts?/i;
|
||||||
|
|
||||||
|
// Timeline IDs for different Explore tabs
|
||||||
|
const TIMELINE_IDS = {
|
||||||
|
forYou: 'VGltZWxpbmU6DAC2CwABAAAAB2Zvcl95b3UAAA==',
|
||||||
|
trending: 'VGltZWxpbmU6DAC2CwABAAAACHRyZW5kaW5nAAA=',
|
||||||
|
news: 'VGltZWxpbmU6DAC2CwABAAAABG5ld3MAAA==',
|
||||||
|
sports: 'VGltZWxpbmU6DAC2CwABAAAABnNwb3J0cwAA',
|
||||||
|
entertainment: 'VGltZWxpbmU6DAC2CwABAAAADWVudGVydGFpbm1lbnQAAA==',
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export type ExploreTab = keyof typeof TIMELINE_IDS;
|
||||||
|
|
||||||
|
/** Options for news fetch methods */
|
||||||
|
export interface NewsFetchOptions {
|
||||||
|
/** Include raw GraphQL response in `_raw` field */
|
||||||
|
includeRaw?: boolean;
|
||||||
|
/** Also fetch related tweets for each news item */
|
||||||
|
withTweets?: boolean;
|
||||||
|
/** Number of tweets to fetch per news item (default: 5) */
|
||||||
|
tweetsPerItem?: number;
|
||||||
|
/** Filter to show only AI-curated news items */
|
||||||
|
aiOnly?: boolean;
|
||||||
|
/** Fetch from specific tabs only (default: all tabs) */
|
||||||
|
tabs?: ExploreTab[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NewsItem {
|
||||||
|
id: string;
|
||||||
|
headline: string;
|
||||||
|
category?: string;
|
||||||
|
timeAgo?: string;
|
||||||
|
postCount?: number;
|
||||||
|
description?: string;
|
||||||
|
url?: string;
|
||||||
|
tweets?: TweetData[];
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: Raw API response can have any structure
|
||||||
|
_raw?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type NewsResult =
|
||||||
|
| {
|
||||||
|
success: true;
|
||||||
|
items: NewsItem[];
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
success: false;
|
||||||
|
error: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export interface TwitterClientNewsMethods {
|
||||||
|
getNews(count?: number, options?: NewsFetchOptions): Promise<NewsResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withNews<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||||
|
Base: TBase,
|
||||||
|
): Mixin<TBase, TwitterClientNewsMethods> {
|
||||||
|
abstract class TwitterClientNews extends Base {
|
||||||
|
// biome-ignore lint/complexity/noUselessConstructor lint/suspicious/noExplicitAny: TS mixin constructor requirement.
|
||||||
|
constructor(...args: any[]) {
|
||||||
|
super(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch news and trending topics from Twitter's Explore page tabs
|
||||||
|
*/
|
||||||
|
async getNews(count = 10, options: NewsFetchOptions = {}): Promise<NewsResult> {
|
||||||
|
const {
|
||||||
|
includeRaw = false,
|
||||||
|
withTweets = false,
|
||||||
|
tweetsPerItem = 5,
|
||||||
|
aiOnly = false,
|
||||||
|
tabs = ['forYou', 'news', 'sports', 'entertainment'],
|
||||||
|
} = options;
|
||||||
|
|
||||||
|
const debug = process.env.BIRD_DEBUG === '1';
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
console.error(`[getNews] Fetching from tabs: ${tabs.join(', ')}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const allItems: NewsItem[] = [];
|
||||||
|
const seenHeadlines = new Set<string>();
|
||||||
|
|
||||||
|
// Fetch from each tab
|
||||||
|
for (const tab of tabs) {
|
||||||
|
const timelineId = TIMELINE_IDS[tab];
|
||||||
|
if (!timelineId) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const tabItems = await this.fetchTimelineTab(tab, timelineId, count, aiOnly, includeRaw);
|
||||||
|
|
||||||
|
// Deduplicate across tabs
|
||||||
|
for (const item of tabItems) {
|
||||||
|
if (!seenHeadlines.has(item.headline)) {
|
||||||
|
seenHeadlines.add(item.headline);
|
||||||
|
allItems.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (debug) {
|
||||||
|
console.error(`[getNews] Tab ${tab}: found ${tabItems.length} items, total unique: ${allItems.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stop early if we have enough
|
||||||
|
if (allItems.length >= count) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (debug) {
|
||||||
|
console.error(`[getNews] Error fetching tab ${tab}:`, error);
|
||||||
|
}
|
||||||
|
// Continue with other tabs
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allItems.length === 0) {
|
||||||
|
return { success: false, error: 'No news items found' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Limit to requested count
|
||||||
|
const items = allItems.slice(0, count);
|
||||||
|
|
||||||
|
if (withTweets) {
|
||||||
|
await this.enrichWithTweets(items, tweetsPerItem, includeRaw);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, items };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch a specific timeline tab using GenericTimelineById
|
||||||
|
*/
|
||||||
|
private async fetchTimelineTab(
|
||||||
|
tabName: string,
|
||||||
|
timelineId: string,
|
||||||
|
maxCount: number,
|
||||||
|
aiOnly: boolean,
|
||||||
|
includeRaw: boolean,
|
||||||
|
): Promise<NewsItem[]> {
|
||||||
|
const queryId = await this.getQueryId('GenericTimelineById');
|
||||||
|
const features = buildExploreFeatures();
|
||||||
|
|
||||||
|
const variables = {
|
||||||
|
timelineId: timelineId,
|
||||||
|
count: maxCount * 2, // Fetch more to account for filtering
|
||||||
|
includePromotedContent: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
variables: JSON.stringify(variables),
|
||||||
|
features: JSON.stringify(features),
|
||||||
|
});
|
||||||
|
|
||||||
|
const url = `${TWITTER_API_BASE}/${queryId}/GenericTimelineById?${params.toString()}`;
|
||||||
|
|
||||||
|
const response = await this.fetchWithTimeout(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: this.getHeaders(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const text = await response.text();
|
||||||
|
throw new Error(`HTTP ${response.status}: ${text.slice(0, 200)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await response.json()) as {
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: API response structure is complex
|
||||||
|
data?: any;
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: API errors can have any structure
|
||||||
|
errors?: Array<{ message: string; code?: number; [key: string]: any }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Debug: save response if BIRD_DEBUG_JSON is set
|
||||||
|
if (process.env.BIRD_DEBUG_JSON) {
|
||||||
|
const fs = await import('node:fs/promises');
|
||||||
|
const debugPath = process.env.BIRD_DEBUG_JSON.replace('.json', `-${tabName}.json`);
|
||||||
|
await fs.writeFile(debugPath, JSON.stringify(data, null, 2)).catch(() => {});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.errors && data.errors.length > 0) {
|
||||||
|
throw new Error(data.errors.map((e) => e.message).join('; '));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse timeline response
|
||||||
|
return this.parseTimelineTabItems(data, tabName, maxCount, aiOnly, includeRaw);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse items from a GenericTimelineById response
|
||||||
|
*/
|
||||||
|
private parseTimelineTabItems(
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: API response structure is complex
|
||||||
|
data: any,
|
||||||
|
source: string,
|
||||||
|
maxCount: number,
|
||||||
|
aiOnly: boolean,
|
||||||
|
includeRaw: boolean,
|
||||||
|
): NewsItem[] {
|
||||||
|
const items: NewsItem[] = [];
|
||||||
|
const seenHeadlines = new Set<string>();
|
||||||
|
|
||||||
|
// Navigate to timeline instructions
|
||||||
|
const timeline = data?.data?.timeline?.timeline;
|
||||||
|
if (!timeline) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
const instructions = timeline.instructions || [];
|
||||||
|
|
||||||
|
for (const instruction of instructions) {
|
||||||
|
const entries = instruction.entries ?? (instruction.entry ? [instruction.entry] : []);
|
||||||
|
if (!entries || entries.length === 0) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (items.length >= maxCount) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
const content = entry.content;
|
||||||
|
if (!content) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle TimelineTimelineItem (single trend item)
|
||||||
|
if (content.itemContent) {
|
||||||
|
const newsItem = this.parseNewsItemFromContent(
|
||||||
|
content.itemContent,
|
||||||
|
entry.entryId,
|
||||||
|
source,
|
||||||
|
seenHeadlines,
|
||||||
|
aiOnly,
|
||||||
|
includeRaw,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (newsItem) {
|
||||||
|
items.push(newsItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle TimelineTimelineModule (multiple items)
|
||||||
|
const itemsArray = content?.items || [];
|
||||||
|
|
||||||
|
for (const data of itemsArray) {
|
||||||
|
if (items.length >= maxCount) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Structure can be data.itemContent OR data.item.itemContent
|
||||||
|
const itemContent = data?.itemContent || data?.item?.itemContent;
|
||||||
|
if (!itemContent) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const newsItem = this.parseNewsItemFromContent(
|
||||||
|
itemContent,
|
||||||
|
entry.entryId,
|
||||||
|
source,
|
||||||
|
seenHeadlines,
|
||||||
|
aiOnly,
|
||||||
|
includeRaw,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (newsItem) {
|
||||||
|
items.push(newsItem);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return items;
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseNewsItemFromContent(
|
||||||
|
// biome-ignore lint/suspicious/noExplicitAny: API response structure is complex
|
||||||
|
itemContent: any,
|
||||||
|
entryId: string,
|
||||||
|
source: string,
|
||||||
|
seenHeadlines: Set<string>,
|
||||||
|
aiOnly: boolean,
|
||||||
|
includeRaw: boolean,
|
||||||
|
): NewsItem | null {
|
||||||
|
const headline = itemContent.name || itemContent.title;
|
||||||
|
|
||||||
|
if (!headline) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const trendMetadata = itemContent?.trend_metadata;
|
||||||
|
const trendUrl = itemContent.trend_url?.url || trendMetadata?.url?.url;
|
||||||
|
|
||||||
|
// Detect AI news by characteristics:
|
||||||
|
// 1. Full sentence headlines (contains spaces and is longer)
|
||||||
|
// 2. Has social_context with "News" category
|
||||||
|
// 3. Or explicitly marked as is_ai_trend
|
||||||
|
const socialContext = itemContent?.social_context?.text || '';
|
||||||
|
const hasNewsCategory = socialContext.includes('News') || socialContext.includes('hours ago');
|
||||||
|
const isFullSentence = headline.split(' ').length >= 5; // AI news are full sentences
|
||||||
|
const isExplicitlyAiTrend = itemContent.is_ai_trend === true;
|
||||||
|
|
||||||
|
const isAiNews = isExplicitlyAiTrend || (isFullSentence && hasNewsCategory);
|
||||||
|
|
||||||
|
// Filter AI trends if aiOnly is enabled
|
||||||
|
if (aiOnly && !isAiNews) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (seenHeadlines.has(headline)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
seenHeadlines.add(headline);
|
||||||
|
|
||||||
|
let postCount: number | undefined;
|
||||||
|
let timeAgo: string | undefined;
|
||||||
|
let category = 'Trending';
|
||||||
|
|
||||||
|
// Parse social context for metadata
|
||||||
|
const socialCtx = itemContent?.social_context;
|
||||||
|
if (socialCtx?.text) {
|
||||||
|
const socialContextText = socialCtx.text;
|
||||||
|
const parts = socialContextText.split('·').map((s: string) => s.trim());
|
||||||
|
|
||||||
|
for (const part of parts) {
|
||||||
|
if (part.includes('ago')) {
|
||||||
|
timeAgo = part;
|
||||||
|
} else if (part.match(POST_COUNT_REGEX)) {
|
||||||
|
const match = part.match(POST_COUNT_MATCH_REGEX);
|
||||||
|
if (match) {
|
||||||
|
let num = Number.parseFloat(match[1]);
|
||||||
|
const suffix = match[2]?.toUpperCase();
|
||||||
|
|
||||||
|
if (suffix === 'K') {
|
||||||
|
num *= 1000;
|
||||||
|
} else if (suffix === 'M') {
|
||||||
|
num *= 1_000_000;
|
||||||
|
} else if (suffix === 'B') {
|
||||||
|
num *= 1_000_000_000;
|
||||||
|
}
|
||||||
|
|
||||||
|
postCount = Math.round(num);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
category = part;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse trend metadata
|
||||||
|
if (trendMetadata?.meta_description) {
|
||||||
|
const metaDesc = trendMetadata.meta_description;
|
||||||
|
const postMatch = metaDesc.match(POST_COUNT_MATCH_REGEX);
|
||||||
|
if (postMatch) {
|
||||||
|
let num = Number.parseFloat(postMatch[1]);
|
||||||
|
const suffix = postMatch[2]?.toUpperCase();
|
||||||
|
|
||||||
|
if (suffix === 'K') {
|
||||||
|
num *= 1000;
|
||||||
|
} else if (suffix === 'M') {
|
||||||
|
num *= 1_000_000;
|
||||||
|
} else if (suffix === 'B') {
|
||||||
|
num *= 1_000_000_000;
|
||||||
|
}
|
||||||
|
|
||||||
|
postCount = Math.round(num);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (trendMetadata?.domain_context && (category === 'Trending' || category === 'News')) {
|
||||||
|
category = trendMetadata.domain_context;
|
||||||
|
}
|
||||||
|
|
||||||
|
const item: NewsItem = {
|
||||||
|
id: trendUrl ?? (entryId ? `${entryId}-${headline}` : `${source}-${headline}`),
|
||||||
|
headline,
|
||||||
|
category: isAiNews ? `AI · ${category}` : category,
|
||||||
|
timeAgo,
|
||||||
|
postCount,
|
||||||
|
description: itemContent.description,
|
||||||
|
url: trendUrl,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (includeRaw) {
|
||||||
|
item._raw = itemContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
return item;
|
||||||
|
}
|
||||||
|
|
||||||
|
private async enrichWithTweets(items: NewsItem[], tweetsPerItem: number, includeRaw: boolean): Promise<void> {
|
||||||
|
const debug = process.env.BIRD_DEBUG === '1';
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
try {
|
||||||
|
const searchQuery = item.headline;
|
||||||
|
if (!searchQuery) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use the search method if available (requires search mixin)
|
||||||
|
if ('search' in this && typeof (this as { search?: unknown }).search === 'function') {
|
||||||
|
const result = (await (
|
||||||
|
this as { search: (q: string, c: number, o: { includeRaw: boolean }) => Promise<SearchResult> }
|
||||||
|
).search(searchQuery, tweetsPerItem, { includeRaw })) as SearchResult;
|
||||||
|
|
||||||
|
if (result.success && result.tweets) {
|
||||||
|
item.tweets = result.tweets;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
if (debug) {
|
||||||
|
console.error('[getNews] Failed to enrich item with tweets:', item.headline);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return TwitterClientNews;
|
||||||
|
}
|
||||||
@@ -71,7 +71,7 @@ export function withPosting<TBase extends AbstractConstructor<TwitterClientBase>
|
|||||||
let body = buildBody();
|
let body = buildBody();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const headers = { ...this.getHeaders(), referer: 'https://x.com/compose/post' };
|
const headers = this.getJsonHeaders();
|
||||||
let response = await this.fetchWithTimeout(urlWithOperation, {
|
let response = await this.fetchWithTimeout(urlWithOperation, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
@@ -88,14 +88,14 @@ export function withPosting<TBase extends AbstractConstructor<TwitterClientBase>
|
|||||||
|
|
||||||
response = await this.fetchWithTimeout(urlWithOperation, {
|
response = await this.fetchWithTimeout(urlWithOperation, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { ...this.getHeaders(), referer: 'https://x.com/compose/post' },
|
headers,
|
||||||
body,
|
body,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.status === 404) {
|
if (response.status === 404) {
|
||||||
const retry = await this.fetchWithTimeout(TWITTER_GRAPHQL_POST_URL, {
|
const retry = await this.fetchWithTimeout(TWITTER_GRAPHQL_POST_URL, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { ...this.getHeaders(), referer: 'https://x.com/compose/post' },
|
headers,
|
||||||
body,
|
body,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -224,12 +224,8 @@ export function withPosting<TBase extends AbstractConstructor<TwitterClientBase>
|
|||||||
try {
|
try {
|
||||||
const response = await this.fetchWithTimeout(TWITTER_STATUS_UPDATE_URL, {
|
const response = await this.fetchWithTimeout(TWITTER_STATUS_UPDATE_URL, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: this.getHeaders(),
|
||||||
...this.getBaseHeaders(),
|
body: params,
|
||||||
'content-type': 'application/x-www-form-urlencoded',
|
|
||||||
referer: 'https://x.com/compose/post',
|
|
||||||
},
|
|
||||||
body: params.toString(),
|
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
|
|||||||
@@ -4,14 +4,45 @@ import { buildSearchFeatures } from './twitter-client-features.js';
|
|||||||
import type { SearchResult, TweetData } from './twitter-client-types.js';
|
import type { SearchResult, TweetData } from './twitter-client-types.js';
|
||||||
import { extractCursorFromInstructions, parseTweetsFromInstructions } from './twitter-client-utils.js';
|
import { extractCursorFromInstructions, parseTweetsFromInstructions } from './twitter-client-utils.js';
|
||||||
|
|
||||||
|
const RAW_QUERY_MISSING_REGEX = /must be defined/i;
|
||||||
|
|
||||||
/** Options for search methods */
|
/** Options for search methods */
|
||||||
export interface SearchFetchOptions {
|
export interface SearchFetchOptions {
|
||||||
/** Include raw GraphQL response in `_raw` field */
|
/** Include raw GraphQL response in `_raw` field */
|
||||||
includeRaw?: boolean;
|
includeRaw?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Options for paged search methods */
|
||||||
|
export interface SearchPaginationOptions extends SearchFetchOptions {
|
||||||
|
maxPages?: number;
|
||||||
|
/** Starting cursor for pagination (resume from previous fetch) */
|
||||||
|
cursor?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface TwitterClientSearchMethods {
|
export interface TwitterClientSearchMethods {
|
||||||
search(query: string, count?: number, options?: SearchFetchOptions): Promise<SearchResult>;
|
search(query: string, count?: number, options?: SearchFetchOptions): Promise<SearchResult>;
|
||||||
|
getAllSearchResults(query: string, options?: SearchPaginationOptions): Promise<SearchResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isQueryIdMismatch(payload: string): boolean {
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(payload) as {
|
||||||
|
errors?: Array<{ message?: string; path?: string[]; extensions?: { code?: string } }>;
|
||||||
|
};
|
||||||
|
return (
|
||||||
|
parsed.errors?.some((error) => {
|
||||||
|
if (error?.extensions?.code === 'GRAPHQL_VALIDATION_FAILED') {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (error?.path?.includes('rawQuery') && RAW_QUERY_MISSING_REGEX.test(error.message ?? '')) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}) ?? false
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>(
|
export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||||
@@ -27,12 +58,29 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
|
|||||||
* Search for tweets matching a query
|
* Search for tweets matching a query
|
||||||
*/
|
*/
|
||||||
async search(query: string, count = 20, options: SearchFetchOptions = {}): Promise<SearchResult> {
|
async search(query: string, count = 20, options: SearchFetchOptions = {}): Promise<SearchResult> {
|
||||||
const { includeRaw = false } = options;
|
return this.searchPaged(query, count, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get all search results (paged)
|
||||||
|
*/
|
||||||
|
async getAllSearchResults(query: string, options?: SearchPaginationOptions): Promise<SearchResult> {
|
||||||
|
return this.searchPaged(query, Number.POSITIVE_INFINITY, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async searchPaged(
|
||||||
|
query: string,
|
||||||
|
limit: number,
|
||||||
|
options: SearchPaginationOptions = {},
|
||||||
|
): Promise<SearchResult> {
|
||||||
const features = buildSearchFeatures();
|
const features = buildSearchFeatures();
|
||||||
const pageSize = 20;
|
const pageSize = 20;
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
const tweets: TweetData[] = [];
|
const tweets: TweetData[] = [];
|
||||||
let cursor: string | undefined;
|
let cursor: string | undefined = options.cursor;
|
||||||
|
let nextCursor: string | undefined;
|
||||||
|
let pagesFetched = 0;
|
||||||
|
const { includeRaw = false, maxPages } = options;
|
||||||
|
|
||||||
const fetchPage = async (pageCount: number, pageCursor?: string) => {
|
const fetchPage = async (pageCount: number, pageCursor?: string) => {
|
||||||
let lastError: string | undefined;
|
let lastError: string | undefined;
|
||||||
@@ -57,7 +105,7 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
|
|||||||
try {
|
try {
|
||||||
const response = await this.fetchWithTimeout(url, {
|
const response = await this.fetchWithTimeout(url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: this.getHeaders(),
|
headers: this.getJsonHeaders(),
|
||||||
body: JSON.stringify({ features, queryId }),
|
body: JSON.stringify({ features, queryId }),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -69,7 +117,13 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
|
|||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
const text = await response.text();
|
const text = await response.text();
|
||||||
return { success: false as const, error: `HTTP ${response.status}: ${text.slice(0, 200)}`, had404 };
|
const shouldRefreshQueryIds =
|
||||||
|
(response.status === 400 || response.status === 422) && isQueryIdMismatch(text);
|
||||||
|
return {
|
||||||
|
success: false as const,
|
||||||
|
error: `HTTP ${response.status}: ${text.slice(0, 200)}`,
|
||||||
|
had404: had404 || shouldRefreshQueryIds,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const data = (await response.json()) as {
|
const data = (await response.json()) as {
|
||||||
@@ -112,11 +166,18 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
errors?: Array<{ message: string }>;
|
errors?: Array<{ message: string; extensions?: { code?: string } }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (data.errors && data.errors.length > 0) {
|
if (data.errors && data.errors.length > 0) {
|
||||||
return { success: false as const, error: data.errors.map((e) => e.message).join(', '), had404 };
|
const shouldRefreshQueryIds = data.errors.some(
|
||||||
|
(error) => error?.extensions?.code === 'GRAPHQL_VALIDATION_FAILED',
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
success: false as const,
|
||||||
|
error: data.errors.map((e) => e.message).join(', '),
|
||||||
|
had404: had404 || shouldRefreshQueryIds,
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const instructions = data.data?.search_by_raw_query?.search_timeline?.timeline?.instructions;
|
const instructions = data.data?.search_by_raw_query?.search_timeline?.timeline?.instructions;
|
||||||
@@ -148,31 +209,42 @@ export function withSearch<TBase extends AbstractConstructor<TwitterClientBase>>
|
|||||||
return { success: false as const, error: firstAttempt.error };
|
return { success: false as const, error: firstAttempt.error };
|
||||||
};
|
};
|
||||||
|
|
||||||
while (tweets.length < count) {
|
const unlimited = limit === Number.POSITIVE_INFINITY;
|
||||||
const pageCount = Math.min(pageSize, count - tweets.length);
|
while (unlimited || tweets.length < limit) {
|
||||||
|
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
|
||||||
const page = await fetchWithRefresh(pageCount, cursor);
|
const page = await fetchWithRefresh(pageCount, cursor);
|
||||||
if (!page.success) {
|
if (!page.success) {
|
||||||
return { success: false, error: page.error };
|
return { success: false, error: page.error };
|
||||||
}
|
}
|
||||||
|
pagesFetched += 1;
|
||||||
|
|
||||||
|
let added = 0;
|
||||||
for (const tweet of page.tweets) {
|
for (const tweet of page.tweets) {
|
||||||
if (seen.has(tweet.id)) {
|
if (seen.has(tweet.id)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
seen.add(tweet.id);
|
seen.add(tweet.id);
|
||||||
tweets.push(tweet);
|
tweets.push(tweet);
|
||||||
if (tweets.length >= count) {
|
added += 1;
|
||||||
|
if (!unlimited && tweets.length >= limit) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!page.cursor || page.cursor === cursor || page.tweets.length === 0) {
|
const pageCursor = page.cursor;
|
||||||
|
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0 || added === 0) {
|
||||||
|
nextCursor = undefined;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
cursor = page.cursor;
|
if (maxPages && pagesFetched >= maxPages) {
|
||||||
|
nextCursor = pageCursor;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cursor = pageCursor;
|
||||||
|
nextCursor = pageCursor;
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success: true, tweets };
|
return { success: true, tweets, nextCursor };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export interface TwitterClientTimelineMethods {
|
|||||||
getBookmarks(count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
|
getBookmarks(count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
|
||||||
getAllBookmarks(options?: TimelinePaginationOptions): Promise<SearchResult>;
|
getAllBookmarks(options?: TimelinePaginationOptions): Promise<SearchResult>;
|
||||||
getLikes(count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
|
getLikes(count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
|
||||||
|
getAllLikes(options?: TimelinePaginationOptions): Promise<SearchResult>;
|
||||||
getBookmarkFolderTimeline(folderId: string, count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
|
getBookmarkFolderTimeline(folderId: string, count?: number, options?: TimelineFetchOptions): Promise<SearchResult>;
|
||||||
getAllBookmarkFolderTimeline(folderId: string, options?: TimelinePaginationOptions): Promise<SearchResult>;
|
getAllBookmarkFolderTimeline(folderId: string, options?: TimelinePaginationOptions): Promise<SearchResult>;
|
||||||
}
|
}
|
||||||
@@ -75,34 +76,48 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
* Get the authenticated user's liked tweets
|
* Get the authenticated user's liked tweets
|
||||||
*/
|
*/
|
||||||
async getLikes(count = 20, options: TimelineFetchOptions = {}): Promise<SearchResult> {
|
async getLikes(count = 20, options: TimelineFetchOptions = {}): Promise<SearchResult> {
|
||||||
const { includeRaw = false } = options;
|
return this.getLikesPaged(count, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAllLikes(options?: TimelinePaginationOptions): Promise<SearchResult> {
|
||||||
|
return this.getLikesPaged(Number.POSITIVE_INFINITY, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getLikesPaged(limit: number, options: TimelinePaginationOptions = {}): Promise<SearchResult> {
|
||||||
const userResult = await this.getCurrentUser();
|
const userResult = await this.getCurrentUser();
|
||||||
if (!userResult.success || !userResult.user) {
|
if (!userResult.success || !userResult.user) {
|
||||||
return { success: false, error: userResult.error ?? 'Could not determine current user' };
|
return { success: false, error: userResult.error ?? 'Could not determine current user' };
|
||||||
}
|
}
|
||||||
|
const userId = userResult.user.id;
|
||||||
const variables = {
|
|
||||||
userId: userResult.user.id,
|
|
||||||
count,
|
|
||||||
includePromotedContent: false,
|
|
||||||
withClientEventToken: false,
|
|
||||||
withBirdwatchNotes: false,
|
|
||||||
withVoice: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
const features = buildLikesFeatures();
|
const features = buildLikesFeatures();
|
||||||
|
const pageSize = 20;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const tweets: TweetData[] = [];
|
||||||
|
let cursor: string | undefined = options.cursor;
|
||||||
|
let nextCursor: string | undefined;
|
||||||
|
let pagesFetched = 0;
|
||||||
|
const { includeRaw = false, maxPages } = options;
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
const fetchPage = async (pageCount: number, pageCursor?: string) => {
|
||||||
variables: JSON.stringify(variables),
|
|
||||||
features: JSON.stringify(features),
|
|
||||||
});
|
|
||||||
|
|
||||||
const tryOnce = async () => {
|
|
||||||
let lastError: string | undefined;
|
let lastError: string | undefined;
|
||||||
let had404 = false;
|
let had404 = false;
|
||||||
const queryIds = await this.getLikesQueryIds();
|
const queryIds = await this.getLikesQueryIds();
|
||||||
|
|
||||||
for (const queryId of queryIds) {
|
for (const queryId of queryIds) {
|
||||||
|
const variables = {
|
||||||
|
userId,
|
||||||
|
count: pageCount,
|
||||||
|
includePromotedContent: false,
|
||||||
|
withClientEventToken: false,
|
||||||
|
withBirdwatchNotes: false,
|
||||||
|
withVoice: true,
|
||||||
|
...(pageCursor ? { cursor: pageCursor } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
variables: JSON.stringify(variables),
|
||||||
|
features: JSON.stringify(features),
|
||||||
|
});
|
||||||
const url = `${TWITTER_API_BASE}/${queryId}/Likes?${params.toString()}`;
|
const url = `${TWITTER_API_BASE}/${queryId}/Likes?${params.toString()}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -147,14 +162,21 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
errors?: Array<{ message: string }>;
|
errors?: Array<{ message: string }>;
|
||||||
};
|
};
|
||||||
|
|
||||||
if (data.errors && data.errors.length > 0) {
|
|
||||||
return { success: false as const, error: data.errors.map((e) => e.message).join(', '), had404 };
|
|
||||||
}
|
|
||||||
|
|
||||||
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
|
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
|
||||||
const tweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
|
if (data.errors && data.errors.length > 0) {
|
||||||
|
const message = data.errors.map((e) => e.message).join(', ');
|
||||||
|
if (!instructions) {
|
||||||
|
if (message.includes('Query: Unspecified')) {
|
||||||
|
lastError = message;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
return { success: false as const, error: message, had404 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
|
||||||
|
const extractedCursor = extractCursorFromInstructions(instructions);
|
||||||
|
|
||||||
return { success: true as const, tweets, had404 };
|
return { success: true as const, tweets: pageTweets, cursor: extractedCursor, had404 };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error instanceof Error ? error.message : String(error);
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
}
|
}
|
||||||
@@ -163,21 +185,61 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
return { success: false as const, error: lastError ?? 'Unknown error fetching likes', had404 };
|
return { success: false as const, error: lastError ?? 'Unknown error fetching likes', had404 };
|
||||||
};
|
};
|
||||||
|
|
||||||
const firstAttempt = await tryOnce();
|
const fetchWithRefresh = async (pageCount: number, pageCursor?: string) => {
|
||||||
if (firstAttempt.success) {
|
const firstAttempt = await fetchPage(pageCount, pageCursor);
|
||||||
return { success: true, tweets: firstAttempt.tweets };
|
if (firstAttempt.success) {
|
||||||
}
|
return firstAttempt;
|
||||||
|
|
||||||
if (firstAttempt.had404) {
|
|
||||||
await this.refreshQueryIds();
|
|
||||||
const secondAttempt = await tryOnce();
|
|
||||||
if (secondAttempt.success) {
|
|
||||||
return { success: true, tweets: secondAttempt.tweets };
|
|
||||||
}
|
}
|
||||||
return { success: false, error: secondAttempt.error };
|
const shouldRefresh =
|
||||||
|
firstAttempt.had404 ||
|
||||||
|
(typeof firstAttempt.error === 'string' && firstAttempt.error.includes('Query: Unspecified'));
|
||||||
|
if (shouldRefresh) {
|
||||||
|
await this.refreshQueryIds();
|
||||||
|
const secondAttempt = await fetchPage(pageCount, pageCursor);
|
||||||
|
if (secondAttempt.success) {
|
||||||
|
return secondAttempt;
|
||||||
|
}
|
||||||
|
return { success: false as const, error: secondAttempt.error };
|
||||||
|
}
|
||||||
|
return { success: false as const, error: firstAttempt.error };
|
||||||
|
};
|
||||||
|
|
||||||
|
const unlimited = limit === Number.POSITIVE_INFINITY;
|
||||||
|
while (unlimited || tweets.length < limit) {
|
||||||
|
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - 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) {
|
||||||
|
if (seen.has(tweet.id)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(tweet.id);
|
||||||
|
tweets.push(tweet);
|
||||||
|
added += 1;
|
||||||
|
if (!unlimited && tweets.length >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageCursor = page.cursor;
|
||||||
|
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0 || added === 0) {
|
||||||
|
nextCursor = undefined;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (maxPages && pagesFetched >= maxPages) {
|
||||||
|
nextCursor = pageCursor;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
cursor = pageCursor;
|
||||||
|
nextCursor = pageCursor;
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success: false, error: firstAttempt.error };
|
return { success: true, tweets, nextCursor };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -320,7 +382,7 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
return { success: false as const, error: firstAttempt.error };
|
return { success: false as const, error: firstAttempt.error };
|
||||||
};
|
};
|
||||||
|
|
||||||
const unlimited = !Number.isFinite(limit);
|
const unlimited = limit === Number.POSITIVE_INFINITY;
|
||||||
while (unlimited || tweets.length < limit) {
|
while (unlimited || tweets.length < limit) {
|
||||||
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
|
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
|
||||||
const page = await fetchWithRefresh(pageCount, cursor);
|
const page = await fetchWithRefresh(pageCount, cursor);
|
||||||
@@ -329,19 +391,21 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
}
|
}
|
||||||
pagesFetched += 1;
|
pagesFetched += 1;
|
||||||
|
|
||||||
|
let added = 0;
|
||||||
for (const tweet of page.tweets) {
|
for (const tweet of page.tweets) {
|
||||||
if (seen.has(tweet.id)) {
|
if (seen.has(tweet.id)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
seen.add(tweet.id);
|
seen.add(tweet.id);
|
||||||
tweets.push(tweet);
|
tweets.push(tweet);
|
||||||
|
added += 1;
|
||||||
if (!unlimited && tweets.length >= limit) {
|
if (!unlimited && tweets.length >= limit) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const pageCursor = page.cursor;
|
const pageCursor = page.cursor;
|
||||||
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0) {
|
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0 || added === 0) {
|
||||||
nextCursor = undefined;
|
nextCursor = undefined;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -501,7 +565,7 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
return { success: false as const, error: firstAttempt.error };
|
return { success: false as const, error: firstAttempt.error };
|
||||||
};
|
};
|
||||||
|
|
||||||
const unlimited = !Number.isFinite(limit);
|
const unlimited = limit === Number.POSITIVE_INFINITY;
|
||||||
while (unlimited || tweets.length < limit) {
|
while (unlimited || tweets.length < limit) {
|
||||||
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
|
const pageCount = unlimited ? pageSize : Math.min(pageSize, limit - tweets.length);
|
||||||
const page = await fetchWithRefresh(pageCount, cursor);
|
const page = await fetchWithRefresh(pageCount, cursor);
|
||||||
@@ -510,19 +574,21 @@ export function withTimelines<TBase extends AbstractConstructor<TwitterClientBas
|
|||||||
}
|
}
|
||||||
pagesFetched += 1;
|
pagesFetched += 1;
|
||||||
|
|
||||||
|
let added = 0;
|
||||||
for (const tweet of page.tweets) {
|
for (const tweet of page.tweets) {
|
||||||
if (seen.has(tweet.id)) {
|
if (seen.has(tweet.id)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
seen.add(tweet.id);
|
seen.add(tweet.id);
|
||||||
tweets.push(tweet);
|
tweets.push(tweet);
|
||||||
|
added += 1;
|
||||||
if (!unlimited && tweets.length >= limit) {
|
if (!unlimited && tweets.length >= limit) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const pageCursor = page.cursor;
|
const pageCursor = page.cursor;
|
||||||
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0) {
|
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0 || added === 0) {
|
||||||
nextCursor = undefined;
|
nextCursor = undefined;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
|
import { paginateCursor } from './paginate-cursor.js';
|
||||||
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||||
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
||||||
import { buildArticleFeatures, buildArticleFieldToggles, buildTweetDetailFeatures } from './twitter-client-features.js';
|
import { buildArticleFeatures, buildArticleFieldToggles, buildTweetDetailFeatures } from './twitter-client-features.js';
|
||||||
import type { GetTweetResult, GraphqlTweetResult, SearchResult } from './twitter-client-types.js';
|
import type { GetTweetResult, GraphqlTweetResult, SearchResult, TweetData } from './twitter-client-types.js';
|
||||||
import {
|
import {
|
||||||
extractArticleText,
|
extractArticleText,
|
||||||
|
extractCursorFromInstructions,
|
||||||
findTweetInInstructions,
|
findTweetInInstructions,
|
||||||
firstText,
|
firstText,
|
||||||
mapTweetResult,
|
mapTweetResult,
|
||||||
@@ -16,10 +18,22 @@ export interface TweetFetchOptions {
|
|||||||
includeRaw?: boolean;
|
includeRaw?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Options for paginated tweet detail fetch */
|
||||||
|
export interface TweetDetailPaginationOptions extends TweetFetchOptions {
|
||||||
|
/** Maximum number of pages to fetch (default: unlimited when using pagination) */
|
||||||
|
maxPages?: number;
|
||||||
|
/** Starting cursor for pagination (resume from previous fetch) */
|
||||||
|
cursor?: string;
|
||||||
|
/** Delay in milliseconds between page fetches (default: 1000) */
|
||||||
|
pageDelayMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
export interface TwitterClientTweetDetailMethods {
|
export interface TwitterClientTweetDetailMethods {
|
||||||
getTweet(tweetId: string, options?: TweetFetchOptions): Promise<GetTweetResult>;
|
getTweet(tweetId: string, options?: TweetFetchOptions): Promise<GetTweetResult>;
|
||||||
getReplies(tweetId: string, options?: TweetFetchOptions): Promise<SearchResult>;
|
getReplies(tweetId: string, options?: TweetFetchOptions): Promise<SearchResult>;
|
||||||
getThread(tweetId: string, options?: TweetFetchOptions): Promise<SearchResult>;
|
getThread(tweetId: string, options?: TweetFetchOptions): Promise<SearchResult>;
|
||||||
|
getRepliesPaged(tweetId: string, options?: TweetDetailPaginationOptions): Promise<SearchResult>;
|
||||||
|
getThreadPaged(tweetId: string, options?: TweetDetailPaginationOptions): Promise<SearchResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function withTweetDetails<TBase extends AbstractConstructor<TwitterClientBase>>(
|
export function withTweetDetails<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||||
@@ -110,7 +124,10 @@ export function withTweetDetails<TBase extends AbstractConstructor<TwitterClient
|
|||||||
return {};
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async fetchTweetDetail(tweetId: string): Promise<
|
private async fetchTweetDetail(
|
||||||
|
tweetId: string,
|
||||||
|
cursor?: string,
|
||||||
|
): Promise<
|
||||||
| {
|
| {
|
||||||
success: true;
|
success: true;
|
||||||
data: {
|
data: {
|
||||||
@@ -141,6 +158,7 @@ export function withTweetDetails<TBase extends AbstractConstructor<TwitterClient
|
|||||||
withQuickPromoteEligibilityTweetFields: true,
|
withQuickPromoteEligibilityTweetFields: true,
|
||||||
withBirdwatchNotes: true,
|
withBirdwatchNotes: true,
|
||||||
withVoice: true,
|
withVoice: true,
|
||||||
|
...(cursor ? { cursor } : {}),
|
||||||
};
|
};
|
||||||
|
|
||||||
const features = {
|
const features = {
|
||||||
@@ -159,9 +177,15 @@ export function withTweetDetails<TBase extends AbstractConstructor<TwitterClient
|
|||||||
rweb_video_timestamps_enabled: true,
|
rweb_video_timestamps_enabled: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const fieldToggles = {
|
||||||
|
...buildArticleFieldToggles(),
|
||||||
|
withArticleRichContentState: true,
|
||||||
|
};
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
variables: JSON.stringify(variables),
|
variables: JSON.stringify(variables),
|
||||||
features: JSON.stringify(features),
|
features: JSON.stringify(features),
|
||||||
|
fieldToggles: JSON.stringify(fieldToggles),
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -192,7 +216,15 @@ export function withTweetDetails<TBase extends AbstractConstructor<TwitterClient
|
|||||||
};
|
};
|
||||||
|
|
||||||
if (data.errors && data.errors.length > 0) {
|
if (data.errors && data.errors.length > 0) {
|
||||||
return { success: false as const, error: data.errors.map((e) => e.message).join(', ') };
|
// Twitter API sometimes returns partial errors (e.g., is_translatable failures)
|
||||||
|
// alongside valid tweet/thread data. Only fail if nothing useful is present.
|
||||||
|
const hasUsableData = Boolean(
|
||||||
|
data.data?.tweetResult?.result ||
|
||||||
|
data.data?.threaded_conversation_with_injections_v2?.instructions?.length,
|
||||||
|
);
|
||||||
|
if (!hasUsableData) {
|
||||||
|
return { success: false as const, error: data.errors.map((e) => e.message).join(', ') };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return { success: true as const, data: data.data ?? {} };
|
return { success: true as const, data: data.data ?? {} };
|
||||||
@@ -219,7 +251,7 @@ export function withTweetDetails<TBase extends AbstractConstructor<TwitterClient
|
|||||||
|
|
||||||
const postResponse = await this.fetchWithTimeout(`${TWITTER_API_BASE}/${queryId}/TweetDetail`, {
|
const postResponse = await this.fetchWithTimeout(`${TWITTER_API_BASE}/${queryId}/TweetDetail`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: this.getHeaders(),
|
headers: this.getJsonHeaders(),
|
||||||
body: JSON.stringify({ variables, features, queryId }),
|
body: JSON.stringify({ variables, features, queryId }),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -340,6 +372,95 @@ export function withTweetDetails<TBase extends AbstractConstructor<TwitterClient
|
|||||||
|
|
||||||
return { success: true, tweets: thread };
|
return { success: true, tweets: thread };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get replies to a tweet with pagination support
|
||||||
|
*/
|
||||||
|
async getRepliesPaged(tweetId: string, options: TweetDetailPaginationOptions = {}): Promise<SearchResult> {
|
||||||
|
const { includeRaw = false, maxPages, pageDelayMs = 1000 } = options;
|
||||||
|
|
||||||
|
const result = await paginateCursor<TweetData>({
|
||||||
|
cursor: options.cursor,
|
||||||
|
maxPages,
|
||||||
|
pageDelayMs,
|
||||||
|
sleep: async (ms) => this.sleep(ms),
|
||||||
|
getKey: (tweet) => tweet.id,
|
||||||
|
fetchPage: async (cursor) => {
|
||||||
|
const response = await this.fetchTweetDetail(tweetId, cursor);
|
||||||
|
if (!response.success) {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const instructions = response.data.threaded_conversation_with_injections_v2?.instructions;
|
||||||
|
const tweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
|
||||||
|
const replies = tweets.filter((tweet) => tweet.inReplyToStatusId === tweetId);
|
||||||
|
const pageCursor = extractCursorFromInstructions(instructions);
|
||||||
|
|
||||||
|
return { success: true as const, items: replies, cursor: pageCursor };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
return { success: true, tweets: result.items, nextCursor: result.nextCursor };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.items) {
|
||||||
|
return { success: false, tweets: result.items, nextCursor: result.nextCursor, error: result.error };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, error: result.error };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get full conversation thread with pagination support
|
||||||
|
*/
|
||||||
|
async getThreadPaged(tweetId: string, options: TweetDetailPaginationOptions = {}): Promise<SearchResult> {
|
||||||
|
const { includeRaw = false, maxPages, pageDelayMs = 1000 } = options;
|
||||||
|
let rootId: string | undefined;
|
||||||
|
|
||||||
|
const result = await paginateCursor<TweetData>({
|
||||||
|
cursor: options.cursor,
|
||||||
|
maxPages,
|
||||||
|
pageDelayMs,
|
||||||
|
sleep: async (ms) => this.sleep(ms),
|
||||||
|
getKey: (tweet) => tweet.id,
|
||||||
|
fetchPage: async (cursor) => {
|
||||||
|
const response = await this.fetchTweetDetail(tweetId, cursor);
|
||||||
|
if (!response.success) {
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
const instructions = response.data.threaded_conversation_with_injections_v2?.instructions;
|
||||||
|
const tweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
|
||||||
|
|
||||||
|
if (!rootId) {
|
||||||
|
const target = tweets.find((t) => t.id === tweetId);
|
||||||
|
rootId = target?.conversationId || tweetId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const threadTweets = tweets.filter((tweet) => tweet.conversationId === rootId);
|
||||||
|
const pageCursor = extractCursorFromInstructions(instructions);
|
||||||
|
|
||||||
|
return { success: true as const, items: threadTweets, cursor: pageCursor };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const sortedTweets = (result.items ?? []).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;
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.success) {
|
||||||
|
return { success: true, tweets: sortedTweets, nextCursor: result.nextCursor };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result.items) {
|
||||||
|
return { success: false, tweets: sortedTweets, nextCursor: result.nextCursor, error: result.error };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, error: result.error };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return TwitterClientTweetDetails;
|
return TwitterClientTweetDetails;
|
||||||
|
|||||||
@@ -1,5 +1,3 @@
|
|||||||
import type { TwitterCookies } from './cookies.js';
|
|
||||||
|
|
||||||
// Raw media entity from Twitter API
|
// Raw media entity from Twitter API
|
||||||
export interface GraphqlMediaEntity {
|
export interface GraphqlMediaEntity {
|
||||||
id_str?: string;
|
id_str?: string;
|
||||||
@@ -80,9 +78,12 @@ export type GraphqlTweetResult = {
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
article?: {
|
article?: {
|
||||||
|
title?: string;
|
||||||
|
preview_text?: string;
|
||||||
article_results?: {
|
article_results?: {
|
||||||
result?: {
|
result?: {
|
||||||
title?: string;
|
title?: string;
|
||||||
|
preview_text?: string;
|
||||||
plain_text?: string;
|
plain_text?: string;
|
||||||
text?: string;
|
text?: string;
|
||||||
richtext?: {
|
richtext?: {
|
||||||
@@ -127,9 +128,36 @@ export type GraphqlTweetResult = {
|
|||||||
};
|
};
|
||||||
}>;
|
}>;
|
||||||
}>;
|
}>;
|
||||||
|
/** Draft.js content state for rich article content */
|
||||||
|
content_state?: {
|
||||||
|
blocks: Array<{
|
||||||
|
key: string;
|
||||||
|
type: string;
|
||||||
|
text: string;
|
||||||
|
data?: Record<string, unknown>;
|
||||||
|
entityRanges?: Array<{ key: number; offset: number; length: number }>;
|
||||||
|
inlineStyleRanges?: Array<{ offset: number; length: number; style: string }>;
|
||||||
|
}>;
|
||||||
|
entityMap?:
|
||||||
|
| Array<{
|
||||||
|
key: string;
|
||||||
|
value: {
|
||||||
|
type: string;
|
||||||
|
mutability: string;
|
||||||
|
data: Record<string, unknown>;
|
||||||
|
};
|
||||||
|
}>
|
||||||
|
| Record<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
type: string;
|
||||||
|
mutability: string;
|
||||||
|
data: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
>;
|
||||||
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
title?: string;
|
|
||||||
plain_text?: string;
|
plain_text?: string;
|
||||||
text?: string;
|
text?: string;
|
||||||
richtext?: {
|
richtext?: {
|
||||||
@@ -236,6 +264,11 @@ export interface TweetData {
|
|||||||
quotedTweet?: TweetData;
|
quotedTweet?: TweetData;
|
||||||
// Media attachments (photos, videos, GIFs)
|
// Media attachments (photos, videos, GIFs)
|
||||||
media?: TweetMedia[];
|
media?: TweetMedia[];
|
||||||
|
// Article metadata (for Twitter Articles / long-form posts)
|
||||||
|
article?: {
|
||||||
|
title: string;
|
||||||
|
previewText?: string;
|
||||||
|
};
|
||||||
// Raw GraphQL tweet result (only when includeRaw is enabled)
|
// Raw GraphQL tweet result (only when includeRaw is enabled)
|
||||||
_raw?: GraphqlTweetResult;
|
_raw?: GraphqlTweetResult;
|
||||||
}
|
}
|
||||||
@@ -246,13 +279,20 @@ export interface GetTweetResult {
|
|||||||
error?: string;
|
error?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface SearchResult {
|
export type SearchResult =
|
||||||
success: boolean;
|
| {
|
||||||
tweets?: TweetData[];
|
success: true;
|
||||||
error?: string;
|
tweets: TweetData[];
|
||||||
/** Cursor for fetching the next page of results */
|
/** Cursor for fetching the next page of results */
|
||||||
nextCursor?: string;
|
nextCursor?: string;
|
||||||
}
|
}
|
||||||
|
| {
|
||||||
|
success: false;
|
||||||
|
error: string;
|
||||||
|
tweets?: TweetData[];
|
||||||
|
/** Cursor for fetching the next page of results */
|
||||||
|
nextCursor?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export interface CurrentUserResult {
|
export interface CurrentUserResult {
|
||||||
success: boolean;
|
success: boolean;
|
||||||
@@ -280,11 +320,12 @@ export interface FollowingResult {
|
|||||||
success: boolean;
|
success: boolean;
|
||||||
users?: TwitterUser[];
|
users?: TwitterUser[];
|
||||||
error?: string;
|
error?: string;
|
||||||
|
/** Cursor for fetching the next page of results */
|
||||||
|
nextCursor?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TwitterClientOptions {
|
export interface TwitterClientOptions {
|
||||||
cookies: TwitterCookies;
|
relayBaseUrl?: string;
|
||||||
userAgent?: string;
|
|
||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
// Max depth for quoted tweets (0 disables). Defaults to 1.
|
// Max depth for quoted tweets (0 disables). Defaults to 1.
|
||||||
quoteDepth?: number;
|
quoteDepth?: number;
|
||||||
|
|||||||
@@ -0,0 +1,211 @@
|
|||||||
|
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';
|
||||||
|
|
||||||
|
/** Result of username to userId lookup */
|
||||||
|
export interface UserLookupResult {
|
||||||
|
success: boolean;
|
||||||
|
userId?: string;
|
||||||
|
username?: string;
|
||||||
|
name?: string;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TwitterClientUserLookupMethods {
|
||||||
|
getUserIdByUsername(username: string): Promise<UserLookupResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withUserLookup<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||||
|
Base: TBase,
|
||||||
|
): Mixin<TBase, TwitterClientUserLookupMethods> {
|
||||||
|
abstract class TwitterClientUserLookup extends Base {
|
||||||
|
// biome-ignore lint/complexity/noUselessConstructor lint/suspicious/noExplicitAny: TS mixin constructor requirement.
|
||||||
|
constructor(...args: any[]) {
|
||||||
|
super(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getUserByScreenNameGraphQL(screenName: string): Promise<UserLookupResult> {
|
||||||
|
// UserByScreenName query IDs observed from web client
|
||||||
|
const queryIds = ['xc8f1g7BYqr6VTzTbvNlGw', 'qW5u-DAuXpMEG0zA1F7UGQ', 'sLVLhk0bGj3MVFEKTdax1w'];
|
||||||
|
|
||||||
|
const variables = {
|
||||||
|
screen_name: screenName,
|
||||||
|
withSafetyModeUserFields: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const features = {
|
||||||
|
hidden_profile_subscriptions_enabled: true,
|
||||||
|
hidden_profile_likes_enabled: true,
|
||||||
|
rweb_tipjar_consumption_enabled: true,
|
||||||
|
responsive_web_graphql_exclude_directive_enabled: true,
|
||||||
|
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,
|
||||||
|
blue_business_profile_image_shape_enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const fieldToggles = {
|
||||||
|
withAuxiliaryUserLabels: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
variables: JSON.stringify(variables),
|
||||||
|
features: JSON.stringify(features),
|
||||||
|
fieldToggles: JSON.stringify(fieldToggles),
|
||||||
|
});
|
||||||
|
|
||||||
|
let lastError: string | undefined;
|
||||||
|
|
||||||
|
for (const queryId of queryIds) {
|
||||||
|
const url = `${TWITTER_API_BASE}/${queryId}/UserByScreenName?${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) {
|
||||||
|
// Try next query ID
|
||||||
|
lastError = `HTTP ${response.status}`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await response.json()) as {
|
||||||
|
data?: {
|
||||||
|
user?: {
|
||||||
|
result?: {
|
||||||
|
__typename?: string;
|
||||||
|
rest_id?: string;
|
||||||
|
legacy?: {
|
||||||
|
screen_name?: string;
|
||||||
|
name?: string;
|
||||||
|
};
|
||||||
|
core?: {
|
||||||
|
screen_name?: string;
|
||||||
|
name?: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
errors?: Array<{ message: string }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Check for user not found
|
||||||
|
if (data.data?.user?.result?.__typename === 'UserUnavailable') {
|
||||||
|
return { success: false, error: `User @${screenName} not found or unavailable` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const userResult = data.data?.user?.result;
|
||||||
|
const userId = userResult?.rest_id;
|
||||||
|
const username = userResult?.legacy?.screen_name ?? userResult?.core?.screen_name;
|
||||||
|
const name = userResult?.legacy?.name ?? userResult?.core?.name;
|
||||||
|
|
||||||
|
if (userId && username) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
userId,
|
||||||
|
username,
|
||||||
|
name,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (data.errors && data.errors.length > 0) {
|
||||||
|
lastError = data.errors.map((e) => e.message).join(', ');
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
lastError = 'Could not parse user data from response';
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, error: lastError ?? 'Unknown error looking up user' };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Look up a user's ID by their username/handle.
|
||||||
|
* Uses GraphQL UserByScreenName first, then falls back to REST on transient failures.
|
||||||
|
*/
|
||||||
|
async getUserIdByUsername(username: string): Promise<UserLookupResult> {
|
||||||
|
const cleanUsername = normalizeHandle(username);
|
||||||
|
if (!cleanUsername) {
|
||||||
|
return { success: false, error: `Invalid username: ${username}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const graphqlResult = await this.getUserByScreenNameGraphQL(cleanUsername);
|
||||||
|
if (graphqlResult.success) {
|
||||||
|
return graphqlResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If GraphQL definitively says user is unavailable, don't retry with REST
|
||||||
|
if (graphqlResult.error?.includes('not found or unavailable')) {
|
||||||
|
return graphqlResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to REST API for transient GraphQL errors
|
||||||
|
const urls = [
|
||||||
|
`https://x.com/i/api/1.1/users/show.json?screen_name=${encodeURIComponent(cleanUsername)}`,
|
||||||
|
`https://api.twitter.com/1.1/users/show.json?screen_name=${encodeURIComponent(cleanUsername)}`,
|
||||||
|
];
|
||||||
|
|
||||||
|
let lastError: string | undefined = graphqlResult.error;
|
||||||
|
|
||||||
|
for (const url of urls) {
|
||||||
|
try {
|
||||||
|
const response = await this.fetchWithTimeout(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: this.getHeaders(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const text = await response.text();
|
||||||
|
if (response.status === 404) {
|
||||||
|
return { success: false, error: `User @${cleanUsername} not found` };
|
||||||
|
}
|
||||||
|
lastError = `HTTP ${response.status}: ${text.slice(0, 200)}`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await response.json()) as {
|
||||||
|
id_str?: string;
|
||||||
|
id?: number;
|
||||||
|
screen_name?: string;
|
||||||
|
name?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const userId = data.id_str ?? (data.id ? String(data.id) : null);
|
||||||
|
if (!userId) {
|
||||||
|
lastError = 'Could not parse user ID from response';
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
userId,
|
||||||
|
username: data.screen_name ?? cleanUsername,
|
||||||
|
name: data.name,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false, error: lastError ?? 'Unknown error looking up user' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return TwitterClientUserLookup;
|
||||||
|
}
|
||||||
@@ -0,0 +1,262 @@
|
|||||||
|
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||||
|
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
||||||
|
import { buildUserTweetsFeatures } from './twitter-client-features.js';
|
||||||
|
import type { GraphqlTweetResult, SearchResult, TweetData } from './twitter-client-types.js';
|
||||||
|
import { extractCursorFromInstructions, parseTweetsFromInstructions } from './twitter-client-utils.js';
|
||||||
|
|
||||||
|
/** Options for user tweets fetch methods */
|
||||||
|
export interface UserTweetsFetchOptions {
|
||||||
|
/** Include raw GraphQL response in `_raw` field */
|
||||||
|
includeRaw?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Options for paginated user tweets fetch */
|
||||||
|
export interface UserTweetsPaginationOptions extends UserTweetsFetchOptions {
|
||||||
|
/** Maximum number of pages to fetch (default: 1) */
|
||||||
|
maxPages?: number;
|
||||||
|
/** Starting cursor for pagination (resume from previous fetch) */
|
||||||
|
cursor?: string;
|
||||||
|
/** Delay in milliseconds between page fetches (default: 1000) */
|
||||||
|
pageDelayMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TwitterClientUserTweetsMethods {
|
||||||
|
getUserTweets(userId: string, count?: number, options?: UserTweetsFetchOptions): Promise<SearchResult>;
|
||||||
|
getUserTweetsPaged(userId: string, limit: number, options?: UserTweetsPaginationOptions): Promise<SearchResult>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function withUserTweets<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||||
|
Base: TBase,
|
||||||
|
): Mixin<TBase, TwitterClientUserTweetsMethods> {
|
||||||
|
abstract class TwitterClientUserTweets extends Base {
|
||||||
|
// biome-ignore lint/complexity/noUselessConstructor lint/suspicious/noExplicitAny: TS mixin constructor requirement.
|
||||||
|
constructor(...args: any[]) {
|
||||||
|
super(...args);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getUserTweetsQueryIds(): Promise<string[]> {
|
||||||
|
const primary = await this.getQueryId('UserTweets');
|
||||||
|
// Fallback query ID observed from web client
|
||||||
|
return Array.from(new Set([primary, 'Wms1GvIiHXAPBaCr9KblaA']));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get tweets from a user's profile timeline (single page).
|
||||||
|
*/
|
||||||
|
async getUserTweets(userId: string, count = 20, options: UserTweetsFetchOptions = {}): Promise<SearchResult> {
|
||||||
|
return this.getUserTweetsPaged(userId, count, options);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get tweets from a user's profile timeline with pagination support.
|
||||||
|
*/
|
||||||
|
async getUserTweetsPaged(
|
||||||
|
userId: string,
|
||||||
|
limit: number,
|
||||||
|
options: UserTweetsPaginationOptions = {},
|
||||||
|
): Promise<SearchResult> {
|
||||||
|
if (!Number.isFinite(limit) || limit <= 0) {
|
||||||
|
return { success: false, error: `Invalid limit: ${limit}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { includeRaw = false, maxPages, pageDelayMs = 1000 } = options;
|
||||||
|
const features = buildUserTweetsFeatures();
|
||||||
|
const pageSize = 20;
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const tweets: TweetData[] = [];
|
||||||
|
let cursor: string | undefined = options.cursor;
|
||||||
|
let nextCursor: string | undefined;
|
||||||
|
let pagesFetched = 0;
|
||||||
|
const hardMaxPages = 10;
|
||||||
|
const computedMaxPages = Math.max(1, Math.ceil(limit / pageSize));
|
||||||
|
const effectiveMaxPages = Math.min(hardMaxPages, maxPages ?? computedMaxPages);
|
||||||
|
|
||||||
|
const fetchPage = async (pageCount: number, pageCursor?: string) => {
|
||||||
|
let lastError: string | undefined;
|
||||||
|
let had404 = false;
|
||||||
|
const queryIds = await this.getUserTweetsQueryIds();
|
||||||
|
|
||||||
|
const variables = {
|
||||||
|
userId,
|
||||||
|
count: pageCount,
|
||||||
|
includePromotedContent: false, // Filter out ads
|
||||||
|
withQuickPromoteEligibilityTweetFields: true,
|
||||||
|
withVoice: true,
|
||||||
|
...(pageCursor ? { cursor: pageCursor } : {}),
|
||||||
|
};
|
||||||
|
|
||||||
|
const fieldToggles = {
|
||||||
|
withArticlePlainText: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
variables: JSON.stringify(variables),
|
||||||
|
features: JSON.stringify(features),
|
||||||
|
fieldToggles: JSON.stringify(fieldToggles),
|
||||||
|
});
|
||||||
|
|
||||||
|
for (const queryId of queryIds) {
|
||||||
|
const url = `${TWITTER_API_BASE}/${queryId}/UserTweets?${params.toString()}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await this.fetchWithTimeout(url, {
|
||||||
|
method: 'GET',
|
||||||
|
headers: this.getHeaders(),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 404) {
|
||||||
|
had404 = true;
|
||||||
|
lastError = `HTTP ${response.status}`;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const text = await response.text();
|
||||||
|
return { success: false as const, error: `HTTP ${response.status}: ${text.slice(0, 200)}`, had404 };
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = (await response.json()) as {
|
||||||
|
data?: {
|
||||||
|
user?: {
|
||||||
|
result?: {
|
||||||
|
timeline?: {
|
||||||
|
timeline?: {
|
||||||
|
instructions?: Array<{
|
||||||
|
type?: string;
|
||||||
|
entries?: Array<{
|
||||||
|
content?: {
|
||||||
|
itemContent?: {
|
||||||
|
tweet_results?: {
|
||||||
|
result?: GraphqlTweetResult;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
item?: {
|
||||||
|
itemContent?: {
|
||||||
|
tweet_results?: {
|
||||||
|
result?: GraphqlTweetResult;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
items?: Array<{
|
||||||
|
item?: {
|
||||||
|
itemContent?: {
|
||||||
|
tweet_results?: {
|
||||||
|
result?: GraphqlTweetResult;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
itemContent?: {
|
||||||
|
tweet_results?: {
|
||||||
|
result?: GraphqlTweetResult;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
content?: {
|
||||||
|
itemContent?: {
|
||||||
|
tweet_results?: {
|
||||||
|
result?: GraphqlTweetResult;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
cursorType?: string;
|
||||||
|
value?: string;
|
||||||
|
};
|
||||||
|
}>;
|
||||||
|
}>;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
};
|
||||||
|
errors?: Array<{ message: string }>;
|
||||||
|
};
|
||||||
|
|
||||||
|
if (data.errors && data.errors.length > 0) {
|
||||||
|
// Check for common errors
|
||||||
|
const errorMsg = data.errors.map((e) => e.message).join(', ');
|
||||||
|
if (errorMsg.includes('User has been suspended') || errorMsg.includes('User not found')) {
|
||||||
|
return { success: false as const, error: errorMsg, had404 };
|
||||||
|
}
|
||||||
|
// Some errors are non-fatal if we got data
|
||||||
|
if (!data.data?.user?.result?.timeline?.timeline?.instructions) {
|
||||||
|
return { success: false as const, error: errorMsg, had404 };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
|
||||||
|
const pageTweets = parseTweetsFromInstructions(instructions, { quoteDepth: this.quoteDepth, includeRaw });
|
||||||
|
const pageCursorValue = extractCursorFromInstructions(instructions);
|
||||||
|
|
||||||
|
return { success: true as const, tweets: pageTweets, cursor: pageCursorValue, had404 };
|
||||||
|
} catch (error) {
|
||||||
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: false as const, error: lastError ?? 'Unknown error fetching user tweets', had404 };
|
||||||
|
};
|
||||||
|
|
||||||
|
const fetchWithRefresh = async (pageCount: number, pageCursor?: string) => {
|
||||||
|
const firstAttempt = await fetchPage(pageCount, pageCursor);
|
||||||
|
if (firstAttempt.success) {
|
||||||
|
return firstAttempt;
|
||||||
|
}
|
||||||
|
if (firstAttempt.had404) {
|
||||||
|
await this.refreshQueryIds();
|
||||||
|
const secondAttempt = await fetchPage(pageCount, pageCursor);
|
||||||
|
if (secondAttempt.success) {
|
||||||
|
return secondAttempt;
|
||||||
|
}
|
||||||
|
return { success: false as const, error: secondAttempt.error };
|
||||||
|
}
|
||||||
|
return { success: false as const, error: firstAttempt.error };
|
||||||
|
};
|
||||||
|
|
||||||
|
while (tweets.length < limit) {
|
||||||
|
// Add delay between pages (but not before the first page)
|
||||||
|
if (pagesFetched > 0 && pageDelayMs > 0) {
|
||||||
|
await this.sleep(pageDelayMs);
|
||||||
|
}
|
||||||
|
|
||||||
|
const remaining = limit - tweets.length;
|
||||||
|
const pageCount = Math.min(pageSize, remaining);
|
||||||
|
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) {
|
||||||
|
if (seen.has(tweet.id)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(tweet.id);
|
||||||
|
tweets.push(tweet);
|
||||||
|
added += 1;
|
||||||
|
if (tweets.length >= limit) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const pageCursor = page.cursor;
|
||||||
|
if (!pageCursor || pageCursor === cursor || page.tweets.length === 0 || added === 0) {
|
||||||
|
nextCursor = undefined;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (pagesFetched >= effectiveMaxPages) {
|
||||||
|
nextCursor = pageCursor;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
cursor = pageCursor;
|
||||||
|
nextCursor = pageCursor;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true, tweets, nextCursor };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return TwitterClientUserTweets;
|
||||||
|
}
|
||||||
+74
-129
@@ -1,18 +1,26 @@
|
|||||||
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
import type { AbstractConstructor, Mixin, TwitterClientBase } from './twitter-client-base.js';
|
||||||
import {
|
import { TWITTER_API_BASE } from './twitter-client-constants.js';
|
||||||
SETTINGS_NAME_REGEX,
|
|
||||||
SETTINGS_SCREEN_NAME_REGEX,
|
|
||||||
SETTINGS_USER_ID_REGEX,
|
|
||||||
TWITTER_API_BASE,
|
|
||||||
} from './twitter-client-constants.js';
|
|
||||||
import { buildFollowingFeatures } from './twitter-client-features.js';
|
import { buildFollowingFeatures } from './twitter-client-features.js';
|
||||||
import type { CurrentUserResult, FollowingResult } from './twitter-client-types.js';
|
import type { CurrentUserResult, FollowingResult, TwitterUser } from './twitter-client-types.js';
|
||||||
import { parseUsersFromInstructions } from './twitter-client-utils.js';
|
import { extractCursorFromInstructions, parseUsersFromInstructions } from './twitter-client-utils.js';
|
||||||
|
|
||||||
|
type RestUser = {
|
||||||
|
id_str?: string;
|
||||||
|
id?: string | number;
|
||||||
|
screen_name?: string;
|
||||||
|
name?: string;
|
||||||
|
description?: string;
|
||||||
|
followers_count?: number;
|
||||||
|
friends_count?: number;
|
||||||
|
verified?: boolean;
|
||||||
|
profile_image_url_https?: string;
|
||||||
|
created_at?: string;
|
||||||
|
};
|
||||||
|
|
||||||
export interface TwitterClientUserMethods {
|
export interface TwitterClientUserMethods {
|
||||||
getCurrentUser(): Promise<CurrentUserResult>;
|
getCurrentUser(): Promise<CurrentUserResult>;
|
||||||
getFollowing(userId: string, count?: number): Promise<FollowingResult>;
|
getFollowing(userId: string, count?: number, cursor?: string): Promise<FollowingResult>;
|
||||||
getFollowers(userId: string, count?: number): Promise<FollowingResult>;
|
getFollowers(userId: string, count?: number, cursor?: string): Promise<FollowingResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
||||||
@@ -34,6 +42,29 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
return Array.from(new Set([primary, 'kuFUYP9eV1FPoEy4N-pi7w']));
|
return Array.from(new Set([primary, 'kuFUYP9eV1FPoEy4N-pi7w']));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private parseUsersFromRestResponse(users: RestUser[] | undefined): TwitterUser[] {
|
||||||
|
return (users ?? [])
|
||||||
|
.map((u) => {
|
||||||
|
const id = typeof u.id_str === 'string' ? u.id_str : typeof u.id === 'number' ? String(u.id) : null;
|
||||||
|
const username = typeof u.screen_name === 'string' ? u.screen_name : null;
|
||||||
|
if (!id || !username) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
id,
|
||||||
|
username,
|
||||||
|
name: typeof u.name === 'string' && u.name.length > 0 ? u.name : username,
|
||||||
|
description: typeof u.description === 'string' ? u.description : undefined,
|
||||||
|
followersCount: typeof u.followers_count === 'number' ? u.followers_count : undefined,
|
||||||
|
followingCount: typeof u.friends_count === 'number' ? u.friends_count : undefined,
|
||||||
|
isBlueVerified: typeof u.verified === 'boolean' ? u.verified : undefined,
|
||||||
|
profileImageUrl: typeof u.profile_image_url_https === 'string' ? u.profile_image_url_https : undefined,
|
||||||
|
createdAt: typeof u.created_at === 'string' ? u.created_at : undefined,
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.filter((u) => u !== null);
|
||||||
|
}
|
||||||
|
|
||||||
private async getFollowersViaRest(userId: string, count: number): Promise<FollowingResult> {
|
private async getFollowersViaRest(userId: string, count: number): Promise<FollowingResult> {
|
||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
user_id: userId,
|
user_id: userId,
|
||||||
@@ -63,40 +94,10 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = (await response.json()) as {
|
const data = (await response.json()) as {
|
||||||
users?: Array<{
|
users?: RestUser[];
|
||||||
id_str?: string;
|
|
||||||
id?: string | number;
|
|
||||||
screen_name?: string;
|
|
||||||
name?: string;
|
|
||||||
description?: string;
|
|
||||||
followers_count?: number;
|
|
||||||
friends_count?: number;
|
|
||||||
verified?: boolean;
|
|
||||||
profile_image_url_https?: string;
|
|
||||||
created_at?: string;
|
|
||||||
}>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const users = (data.users ?? [])
|
const users = this.parseUsersFromRestResponse(data.users);
|
||||||
.map((u) => {
|
|
||||||
const id = typeof u.id_str === 'string' ? u.id_str : typeof u.id === 'number' ? String(u.id) : null;
|
|
||||||
const username = typeof u.screen_name === 'string' ? u.screen_name : null;
|
|
||||||
if (!id || !username) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
username,
|
|
||||||
name: typeof u.name === 'string' && u.name.length > 0 ? u.name : username,
|
|
||||||
description: typeof u.description === 'string' ? u.description : undefined,
|
|
||||||
followersCount: typeof u.followers_count === 'number' ? u.followers_count : undefined,
|
|
||||||
followingCount: typeof u.friends_count === 'number' ? u.friends_count : undefined,
|
|
||||||
isBlueVerified: typeof u.verified === 'boolean' ? u.verified : undefined,
|
|
||||||
profileImageUrl: typeof u.profile_image_url_https === 'string' ? u.profile_image_url_https : undefined,
|
|
||||||
createdAt: typeof u.created_at === 'string' ? u.created_at : undefined,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.filter((u) => u !== null);
|
|
||||||
|
|
||||||
return { success: true, users };
|
return { success: true, users };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -136,40 +137,10 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const data = (await response.json()) as {
|
const data = (await response.json()) as {
|
||||||
users?: Array<{
|
users?: RestUser[];
|
||||||
id_str?: string;
|
|
||||||
id?: string | number;
|
|
||||||
screen_name?: string;
|
|
||||||
name?: string;
|
|
||||||
description?: string;
|
|
||||||
followers_count?: number;
|
|
||||||
friends_count?: number;
|
|
||||||
verified?: boolean;
|
|
||||||
profile_image_url_https?: string;
|
|
||||||
created_at?: string;
|
|
||||||
}>;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const users = (data.users ?? [])
|
const users = this.parseUsersFromRestResponse(data.users);
|
||||||
.map((u) => {
|
|
||||||
const id = typeof u.id_str === 'string' ? u.id_str : typeof u.id === 'number' ? String(u.id) : null;
|
|
||||||
const username = typeof u.screen_name === 'string' ? u.screen_name : null;
|
|
||||||
if (!id || !username) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
username,
|
|
||||||
name: typeof u.name === 'string' && u.name.length > 0 ? u.name : username,
|
|
||||||
description: typeof u.description === 'string' ? u.description : undefined,
|
|
||||||
followersCount: typeof u.followers_count === 'number' ? u.followers_count : undefined,
|
|
||||||
followingCount: typeof u.friends_count === 'number' ? u.friends_count : undefined,
|
|
||||||
isBlueVerified: typeof u.verified === 'boolean' ? u.verified : undefined,
|
|
||||||
profileImageUrl: typeof u.profile_image_url_https === 'string' ? u.profile_image_url_https : undefined,
|
|
||||||
createdAt: typeof u.created_at === 'string' ? u.created_at : undefined,
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.filter((u) => u !== null);
|
|
||||||
|
|
||||||
return { success: true, users };
|
return { success: true, users };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -181,7 +152,7 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch the account associated with the current cookies
|
* Fetch the account associated with the configured relay.
|
||||||
*/
|
*/
|
||||||
async getCurrentUser(): Promise<CurrentUserResult> {
|
async getCurrentUser(): Promise<CurrentUserResult> {
|
||||||
const candidateUrls = [
|
const candidateUrls = [
|
||||||
@@ -258,48 +229,6 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Fallback: scrape the authenticated settings page (HTML) for screen_name/user_id
|
|
||||||
const profilePages = ['https://x.com/settings/account', 'https://twitter.com/settings/account'];
|
|
||||||
for (const page of profilePages) {
|
|
||||||
try {
|
|
||||||
const response = await this.fetchWithTimeout(page, {
|
|
||||||
headers: {
|
|
||||||
cookie: this.cookieHeader,
|
|
||||||
'user-agent': this.userAgent,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
lastError = `HTTP ${response.status} (settings page)`;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
const html = await response.text();
|
|
||||||
const usernameMatch = SETTINGS_SCREEN_NAME_REGEX.exec(html);
|
|
||||||
const idMatch = SETTINGS_USER_ID_REGEX.exec(html);
|
|
||||||
const nameMatch = SETTINGS_NAME_REGEX.exec(html);
|
|
||||||
|
|
||||||
const username = usernameMatch?.[1];
|
|
||||||
const userId = idMatch?.[1];
|
|
||||||
const name = nameMatch?.[1]?.replace(/\\"/g, '"');
|
|
||||||
|
|
||||||
if (username && userId) {
|
|
||||||
return {
|
|
||||||
success: true,
|
|
||||||
user: {
|
|
||||||
id: userId,
|
|
||||||
username,
|
|
||||||
name: name || username,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
lastError = 'Could not parse settings page for user info';
|
|
||||||
} catch (error) {
|
|
||||||
lastError = error instanceof Error ? error.message : String(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: lastError ?? 'Unknown error fetching current user',
|
error: lastError ?? 'Unknown error fetching current user',
|
||||||
@@ -309,13 +238,17 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
/**
|
/**
|
||||||
* Get users that a user is following
|
* Get users that a user is following
|
||||||
*/
|
*/
|
||||||
async getFollowing(userId: string, count = 20): Promise<FollowingResult> {
|
async getFollowing(userId: string, count = 20, cursor?: string): Promise<FollowingResult> {
|
||||||
const variables = {
|
const variables: Record<string, unknown> = {
|
||||||
userId,
|
userId,
|
||||||
count,
|
count,
|
||||||
includePromotedContent: false,
|
includePromotedContent: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (cursor) {
|
||||||
|
variables.cursor = cursor;
|
||||||
|
}
|
||||||
|
|
||||||
const features = buildFollowingFeatures();
|
const features = buildFollowingFeatures();
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
@@ -369,8 +302,11 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
|
|
||||||
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
|
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
|
||||||
const users = parseUsersFromInstructions(instructions);
|
const users = parseUsersFromInstructions(instructions);
|
||||||
|
const nextCursor = extractCursorFromInstructions(
|
||||||
|
instructions as Array<{ entries?: Array<{ content?: unknown }> }> | undefined,
|
||||||
|
);
|
||||||
|
|
||||||
return { success: true as const, users, had404 };
|
return { success: true as const, users, nextCursor, had404 };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error instanceof Error ? error.message : String(error);
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
}
|
}
|
||||||
@@ -381,18 +317,19 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
|
|
||||||
const firstAttempt = await tryOnce();
|
const firstAttempt = await tryOnce();
|
||||||
if (firstAttempt.success) {
|
if (firstAttempt.success) {
|
||||||
return { success: true, users: firstAttempt.users };
|
return { success: true, users: firstAttempt.users, nextCursor: firstAttempt.nextCursor };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (firstAttempt.had404) {
|
if (firstAttempt.had404) {
|
||||||
await this.refreshQueryIds();
|
await this.refreshQueryIds();
|
||||||
const secondAttempt = await tryOnce();
|
const secondAttempt = await tryOnce();
|
||||||
if (secondAttempt.success) {
|
if (secondAttempt.success) {
|
||||||
return { success: true, users: secondAttempt.users };
|
return { success: true, users: secondAttempt.users, nextCursor: secondAttempt.nextCursor };
|
||||||
}
|
}
|
||||||
|
|
||||||
// GraphQL Following can also return 404 (queryId churn / endpoint flakiness).
|
// GraphQL Following can also return 404 (queryId churn / endpoint flakiness).
|
||||||
// Fallback to the internal v1.1 REST endpoint used by the web client (cookie-auth; no dev API key).
|
// 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);
|
||||||
if (restAttempt.success) {
|
if (restAttempt.success) {
|
||||||
return restAttempt;
|
return restAttempt;
|
||||||
@@ -407,13 +344,17 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
/**
|
/**
|
||||||
* Get users that follow a user
|
* Get users that follow a user
|
||||||
*/
|
*/
|
||||||
async getFollowers(userId: string, count = 20): Promise<FollowingResult> {
|
async getFollowers(userId: string, count = 20, cursor?: string): Promise<FollowingResult> {
|
||||||
const variables = {
|
const variables: Record<string, unknown> = {
|
||||||
userId,
|
userId,
|
||||||
count,
|
count,
|
||||||
includePromotedContent: false,
|
includePromotedContent: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (cursor) {
|
||||||
|
variables.cursor = cursor;
|
||||||
|
}
|
||||||
|
|
||||||
const features = buildFollowingFeatures();
|
const features = buildFollowingFeatures();
|
||||||
|
|
||||||
const params = new URLSearchParams({
|
const params = new URLSearchParams({
|
||||||
@@ -467,8 +408,11 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
|
|
||||||
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
|
const instructions = data.data?.user?.result?.timeline?.timeline?.instructions;
|
||||||
const users = parseUsersFromInstructions(instructions);
|
const users = parseUsersFromInstructions(instructions);
|
||||||
|
const nextCursor = extractCursorFromInstructions(
|
||||||
|
instructions as Array<{ entries?: Array<{ content?: unknown }> }> | undefined,
|
||||||
|
);
|
||||||
|
|
||||||
return { success: true as const, users, had404 };
|
return { success: true as const, users, nextCursor, had404 };
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
lastError = error instanceof Error ? error.message : String(error);
|
lastError = error instanceof Error ? error.message : String(error);
|
||||||
}
|
}
|
||||||
@@ -479,18 +423,19 @@ export function withUsers<TBase extends AbstractConstructor<TwitterClientBase>>(
|
|||||||
|
|
||||||
const firstAttempt = await tryOnce();
|
const firstAttempt = await tryOnce();
|
||||||
if (firstAttempt.success) {
|
if (firstAttempt.success) {
|
||||||
return { success: true, users: firstAttempt.users };
|
return { success: true, users: firstAttempt.users, nextCursor: firstAttempt.nextCursor };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (firstAttempt.had404) {
|
if (firstAttempt.had404) {
|
||||||
await this.refreshQueryIds();
|
await this.refreshQueryIds();
|
||||||
const secondAttempt = await tryOnce();
|
const secondAttempt = await tryOnce();
|
||||||
if (secondAttempt.success) {
|
if (secondAttempt.success) {
|
||||||
return { success: true, users: secondAttempt.users };
|
return { success: true, users: secondAttempt.users, nextCursor: secondAttempt.nextCursor };
|
||||||
}
|
}
|
||||||
|
|
||||||
// GraphQL Followers regularly returns 404 (queryId churn / endpoint flakiness).
|
// GraphQL Followers regularly returns 404 (queryId churn / endpoint flakiness).
|
||||||
// Fallback to the internal v1.1 REST endpoint used by the web client (cookie-auth; no dev API key).
|
// 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);
|
||||||
if (restAttempt.success) {
|
if (restAttempt.success) {
|
||||||
return restAttempt;
|
return restAttempt;
|
||||||
|
|||||||
@@ -66,6 +66,253 @@ export function uniqueOrdered(values: string[]): string[] {
|
|||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ============================================================================
|
||||||
|
// Draft.js Content State Types and Parser for Long-form Tweets (X Articles)
|
||||||
|
// ============================================================================
|
||||||
|
|
||||||
|
/** Inline style range for text formatting (Bold, Italic, etc.) */
|
||||||
|
interface InlineStyleRange {
|
||||||
|
offset: number;
|
||||||
|
length: number;
|
||||||
|
style: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Entity range linking a portion of text to an entity in entityMap */
|
||||||
|
interface EntityRange {
|
||||||
|
key: number;
|
||||||
|
offset: number;
|
||||||
|
length: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A content block in Draft.js format */
|
||||||
|
interface ContentBlock {
|
||||||
|
key: string;
|
||||||
|
type: string;
|
||||||
|
text: string;
|
||||||
|
data?: {
|
||||||
|
mentions?: Array<{ fromIndex: number; toIndex: number; text: string }>;
|
||||||
|
};
|
||||||
|
entityRanges?: EntityRange[];
|
||||||
|
inlineStyleRanges?: InlineStyleRange[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Entity data for different entity types */
|
||||||
|
interface EntityValue {
|
||||||
|
type: string;
|
||||||
|
mutability: string;
|
||||||
|
data: {
|
||||||
|
markdown?: string;
|
||||||
|
url?: string;
|
||||||
|
tweetId?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Entity map entry */
|
||||||
|
interface EntityMapEntry {
|
||||||
|
key: string;
|
||||||
|
value: EntityValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Draft.js content state structure */
|
||||||
|
interface ContentState {
|
||||||
|
blocks: ContentBlock[];
|
||||||
|
entityMap?: Array<EntityMapEntry> | Record<string, EntityValue>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders a Draft.js content_state into readable markdown/text format.
|
||||||
|
* Handles blocks (paragraphs, headers, lists) and entities (code blocks, links, tweets, dividers).
|
||||||
|
*/
|
||||||
|
export function renderContentState(contentState: ContentState | undefined): string | undefined {
|
||||||
|
if (!contentState?.blocks || contentState.blocks.length === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build entity lookup map from array/object formats
|
||||||
|
const entityMap = new Map<number, EntityValue>();
|
||||||
|
const rawEntityMap = contentState.entityMap ?? [];
|
||||||
|
if (Array.isArray(rawEntityMap)) {
|
||||||
|
for (const entry of rawEntityMap) {
|
||||||
|
const key = Number.parseInt(entry.key, 10);
|
||||||
|
if (!Number.isNaN(key)) {
|
||||||
|
entityMap.set(key, entry.value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (const [key, value] of Object.entries(rawEntityMap)) {
|
||||||
|
const keyNumber = Number.parseInt(key, 10);
|
||||||
|
if (!Number.isNaN(keyNumber)) {
|
||||||
|
entityMap.set(keyNumber, value);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const outputLines: string[] = [];
|
||||||
|
let orderedListCounter = 0;
|
||||||
|
let previousBlockType: string | undefined;
|
||||||
|
|
||||||
|
for (const block of contentState.blocks) {
|
||||||
|
// Reset ordered list counter when leaving ordered list context
|
||||||
|
if (block.type !== 'ordered-list-item' && previousBlockType === 'ordered-list-item') {
|
||||||
|
orderedListCounter = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (block.type) {
|
||||||
|
case 'unstyled': {
|
||||||
|
// Plain paragraph - just output text with any inline formatting
|
||||||
|
const text = renderBlockText(block, entityMap);
|
||||||
|
if (text) {
|
||||||
|
outputLines.push(text);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'header-one': {
|
||||||
|
const text = renderBlockText(block, entityMap);
|
||||||
|
if (text) {
|
||||||
|
outputLines.push(`# ${text}`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'header-two': {
|
||||||
|
const text = renderBlockText(block, entityMap);
|
||||||
|
if (text) {
|
||||||
|
outputLines.push(`## ${text}`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'header-three': {
|
||||||
|
const text = renderBlockText(block, entityMap);
|
||||||
|
if (text) {
|
||||||
|
outputLines.push(`### ${text}`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'unordered-list-item': {
|
||||||
|
const text = renderBlockText(block, entityMap);
|
||||||
|
if (text) {
|
||||||
|
outputLines.push(`- ${text}`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'ordered-list-item': {
|
||||||
|
orderedListCounter++;
|
||||||
|
const text = renderBlockText(block, entityMap);
|
||||||
|
if (text) {
|
||||||
|
outputLines.push(`${orderedListCounter}. ${text}`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'blockquote': {
|
||||||
|
const text = renderBlockText(block, entityMap);
|
||||||
|
if (text) {
|
||||||
|
outputLines.push(`> ${text}`);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
case 'atomic': {
|
||||||
|
// Atomic blocks are placeholders for embedded entities
|
||||||
|
const entityContent = renderAtomicBlock(block, entityMap);
|
||||||
|
if (entityContent) {
|
||||||
|
outputLines.push(entityContent);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
default: {
|
||||||
|
// Fallback: just output the text
|
||||||
|
const text = renderBlockText(block, entityMap);
|
||||||
|
if (text) {
|
||||||
|
outputLines.push(text);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
previousBlockType = block.type;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = outputLines.join('\n\n');
|
||||||
|
return result.trim() || undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders text content of a block, applying inline link entities.
|
||||||
|
*/
|
||||||
|
function renderBlockText(block: ContentBlock, entityMap: Map<number, EntityValue>): string {
|
||||||
|
let text = block.text;
|
||||||
|
|
||||||
|
// Handle LINK entities by appending URL in markdown format
|
||||||
|
// Process in reverse order to not mess up offsets
|
||||||
|
const linkRanges = (block.entityRanges ?? [])
|
||||||
|
.filter((range) => {
|
||||||
|
const entity = entityMap.get(range.key);
|
||||||
|
return entity?.type === 'LINK' && entity.data.url;
|
||||||
|
})
|
||||||
|
.sort((a, b) => b.offset - a.offset);
|
||||||
|
|
||||||
|
for (const range of linkRanges) {
|
||||||
|
const entity = entityMap.get(range.key);
|
||||||
|
if (entity?.data.url) {
|
||||||
|
const linkText = text.slice(range.offset, range.offset + range.length);
|
||||||
|
const markdownLink = `[${linkText}](${entity.data.url})`;
|
||||||
|
text = text.slice(0, range.offset) + markdownLink + text.slice(range.offset + range.length);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return text.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Renders an atomic block by looking up its entity and returning appropriate content.
|
||||||
|
*/
|
||||||
|
function renderAtomicBlock(block: ContentBlock, entityMap: Map<number, EntityValue>): string | undefined {
|
||||||
|
const entityRanges = block.entityRanges ?? [];
|
||||||
|
if (entityRanges.length === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const entityKey = entityRanges[0].key;
|
||||||
|
const entity = entityMap.get(entityKey);
|
||||||
|
|
||||||
|
if (!entity) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (entity.type) {
|
||||||
|
case 'MARKDOWN':
|
||||||
|
// Code blocks and other markdown content - output as-is
|
||||||
|
return entity.data.markdown?.trim();
|
||||||
|
|
||||||
|
case 'DIVIDER':
|
||||||
|
return '---';
|
||||||
|
|
||||||
|
case 'TWEET':
|
||||||
|
if (entity.data.tweetId) {
|
||||||
|
return `[Embedded Tweet: https://x.com/i/status/${entity.data.tweetId}]`;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
|
||||||
|
case 'LINK':
|
||||||
|
if (entity.data.url) {
|
||||||
|
return `[Link: ${entity.data.url}]`;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
|
||||||
|
case 'IMAGE':
|
||||||
|
// Images in atomic blocks - could extract URL if available
|
||||||
|
return '[Image]';
|
||||||
|
|
||||||
|
default:
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
export function extractArticleText(result: GraphqlTweetResult | undefined): string | undefined {
|
export function extractArticleText(result: GraphqlTweetResult | undefined): string | undefined {
|
||||||
const article = result?.article;
|
const article = result?.article;
|
||||||
if (!article) {
|
if (!article) {
|
||||||
@@ -87,7 +334,31 @@ export function extractArticleText(result: GraphqlTweetResult | undefined): stri
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const title = firstText(articleResult.title, article.title);
|
const title = firstText(articleResult.title, article.title);
|
||||||
|
|
||||||
|
// Try to render from rich content_state first (Draft.js format with blocks + entityMap)
|
||||||
|
// This preserves code blocks, embedded tweets, markdown, etc.
|
||||||
|
const contentState = article.article_results?.result?.content_state;
|
||||||
|
const richBody = renderContentState(contentState);
|
||||||
|
if (richBody) {
|
||||||
|
// Rich content found - prepend title if not already included
|
||||||
|
if (title) {
|
||||||
|
const normalizedTitle = title.trim();
|
||||||
|
const trimmedBody = richBody.trimStart();
|
||||||
|
const headingMatches = [`# ${normalizedTitle}`, `## ${normalizedTitle}`, `### ${normalizedTitle}`];
|
||||||
|
const hasTitle =
|
||||||
|
trimmedBody === normalizedTitle ||
|
||||||
|
trimmedBody.startsWith(`${normalizedTitle}\n`) ||
|
||||||
|
headingMatches.some((heading) => trimmedBody.startsWith(heading));
|
||||||
|
if (!hasTitle) {
|
||||||
|
return `${title}\n\n${richBody}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return richBody;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback to plain text extraction for articles without rich content_state
|
||||||
let body = firstText(
|
let body = firstText(
|
||||||
articleResult.plain_text,
|
articleResult.plain_text,
|
||||||
article.plain_text,
|
article.plain_text,
|
||||||
@@ -153,6 +424,26 @@ export function extractTweetText(result: GraphqlTweetResult | undefined): string
|
|||||||
return extractArticleText(result) ?? extractNoteTweetText(result) ?? firstText(result?.legacy?.full_text);
|
return extractArticleText(result) ?? extractNoteTweetText(result) ?? firstText(result?.legacy?.full_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function extractArticleMetadata(
|
||||||
|
result: GraphqlTweetResult | undefined,
|
||||||
|
): { title: string; previewText?: string } | undefined {
|
||||||
|
const article = result?.article;
|
||||||
|
if (!article) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
const articleResult = article.article_results?.result ?? article;
|
||||||
|
const title = firstText(articleResult.title, article.title);
|
||||||
|
if (!title) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// preview_text is available in home timeline responses
|
||||||
|
const previewText = firstText(articleResult.preview_text, article.preview_text);
|
||||||
|
|
||||||
|
return { title, previewText };
|
||||||
|
}
|
||||||
|
|
||||||
export function extractMedia(result: GraphqlTweetResult | undefined): TweetMedia[] | undefined {
|
export function extractMedia(result: GraphqlTweetResult | undefined): TweetMedia[] | undefined {
|
||||||
// Prefer extended_entities (has video info), fall back to entities
|
// Prefer extended_entities (has video info), fall back to entities
|
||||||
const rawMedia = result?.legacy?.extended_entities?.media ?? result?.legacy?.entities?.media;
|
const rawMedia = result?.legacy?.extended_entities?.media ?? result?.legacy?.entities?.media;
|
||||||
@@ -261,6 +552,7 @@ export function mapTweetResult(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const media = extractMedia(result);
|
const media = extractMedia(result);
|
||||||
|
const article = extractArticleMetadata(result);
|
||||||
|
|
||||||
const tweetData: TweetData = {
|
const tweetData: TweetData = {
|
||||||
id: result.rest_id,
|
id: result.rest_id,
|
||||||
@@ -278,6 +570,7 @@ export function mapTweetResult(
|
|||||||
authorId: userId,
|
authorId: userId,
|
||||||
quotedTweet,
|
quotedTweet,
|
||||||
media,
|
media,
|
||||||
|
article,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (includeRaw) {
|
if (includeRaw) {
|
||||||
|
|||||||
@@ -1,30 +1,50 @@
|
|||||||
import type { AbstractConstructor } from './twitter-client-base.js';
|
import type { AbstractConstructor } from './twitter-client-base.js';
|
||||||
import { TwitterClientBase } from './twitter-client-base.js';
|
import { TwitterClientBase } from './twitter-client-base.js';
|
||||||
import { type TwitterClientBookmarkMethods, withBookmarks } from './twitter-client-bookmarks.js';
|
import { type TwitterClientBookmarkMethods, withBookmarks } from './twitter-client-bookmarks.js';
|
||||||
|
import { type TwitterClientHomeMethods, withHome } from './twitter-client-home.js';
|
||||||
import { type TwitterClientListMethods, withLists } from './twitter-client-lists.js';
|
import { type TwitterClientListMethods, withLists } from './twitter-client-lists.js';
|
||||||
import { type TwitterClientMediaMethods, withMedia } from './twitter-client-media.js';
|
import { type TwitterClientMediaMethods, withMedia } from './twitter-client-media.js';
|
||||||
|
import { type TwitterClientNewsMethods, withNews } from './twitter-client-news.js';
|
||||||
import { type TwitterClientPostingMethods, withPosting } from './twitter-client-posting.js';
|
import { type TwitterClientPostingMethods, withPosting } from './twitter-client-posting.js';
|
||||||
import { type TwitterClientSearchMethods, withSearch } from './twitter-client-search.js';
|
import { type TwitterClientSearchMethods, withSearch } from './twitter-client-search.js';
|
||||||
import { type TwitterClientTimelineMethods, withTimelines } from './twitter-client-timelines.js';
|
import { type TwitterClientTimelineMethods, withTimelines } from './twitter-client-timelines.js';
|
||||||
import { type TwitterClientTweetDetailMethods, withTweetDetails } from './twitter-client-tweet-detail.js';
|
import { type TwitterClientTweetDetailMethods, withTweetDetails } from './twitter-client-tweet-detail.js';
|
||||||
|
import { type TwitterClientUserLookupMethods, withUserLookup } from './twitter-client-user-lookup.js';
|
||||||
|
import { type TwitterClientUserTweetsMethods, withUserTweets } from './twitter-client-user-tweets.js';
|
||||||
import { type TwitterClientUserMethods, withUsers } from './twitter-client-users.js';
|
import { type TwitterClientUserMethods, withUsers } from './twitter-client-users.js';
|
||||||
|
|
||||||
type TwitterClientInstance = TwitterClientBase &
|
type TwitterClientInstance = TwitterClientBase &
|
||||||
TwitterClientBookmarkMethods &
|
TwitterClientBookmarkMethods &
|
||||||
|
TwitterClientHomeMethods &
|
||||||
TwitterClientListMethods &
|
TwitterClientListMethods &
|
||||||
TwitterClientMediaMethods &
|
TwitterClientMediaMethods &
|
||||||
|
TwitterClientNewsMethods &
|
||||||
TwitterClientPostingMethods &
|
TwitterClientPostingMethods &
|
||||||
TwitterClientSearchMethods &
|
TwitterClientSearchMethods &
|
||||||
TwitterClientTimelineMethods &
|
TwitterClientTimelineMethods &
|
||||||
TwitterClientTweetDetailMethods &
|
TwitterClientTweetDetailMethods &
|
||||||
TwitterClientUserMethods;
|
TwitterClientUserMethods &
|
||||||
|
TwitterClientUserLookupMethods &
|
||||||
|
TwitterClientUserTweetsMethods;
|
||||||
|
|
||||||
const MixedTwitterClient = withUsers(
|
// News mixin wraps search because it depends on the search() method
|
||||||
withLists(withTimelines(withSearch(withTweetDetails(withPosting(withBookmarks(withMedia(TwitterClientBase))))))),
|
const MixedTwitterClient = withNews(
|
||||||
|
withUserTweets(
|
||||||
|
withUserLookup(
|
||||||
|
withUsers(
|
||||||
|
withLists(
|
||||||
|
withHome(
|
||||||
|
withTimelines(withSearch(withTweetDetails(withPosting(withBookmarks(withMedia(TwitterClientBase)))))),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
) as AbstractConstructor<TwitterClientInstance>;
|
) as AbstractConstructor<TwitterClientInstance>;
|
||||||
|
|
||||||
export class TwitterClient extends MixedTwitterClient {}
|
export class TwitterClient extends MixedTwitterClient {}
|
||||||
|
|
||||||
|
export type { NewsFetchOptions, NewsItem, NewsResult } from './twitter-client-news.js';
|
||||||
export type {
|
export type {
|
||||||
BookmarkMutationResult,
|
BookmarkMutationResult,
|
||||||
CurrentUserResult,
|
CurrentUserResult,
|
||||||
|
|||||||
@@ -8,10 +8,7 @@ describe('bookmarks command', () => {
|
|||||||
const program = new Command();
|
const program = new Command();
|
||||||
const ctx = {
|
const ctx = {
|
||||||
resolveTimeoutFromOptions: () => undefined,
|
resolveTimeoutFromOptions: () => undefined,
|
||||||
resolveCredentialsFromOptions: async () => ({
|
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||||
cookies: { authToken: 'auth', ct0: 'ct0', cookieHeader: 'auth=auth; ct0=ct0' },
|
|
||||||
warnings: [],
|
|
||||||
}),
|
|
||||||
p: () => '',
|
p: () => '',
|
||||||
printTweets: () => undefined,
|
printTweets: () => undefined,
|
||||||
} as unknown as CliContext;
|
} as unknown as CliContext;
|
||||||
|
|||||||
@@ -0,0 +1,155 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { CliContext } from '../src/cli/shared.js';
|
||||||
|
import { registerNewsCommand } from '../src/commands/news.js';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
|
||||||
|
describe('news command', () => {
|
||||||
|
let program: Command;
|
||||||
|
let mockContext: Partial<CliContext>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
program = new Command();
|
||||||
|
mockContext = {
|
||||||
|
resolveTimeoutFromOptions: () => 30000,
|
||||||
|
resolveQuoteDepthFromOptions: () => undefined,
|
||||||
|
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||||
|
p: (type: string) => `[${type}] `,
|
||||||
|
colors: {
|
||||||
|
accent: (text: string) => text,
|
||||||
|
command: (text: string) => text,
|
||||||
|
muted: (text: string) => text,
|
||||||
|
section: (text: string) => text,
|
||||||
|
},
|
||||||
|
l: (key: string) => key,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires positive count value', async () => {
|
||||||
|
registerNewsCommand(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'news', '--count', '0'])).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--count must be a positive number'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects negative count value', async () => {
|
||||||
|
registerNewsCommand(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'news', '--count', '-5'])).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--count must be a positive number'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects non-numeric count value', async () => {
|
||||||
|
registerNewsCommand(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'news', '--count', 'abc'])).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--count must be a positive number'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires positive tweets-per-item value', async () => {
|
||||||
|
registerNewsCommand(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'news', '--tweets-per-item', '0'])).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--tweets-per-item must be a positive number'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects negative tweets-per-item value', async () => {
|
||||||
|
registerNewsCommand(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'news', '--tweets-per-item', '-3'])).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--tweets-per-item must be a positive number'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects non-numeric tweets-per-item value', async () => {
|
||||||
|
registerNewsCommand(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'news', '--tweets-per-item', 'xyz'])).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--tweets-per-item must be a positive number'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('limits related tweets to tweets-per-item in CLI output', async () => {
|
||||||
|
registerNewsCommand(program, mockContext as CliContext);
|
||||||
|
const getNewsSpy = vi.spyOn(TwitterClient.prototype, 'getNews').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 'item-1',
|
||||||
|
headline: 'News headline',
|
||||||
|
category: 'News',
|
||||||
|
tweets: [
|
||||||
|
{ id: 't1', text: 'first tweet', author: { username: 'a', name: 'A' } },
|
||||||
|
{ id: 't2', text: 'second tweet', author: { username: 'b', name: 'B' } },
|
||||||
|
{ id: 't3', text: 'third tweet', author: { username: 'c', name: 'C' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await program.parseAsync(['node', 'bird', 'news', '--with-tweets', '--tweets-per-item', '2', '--count', '1']);
|
||||||
|
expect(getNewsSpy).toHaveBeenCalledWith(1, expect.objectContaining({ tweetsPerItem: 2, withTweets: true }));
|
||||||
|
const tweetLines = logSpy.mock.calls
|
||||||
|
.map((call) => String(call[0]))
|
||||||
|
.filter((line) => line.trimStart().startsWith('@'));
|
||||||
|
expect(tweetLines).toHaveLength(2);
|
||||||
|
} finally {
|
||||||
|
getNewsSpy.mockRestore();
|
||||||
|
logSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import { describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { CliContext } from '../src/cli/shared.js';
|
||||||
|
import { registerReadCommands } from '../src/commands/read.js';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
|
||||||
|
describe('replies command', () => {
|
||||||
|
const createMockContext = () =>
|
||||||
|
({
|
||||||
|
resolveTimeoutFromOptions: () => undefined,
|
||||||
|
resolveQuoteDepthFromOptions: () => 1,
|
||||||
|
extractTweetId: (input: string) => input,
|
||||||
|
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||||
|
p: () => '',
|
||||||
|
printTweets: () => undefined,
|
||||||
|
printTweetsResult: () => undefined,
|
||||||
|
}) as unknown as CliContext;
|
||||||
|
|
||||||
|
it('uses pagination when --max-pages is provided', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerReadCommands(program, createMockContext());
|
||||||
|
|
||||||
|
const pagedSpy = vi
|
||||||
|
.spyOn(TwitterClient.prototype, 'getRepliesPaged')
|
||||||
|
.mockResolvedValue({ success: true, tweets: [], nextCursor: undefined });
|
||||||
|
const unpagedSpy = vi.spyOn(TwitterClient.prototype, 'getReplies').mockResolvedValue({ success: true, tweets: [] });
|
||||||
|
|
||||||
|
try {
|
||||||
|
await program.parseAsync(['node', 'bird', 'replies', '123', '--max-pages', '2', '--json']);
|
||||||
|
expect(pagedSpy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(unpagedSpy).toHaveBeenCalledTimes(0);
|
||||||
|
} finally {
|
||||||
|
pagedSpy.mockRestore();
|
||||||
|
unpagedSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates --max-pages is a positive integer', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerReadCommands(program, createMockContext());
|
||||||
|
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(
|
||||||
|
program.parseAsync(['node', 'bird', 'replies', '123', '--all', '--max-pages', '-1']),
|
||||||
|
).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid --max-pages'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates --delay is a non-negative integer', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerReadCommands(program, createMockContext());
|
||||||
|
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'replies', '123', '--all', '--delay', '-100'])).rejects.toThrow(
|
||||||
|
'exit 1',
|
||||||
|
);
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid --delay'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('thread command', () => {
|
||||||
|
const createMockContext = () =>
|
||||||
|
({
|
||||||
|
resolveTimeoutFromOptions: () => undefined,
|
||||||
|
resolveQuoteDepthFromOptions: () => 1,
|
||||||
|
extractTweetId: (input: string) => input,
|
||||||
|
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||||
|
p: () => '',
|
||||||
|
printTweets: () => undefined,
|
||||||
|
printTweetsResult: () => undefined,
|
||||||
|
}) as unknown as CliContext;
|
||||||
|
|
||||||
|
it('uses pagination when --max-pages is provided', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerReadCommands(program, createMockContext());
|
||||||
|
|
||||||
|
const pagedSpy = vi
|
||||||
|
.spyOn(TwitterClient.prototype, 'getThreadPaged')
|
||||||
|
.mockResolvedValue({ success: true, tweets: [], nextCursor: undefined });
|
||||||
|
const unpagedSpy = vi.spyOn(TwitterClient.prototype, 'getThread').mockResolvedValue({ success: true, tweets: [] });
|
||||||
|
|
||||||
|
try {
|
||||||
|
await program.parseAsync(['node', 'bird', 'thread', '123', '--max-pages', '2', '--json']);
|
||||||
|
expect(pagedSpy).toHaveBeenCalledTimes(1);
|
||||||
|
expect(unpagedSpy).toHaveBeenCalledTimes(0);
|
||||||
|
} finally {
|
||||||
|
pagedSpy.mockRestore();
|
||||||
|
unpagedSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates --max-pages is a positive integer', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerReadCommands(program, createMockContext());
|
||||||
|
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'thread', '123', '--all', '--max-pages', '0'])).rejects.toThrow(
|
||||||
|
'exit 1',
|
||||||
|
);
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid --max-pages'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates --delay is a non-negative integer', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerReadCommands(program, createMockContext());
|
||||||
|
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'thread', '123', '--all', '--delay', 'abc'])).rejects.toThrow(
|
||||||
|
'exit 1',
|
||||||
|
);
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid --delay'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
import { Command } from 'commander';
|
||||||
|
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import type { CliContext } from '../src/cli/shared.js';
|
||||||
|
import { registerSearchCommands } from '../src/commands/search.js';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
|
||||||
|
describe('search command', () => {
|
||||||
|
let program: Command;
|
||||||
|
let mockContext: Partial<CliContext>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
program = new Command();
|
||||||
|
mockContext = {
|
||||||
|
resolveTimeoutFromOptions: () => undefined,
|
||||||
|
resolveQuoteDepthFromOptions: () => undefined,
|
||||||
|
resolveRelayBaseUrlFromOptions: () => 'https://relay.example',
|
||||||
|
p: () => '',
|
||||||
|
printTweetsResult: vi.fn(),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires --all or --cursor when --max-pages is provided', async () => {
|
||||||
|
registerSearchCommands(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'search', 'cats', '--max-pages', '2'])).rejects.toThrow(
|
||||||
|
'exit 1',
|
||||||
|
);
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--max-pages requires --all or --cursor'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires positive --count when not paging', async () => {
|
||||||
|
registerSearchCommands(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'search', 'cats', '--count', '0'])).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Invalid --count. Expected a positive integer.'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires positive --max-pages when paging', async () => {
|
||||||
|
registerSearchCommands(program, mockContext as CliContext);
|
||||||
|
const exitSpy = vi.spyOn(process, 'exit').mockImplementation(((code?: number) => {
|
||||||
|
throw new Error(`exit ${code}`);
|
||||||
|
}) as never);
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'search', 'cats', '--all', '--max-pages', '0'])).rejects.toThrow(
|
||||||
|
'exit 1',
|
||||||
|
);
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining('Invalid --max-pages. Expected a positive integer.'),
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses paged search when --all is set', async () => {
|
||||||
|
registerSearchCommands(program, mockContext as CliContext);
|
||||||
|
const getAllSpy = vi
|
||||||
|
.spyOn(TwitterClient.prototype, 'getAllSearchResults')
|
||||||
|
.mockResolvedValue({ success: true, tweets: [] });
|
||||||
|
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 }));
|
||||||
|
expect(searchSpy).not.toHaveBeenCalled();
|
||||||
|
expect(mockContext.printTweetsResult).toHaveBeenCalledWith(expect.objectContaining({ tweets: [] }), {
|
||||||
|
json: true,
|
||||||
|
usePagination: true,
|
||||||
|
emptyMessage: 'No tweets found.',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
getAllSpy.mockRestore();
|
||||||
|
searchSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses cursor pagination when --cursor is set', async () => {
|
||||||
|
registerSearchCommands(program, mockContext as CliContext);
|
||||||
|
const getAllSpy = vi
|
||||||
|
.spyOn(TwitterClient.prototype, 'getAllSearchResults')
|
||||||
|
.mockResolvedValue({ success: true, tweets: [] });
|
||||||
|
|
||||||
|
try {
|
||||||
|
await program.parseAsync(['node', 'bird', 'search', 'cats', '--cursor', 'cursor-1']);
|
||||||
|
expect(getAllSpy).toHaveBeenCalledWith('cats', expect.objectContaining({ cursor: 'cursor-1' }));
|
||||||
|
expect(mockContext.printTweetsResult).toHaveBeenCalledWith(expect.objectContaining({ tweets: [] }), {
|
||||||
|
json: false,
|
||||||
|
usePagination: true,
|
||||||
|
emptyMessage: 'No tweets found.',
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
getAllSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,211 @@
|
|||||||
|
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: () => 'https://relay.example',
|
||||||
|
p: () => '',
|
||||||
|
printTweets: () => undefined,
|
||||||
|
} as unknown as CliContext;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('users commands', () => {
|
||||||
|
it('requires --all when --max-pages is provided', 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);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(program.parseAsync(['node', 'bird', 'following', '--max-pages', '2'])).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--max-pages requires --all.'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects --max-pages when only --cursor is provided', 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);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await expect(
|
||||||
|
program.parseAsync(['node', 'bird', 'following', '--cursor', 'prev', '--max-pages', '2']),
|
||||||
|
).rejects.toThrow('exit 1');
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('--max-pages requires --all.'));
|
||||||
|
} finally {
|
||||||
|
exitSpy.mockRestore();
|
||||||
|
errorSpy.mockRestore();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits pagination JSON when --cursor is provided', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerUserCommands(program, baseCtx);
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getCurrentUser').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
user: { id: '123', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getFollowing').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
users: [{ id: '1', username: 'alpha', name: 'Alpha' }],
|
||||||
|
nextCursor: 'next-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||||
|
await program.parseAsync(['node', 'bird', 'following', '--cursor', 'prev', '--json']);
|
||||||
|
|
||||||
|
const payload = JSON.parse(String(logSpy.mock.calls[0]?.[0]));
|
||||||
|
expect(payload.users).toHaveLength(1);
|
||||||
|
expect(payload.nextCursor).toBe('next-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prints next cursor in non-JSON single-page mode', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerUserCommands(program, baseCtx);
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getCurrentUser').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
user: { id: '123', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getFollowing').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
users: [{ id: '1', username: 'alpha', name: 'Alpha' }],
|
||||||
|
nextCursor: 'next-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||||
|
await program.parseAsync(['node', 'bird', 'following', '--cursor', 'prev']);
|
||||||
|
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Next cursor: next-1'));
|
||||||
|
expect(logSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('emits pagination JSON for --all results', async () => {
|
||||||
|
const program = new Command();
|
||||||
|
registerUserCommands(program, baseCtx);
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getCurrentUser').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
user: { id: '123', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getFollowing').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
users: [{ id: '1', username: 'alpha', name: 'Alpha' }],
|
||||||
|
nextCursor: 'next-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||||
|
await program.parseAsync(['node', 'bird', 'following', '--all', '--max-pages', '1', '--json']);
|
||||||
|
|
||||||
|
const payload = JSON.parse(String(logSpy.mock.calls[0]?.[0]));
|
||||||
|
expect(payload.users).toHaveLength(1);
|
||||||
|
expect(payload.nextCursor).toBe('next-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('prints next cursor when stopping at max pages in non-JSON mode', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const program = new Command();
|
||||||
|
registerUserCommands(program, baseCtx);
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getCurrentUser').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
user: { id: '123', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getFollowing').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
users: [{ id: '1', username: 'alpha', name: 'Alpha' }],
|
||||||
|
nextCursor: 'next-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined);
|
||||||
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||||
|
const run = program.parseAsync(['node', 'bird', 'following', '--all', '--max-pages', '1']);
|
||||||
|
await vi.advanceTimersByTimeAsync(1000);
|
||||||
|
await run;
|
||||||
|
|
||||||
|
expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining('Next cursor: next-1'));
|
||||||
|
expect(logSpy).toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deduplicates users across pages in --all mode', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const program = new Command();
|
||||||
|
registerUserCommands(program, baseCtx);
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getCurrentUser').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
user: { id: '123', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
const followingSpy = vi.spyOn(TwitterClient.prototype, 'getFollowing');
|
||||||
|
followingSpy
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
success: true,
|
||||||
|
users: [
|
||||||
|
{ id: '1', username: 'alpha', name: 'Alpha' },
|
||||||
|
{ id: '2', username: 'beta', name: 'Beta' },
|
||||||
|
],
|
||||||
|
nextCursor: 'cursor-1',
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
success: true,
|
||||||
|
users: [
|
||||||
|
{ id: '2', username: 'beta', name: 'Beta' },
|
||||||
|
{ id: '3', username: 'gamma', name: 'Gamma' },
|
||||||
|
],
|
||||||
|
nextCursor: undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||||
|
const run = program.parseAsync(['node', 'bird', 'following', '--all', '--json']);
|
||||||
|
await vi.advanceTimersByTimeAsync(1000);
|
||||||
|
await run;
|
||||||
|
|
||||||
|
const payload = JSON.parse(String(logSpy.mock.calls[0]?.[0]));
|
||||||
|
expect(payload.users).toHaveLength(3);
|
||||||
|
expect(payload.users.map((user: { id: string }) => user.id)).toEqual(['1', '2', '3']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops pagination when cursor repeats or no new users are added', async () => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
const program = new Command();
|
||||||
|
registerUserCommands(program, baseCtx);
|
||||||
|
vi.spyOn(TwitterClient.prototype, 'getCurrentUser').mockResolvedValue({
|
||||||
|
success: true,
|
||||||
|
user: { id: '123', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
const followingSpy = vi.spyOn(TwitterClient.prototype, 'getFollowing');
|
||||||
|
followingSpy
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
success: true,
|
||||||
|
users: [{ id: '1', username: 'alpha', name: 'Alpha' }],
|
||||||
|
nextCursor: 'cursor-1',
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
success: true,
|
||||||
|
users: [{ id: '1', username: 'alpha', name: 'Alpha' }],
|
||||||
|
nextCursor: 'cursor-1',
|
||||||
|
});
|
||||||
|
|
||||||
|
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => undefined);
|
||||||
|
const run = program.parseAsync(['node', 'bird', 'following', '--all', '--json']);
|
||||||
|
await vi.advanceTimersByTimeAsync(1000);
|
||||||
|
await run;
|
||||||
|
|
||||||
|
const payload = JSON.parse(String(logSpy.mock.calls[0]?.[0]));
|
||||||
|
expect(payload.users).toHaveLength(1);
|
||||||
|
expect(payload.nextCursor).toBeNull();
|
||||||
|
expect(followingSpy).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,381 +0,0 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
|
|
||||||
type SweetCookieResult = { cookies: Array<{ name: string; value: string; domain?: string }>; warnings: string[] };
|
|
||||||
|
|
||||||
const sweet = vi.hoisted(() => ({
|
|
||||||
results: new Map<string, SweetCookieResult>(),
|
|
||||||
options: new Map<string, { timeoutMs?: number }>(),
|
|
||||||
}));
|
|
||||||
|
|
||||||
vi.mock('@steipete/sweet-cookie', () => ({
|
|
||||||
getCookies: vi.fn(async (options: { browsers?: string[]; timeoutMs?: number }) => {
|
|
||||||
const browser = options.browsers?.[0] ?? 'unknown';
|
|
||||||
sweet.options.set(browser, options);
|
|
||||||
return (
|
|
||||||
sweet.results.get(browser) ?? {
|
|
||||||
cookies: [],
|
|
||||||
warnings: [],
|
|
||||||
}
|
|
||||||
);
|
|
||||||
}),
|
|
||||||
}));
|
|
||||||
|
|
||||||
describe('cookies', () => {
|
|
||||||
const originalEnv = process.env;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
vi.resetModules();
|
|
||||||
sweet.results.clear();
|
|
||||||
sweet.options.clear();
|
|
||||||
process.env = { ...originalEnv };
|
|
||||||
process.env.AUTH_TOKEN = undefined;
|
|
||||||
process.env.TWITTER_AUTH_TOKEN = undefined;
|
|
||||||
process.env.CT0 = undefined;
|
|
||||||
process.env.TWITTER_CT0 = undefined;
|
|
||||||
});
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
process.env = originalEnv;
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('resolveCredentials', () => {
|
|
||||||
it('honors cookieSource=firefox even when Safari has cookies', async () => {
|
|
||||||
sweet.results.set('safari', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'safari_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'safari_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
sweet.results.set('firefox', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'firefox_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'firefox_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'firefox' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('firefox_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('firefox_ct0');
|
|
||||||
expect(result.cookies.source).toContain('Firefox');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('honors cookieSource=safari', async () => {
|
|
||||||
if (process.platform !== 'darwin') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sweet.results.set('safari', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'safari_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'safari_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'safari' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('safari_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('safari_ct0');
|
|
||||||
expect(result.cookies.cookieHeader).toContain('auth_token=safari_auth');
|
|
||||||
expect(result.cookies.cookieHeader).toContain('ct0=safari_ct0');
|
|
||||||
expect(result.cookies.source).toBe('Safari');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('uses firefox when enabled and returns cookies', async () => {
|
|
||||||
sweet.results.set('firefox', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'firefox_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'firefox_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'firefox', firefoxProfile: 'abc.default-release' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('firefox_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('firefox_ct0');
|
|
||||||
expect(result.cookies.cookieHeader).toContain('auth_token=firefox_auth');
|
|
||||||
expect(result.cookies.cookieHeader).toContain('ct0=firefox_ct0');
|
|
||||||
expect(result.cookies.source).toContain('Firefox');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should prioritize CLI arguments over env vars', async () => {
|
|
||||||
process.env.AUTH_TOKEN = 'env_auth';
|
|
||||||
process.env.CT0 = 'env_ct0';
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({
|
|
||||||
authToken: 'cli_auth',
|
|
||||||
ct0: 'cli_ct0',
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('cli_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('cli_ct0');
|
|
||||||
expect(result.cookies.cookieHeader).toBe('auth_token=cli_auth; ct0=cli_ct0');
|
|
||||||
expect(result.cookies.source).toBe('CLI argument');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should use AUTH_TOKEN env var', async () => {
|
|
||||||
process.env.AUTH_TOKEN = 'test_auth_token';
|
|
||||||
process.env.CT0 = 'test_ct0';
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'safari' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('test_auth_token');
|
|
||||||
expect(result.cookies.ct0).toBe('test_ct0');
|
|
||||||
expect(result.cookies.source).toBe('env AUTH_TOKEN');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should use TWITTER_AUTH_TOKEN env var as fallback', async () => {
|
|
||||||
process.env.TWITTER_AUTH_TOKEN = 'twitter_auth';
|
|
||||||
process.env.TWITTER_CT0 = 'twitter_ct0';
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'safari' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('twitter_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('twitter_ct0');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should trim whitespace from values', async () => {
|
|
||||||
process.env.AUTH_TOKEN = ' trimmed_auth ';
|
|
||||||
process.env.CT0 = ' trimmed_ct0 ';
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({});
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('trimmed_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('trimmed_ct0');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should treat empty strings as null', async () => {
|
|
||||||
process.env.AUTH_TOKEN = ' ';
|
|
||||||
process.env.CT0 = '';
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'safari' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBeNull();
|
|
||||||
expect(result.cookies.ct0).toBeNull();
|
|
||||||
expect(result.warnings.length).toBeGreaterThan(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should warn when credentials are missing', async () => {
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'safari' });
|
|
||||||
|
|
||||||
expect(result.warnings).toContain(
|
|
||||||
'Missing auth_token - provide via --auth-token, AUTH_TOKEN env var, or login to x.com in Safari/Chrome/Firefox',
|
|
||||||
);
|
|
||||||
expect(result.warnings).toContain(
|
|
||||||
'Missing ct0 - provide via --ct0, CT0 env var, or login to x.com in Safari/Chrome/Firefox',
|
|
||||||
);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('falls back to Chrome when enabled and Firefox disabled', async () => {
|
|
||||||
sweet.results.set('chrome', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'test_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'test_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({
|
|
||||||
cookieSource: 'chrome',
|
|
||||||
chromeProfile: 'Default',
|
|
||||||
cookieTimeoutMs: 15000,
|
|
||||||
});
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('test_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('test_ct0');
|
|
||||||
expect(result.cookies.source).toContain('Chrome');
|
|
||||||
expect(sweet.options.get('chrome')?.timeoutMs).toBe(15000);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('defaults to a 30s cookie timeout on macOS', async () => {
|
|
||||||
if (process.platform !== 'darwin') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sweet.results.set('chrome', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'test_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'test_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'chrome' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('test_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('test_ct0');
|
|
||||||
expect(sweet.options.get('chrome')?.timeoutMs).toBe(30000);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('uses default browser order when cookieSource is omitted', async () => {
|
|
||||||
sweet.results.set('safari', { cookies: [], warnings: [] });
|
|
||||||
sweet.results.set('chrome', { cookies: [], warnings: [] });
|
|
||||||
sweet.results.set('firefox', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'firefox_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'firefox_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({});
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('firefox_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('firefox_ct0');
|
|
||||||
expect(result.cookies.source).toContain('Firefox');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('prefers twitter.com cookies when x.com is missing', async () => {
|
|
||||||
sweet.results.set('chrome', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'twitter_auth', domain: 'twitter.com' },
|
|
||||||
{ name: 'ct0', value: 'twitter_ct0', domain: 'twitter.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'chrome' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('twitter_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('twitter_ct0');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('falls back to the first cookie when no domain matches', async () => {
|
|
||||||
sweet.results.set('firefox', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'first_auth', domain: 'example.com' },
|
|
||||||
{ name: 'ct0', value: 'first_ct0', domain: 'example.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: 'firefox' });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('first_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('first_ct0');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('extractCookiesFromSafari', () => {
|
|
||||||
it('returns cookies from Safari', async () => {
|
|
||||||
if (process.platform !== 'darwin') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sweet.results.set('safari', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'safari_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'safari_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { extractCookiesFromSafari } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await extractCookiesFromSafari();
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('safari_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('safari_ct0');
|
|
||||||
expect(result.cookies.source).toBe('Safari');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('prefers Safari over Chrome when both are available', async () => {
|
|
||||||
if (process.platform !== 'darwin') {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
sweet.results.set('safari', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'safari_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'safari_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
sweet.results.set('chrome', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'chrome_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'chrome_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { resolveCredentials } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await resolveCredentials({ cookieSource: ['safari', 'chrome'] });
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('safari_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('safari_ct0');
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('extractCookiesFromChrome', () => {
|
|
||||||
it('returns cookies when Chrome yields values', async () => {
|
|
||||||
sweet.results.set('chrome', {
|
|
||||||
cookies: [
|
|
||||||
{ name: 'auth_token', value: 'test_auth', domain: 'x.com' },
|
|
||||||
{ name: 'ct0', value: 'test_ct0', domain: 'x.com' },
|
|
||||||
],
|
|
||||||
warnings: [],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { extractCookiesFromChrome } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await extractCookiesFromChrome('Default');
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBe('test_auth');
|
|
||||||
expect(result.cookies.ct0).toBe('test_ct0');
|
|
||||||
expect(result.cookies.source).toContain('Chrome');
|
|
||||||
expect(result.warnings).toHaveLength(0);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('warns when Chrome returns no cookies', async () => {
|
|
||||||
sweet.results.set('chrome', { cookies: [], warnings: [] });
|
|
||||||
|
|
||||||
const { extractCookiesFromChrome } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await extractCookiesFromChrome('Default');
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBeNull();
|
|
||||||
expect(result.cookies.ct0).toBeNull();
|
|
||||||
expect(result.warnings.some((w) => w.includes('No Twitter cookies found in Chrome'))).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('extractCookiesFromFirefox', () => {
|
|
||||||
it('warns when Firefox cookies database is missing', async () => {
|
|
||||||
sweet.results.set('firefox', {
|
|
||||||
cookies: [],
|
|
||||||
warnings: ['Firefox cookies database not found.'],
|
|
||||||
});
|
|
||||||
|
|
||||||
const { extractCookiesFromFirefox } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await extractCookiesFromFirefox('missing-profile');
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBeNull();
|
|
||||||
expect(result.cookies.ct0).toBeNull();
|
|
||||||
expect(result.warnings).toContain('Firefox cookies database not found.');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('warns when Firefox returns no cookies', async () => {
|
|
||||||
sweet.results.set('firefox', { cookies: [], warnings: [] });
|
|
||||||
|
|
||||||
const { extractCookiesFromFirefox } = await import('../src/lib/cookies.js');
|
|
||||||
const result = await extractCookiesFromFirefox('abc.default-release');
|
|
||||||
|
|
||||||
expect(result.cookies.authToken).toBeNull();
|
|
||||||
expect(result.cookies.ct0).toBeNull();
|
|
||||||
expect(result.warnings.some((w) => w.includes('No Twitter cookies found in Firefox'))).toBe(true);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { GraphqlTweetResult } from '../src/lib/twitter-client-types.js';
|
||||||
|
import { extractArticleMetadata } from '../src/lib/twitter-client-utils.js';
|
||||||
|
|
||||||
|
describe('extractArticleMetadata', () => {
|
||||||
|
it('returns undefined when no result', () => {
|
||||||
|
expect(extractArticleMetadata(undefined)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns undefined when no article field', () => {
|
||||||
|
const result: GraphqlTweetResult = {
|
||||||
|
rest_id: '123',
|
||||||
|
legacy: { full_text: 'Hello world' },
|
||||||
|
};
|
||||||
|
expect(extractArticleMetadata(result)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns undefined when article has no title', () => {
|
||||||
|
const result: GraphqlTweetResult = {
|
||||||
|
rest_id: '123',
|
||||||
|
article: {
|
||||||
|
article_results: {
|
||||||
|
result: {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
expect(extractArticleMetadata(result)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extracts title from article_results.result', () => {
|
||||||
|
const result: GraphqlTweetResult = {
|
||||||
|
rest_id: '123',
|
||||||
|
article: {
|
||||||
|
article_results: {
|
||||||
|
result: {
|
||||||
|
title: 'Building Context Graphs for GTM',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const metadata = extractArticleMetadata(result);
|
||||||
|
expect(metadata).toEqual({
|
||||||
|
title: 'Building Context Graphs for GTM',
|
||||||
|
previewText: undefined,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extracts title and preview_text from article_results.result', () => {
|
||||||
|
const result: GraphqlTweetResult = {
|
||||||
|
rest_id: '123',
|
||||||
|
article: {
|
||||||
|
article_results: {
|
||||||
|
result: {
|
||||||
|
title: 'Building Context Graphs for GTM',
|
||||||
|
preview_text:
|
||||||
|
'Foundation Capital recently argued that one of the next trillion-dollar opportunities in AI will come from context graphs.',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as GraphqlTweetResult;
|
||||||
|
|
||||||
|
const metadata = extractArticleMetadata(result);
|
||||||
|
expect(metadata).toEqual({
|
||||||
|
title: 'Building Context Graphs for GTM',
|
||||||
|
previewText:
|
||||||
|
'Foundation Capital recently argued that one of the next trillion-dollar opportunities in AI will come from context graphs.',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to article.title when article_results.result.title missing', () => {
|
||||||
|
const result: GraphqlTweetResult = {
|
||||||
|
rest_id: '123',
|
||||||
|
article: {
|
||||||
|
title: 'Fallback Title',
|
||||||
|
article_results: {
|
||||||
|
result: {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const metadata = extractArticleMetadata(result);
|
||||||
|
expect(metadata).toEqual({
|
||||||
|
title: 'Fallback Title',
|
||||||
|
previewText: undefined,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { GraphqlTweetResult } from '../src/lib/twitter-client-types.js';
|
||||||
|
import { extractArticleText } from '../src/lib/twitter-client-utils.js';
|
||||||
|
|
||||||
|
describe('extractArticleText', () => {
|
||||||
|
it('does not duplicate title when rich content starts with a heading', () => {
|
||||||
|
const result = {
|
||||||
|
rest_id: '1',
|
||||||
|
article: {
|
||||||
|
title: 'Hello World',
|
||||||
|
article_results: {
|
||||||
|
result: {
|
||||||
|
title: 'Hello World',
|
||||||
|
content_state: {
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
key: '1',
|
||||||
|
type: 'header-one',
|
||||||
|
text: 'Hello World',
|
||||||
|
entityRanges: [],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
entityMap: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
} as GraphqlTweetResult;
|
||||||
|
|
||||||
|
expect(extractArticleText(result)).toBe('# Hello World');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -45,8 +45,9 @@ describe('root help output', () => {
|
|||||||
|
|
||||||
cmd.outputHelp();
|
cmd.outputHelp();
|
||||||
|
|
||||||
expect(help).toContain('--auth-token');
|
expect(help).toContain('--relay-base-url');
|
||||||
expect(help).toContain('--ct0');
|
expect(help).not.toContain('--auth-token');
|
||||||
|
expect(help).not.toContain('--ct0');
|
||||||
expect(help).toContain('--timeout');
|
expect(help).toContain('--timeout');
|
||||||
expect(help).toContain('--quote-depth');
|
expect(help).toContain('--quote-depth');
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
import { resolveCredentials, TwitterClient } from '../src/index.js';
|
import { TwitterClient } from '../src/index.js';
|
||||||
|
|
||||||
describe('library exports', () => {
|
describe('library exports', () => {
|
||||||
it('exposes primary library surface', () => {
|
it('exposes primary library surface', () => {
|
||||||
expect(typeof TwitterClient).toBe('function');
|
expect(typeof TwitterClient).toBe('function');
|
||||||
expect(typeof resolveCredentials).toBe('function');
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,367 @@
|
|||||||
|
import { spawn } from 'node:child_process';
|
||||||
|
import { existsSync } from 'node:fs';
|
||||||
|
import path from 'node:path';
|
||||||
|
import { beforeAll, describe, expect, it } from 'vitest';
|
||||||
|
|
||||||
|
type RunResult = { exitCode: number; stdout: string; stderr: string; signal: NodeJS.Signals | null };
|
||||||
|
|
||||||
|
const LIVE = process.env.BIRD_LIVE === '1';
|
||||||
|
|
||||||
|
const relayBaseUrl = (process.env.TWITTER_RELAY_BASE_URL ?? '').trim();
|
||||||
|
|
||||||
|
const CLI_PATH = path.resolve(process.cwd(), 'dist', 'cli.js');
|
||||||
|
|
||||||
|
const WHOAMI_HANDLE_REGEX = /^user:\s*@([A-Za-z0-9_]+)/m;
|
||||||
|
const WHOAMI_USER_ID_REGEX = /^user_id:\s*([0-9]+)/m;
|
||||||
|
const TWEET_ID_REGEX = /^\d+$/;
|
||||||
|
const LIVE_NODE_ENV = (process.env.BIRD_LIVE_NODE_ENV ?? 'production').trim() || 'production';
|
||||||
|
|
||||||
|
function runBird(args: string[], options: { timeoutMs?: number } = {}): Promise<RunResult> {
|
||||||
|
if (!LIVE) {
|
||||||
|
throw new Error('runBird() called without BIRD_LIVE=1');
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve) => {
|
||||||
|
const child = spawn(process.execPath, [CLI_PATH, ...args], {
|
||||||
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
|
env: {
|
||||||
|
...process.env,
|
||||||
|
NODE_ENV: LIVE_NODE_ENV,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const stdoutChunks: Buffer[] = [];
|
||||||
|
const stderrChunks: Buffer[] = [];
|
||||||
|
|
||||||
|
child.stdout.on('data', (chunk: Buffer) => stdoutChunks.push(chunk));
|
||||||
|
child.stderr.on('data', (chunk: Buffer) => stderrChunks.push(chunk));
|
||||||
|
|
||||||
|
const killTimer =
|
||||||
|
typeof options.timeoutMs === 'number' && options.timeoutMs > 0
|
||||||
|
? setTimeout(() => {
|
||||||
|
child.kill('SIGKILL');
|
||||||
|
}, options.timeoutMs)
|
||||||
|
: null;
|
||||||
|
|
||||||
|
child.on('close', (code, signal) => {
|
||||||
|
if (killTimer) {
|
||||||
|
clearTimeout(killTimer);
|
||||||
|
}
|
||||||
|
resolve({
|
||||||
|
exitCode: code ?? (signal ? 1 : 0),
|
||||||
|
stdout: Buffer.concat(stdoutChunks).toString('utf8'),
|
||||||
|
stderr: Buffer.concat(stderrChunks).toString('utf8'),
|
||||||
|
signal: signal ?? null,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseJson<T>(stdout: string): T {
|
||||||
|
try {
|
||||||
|
return JSON.parse(stdout) as T;
|
||||||
|
} catch (error) {
|
||||||
|
throw new Error(`Invalid JSON output: ${error instanceof Error ? error.message : String(error)}\n${stdout}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sleep(ms: number): Promise<void> {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
|
|
||||||
|
const d = LIVE ? describe : describe.skip;
|
||||||
|
|
||||||
|
d('live CLI (Twitter/X) all commands', () => {
|
||||||
|
const timeoutArg = (process.env.BIRD_LIVE_TIMEOUT_MS ?? '20000').trim();
|
||||||
|
const baseArgs = ['--plain', '--timeout', timeoutArg, '--quote-depth', '0'];
|
||||||
|
|
||||||
|
let whoamiStdout = '';
|
||||||
|
let handle = '';
|
||||||
|
let userId = '';
|
||||||
|
let tweetId = '';
|
||||||
|
let searchStdout = '';
|
||||||
|
let listId = '';
|
||||||
|
let listTimelineAvailable = false;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
if (!existsSync(CLI_PATH)) {
|
||||||
|
throw new Error(`Missing ${CLI_PATH}. Run: pnpm run build:dist`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!relayBaseUrl) {
|
||||||
|
throw new Error('Missing TWITTER_RELAY_BASE_URL for live tests.');
|
||||||
|
}
|
||||||
|
|
||||||
|
const check = await runBird([...baseArgs, 'check'], { timeoutMs: 45_000 });
|
||||||
|
if (check.exitCode !== 0) {
|
||||||
|
throw new Error(`bird check failed:\n${check.stdout}\n${check.stderr}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const who = await runBird([...baseArgs, 'whoami'], { timeoutMs: 45_000 });
|
||||||
|
if (who.exitCode !== 0) {
|
||||||
|
throw new Error(`whoami failed (exit ${who.exitCode}, signal ${who.signal ?? 'none'}):\n${who.stderr}`);
|
||||||
|
}
|
||||||
|
whoamiStdout = who.stdout;
|
||||||
|
|
||||||
|
const handleMatch = WHOAMI_HANDLE_REGEX.exec(who.stdout);
|
||||||
|
if (!handleMatch?.[1]) {
|
||||||
|
throw new Error(`Could not parse whoami handle:\n${who.stdout}`);
|
||||||
|
}
|
||||||
|
handle = handleMatch[1];
|
||||||
|
|
||||||
|
const userIdMatch = WHOAMI_USER_ID_REGEX.exec(who.stdout);
|
||||||
|
if (!userIdMatch?.[1]) {
|
||||||
|
throw new Error(`Could not parse whoami user_id:\n${who.stdout}`);
|
||||||
|
}
|
||||||
|
userId = userIdMatch[1];
|
||||||
|
|
||||||
|
const forcedTweetId = (process.env.BIRD_LIVE_TWEET_ID ?? '').trim();
|
||||||
|
if (forcedTweetId) {
|
||||||
|
if (!TWEET_ID_REGEX.test(forcedTweetId)) {
|
||||||
|
throw new Error(`Invalid BIRD_LIVE_TWEET_ID (expected digits): "${forcedTweetId}"`);
|
||||||
|
}
|
||||||
|
tweetId = forcedTweetId;
|
||||||
|
} else {
|
||||||
|
const searchQuery = (
|
||||||
|
process.env.BIRD_LIVE_SEARCH_QUERY ?? `from:${handle} -filter:replies -filter:retweets`
|
||||||
|
).trim();
|
||||||
|
const search = await runBird([...baseArgs, 'search', searchQuery, '-n', '25', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
if (search.exitCode !== 0) {
|
||||||
|
throw new Error(
|
||||||
|
`search failed (exit ${search.exitCode}, signal ${search.signal ?? 'none'}):\n${search.stderr}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
searchStdout = search.stdout;
|
||||||
|
const tweets = parseJson<Array<{ id?: string }>>(search.stdout);
|
||||||
|
const first = String(tweets[0]?.id ?? '');
|
||||||
|
if (!TWEET_ID_REGEX.test(first)) {
|
||||||
|
throw new Error(
|
||||||
|
`Search returned no usable tweets. Query: "${searchQuery}". ` +
|
||||||
|
`Override with BIRD_LIVE_SEARCH_QUERY.\n${search.stdout}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
tweetId = first;
|
||||||
|
}
|
||||||
|
|
||||||
|
listId = (process.env.BIRD_LIVE_LIST_ID ?? '').trim();
|
||||||
|
if (!listId) {
|
||||||
|
const lists = await runBird([...baseArgs, 'lists', '-n', '1', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
if (lists.exitCode === 0) {
|
||||||
|
const parsed = parseJson<Array<{ id?: string }>>(lists.stdout);
|
||||||
|
listId = String(parsed[0]?.id ?? '').trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!listId) {
|
||||||
|
const lists = await runBird([...baseArgs, 'lists', '--member-of', '-n', '1', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
if (lists.exitCode === 0) {
|
||||||
|
const parsed = parseJson<Array<{ id?: string }>>(lists.stdout);
|
||||||
|
listId = String(parsed[0]?.id ?? '').trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
listTimelineAvailable = Boolean(listId);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requires env credentials + built dist CLI', async () => {
|
||||||
|
expect(existsSync(CLI_PATH)).toBe(true);
|
||||||
|
expect(whoamiStdout.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('check works', async () => {
|
||||||
|
const check = await runBird([...baseArgs, 'check'], { timeoutMs: 45_000 });
|
||||||
|
expect(check.exitCode).toBe(0);
|
||||||
|
expect(check.stdout.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('whoami works', async () => {
|
||||||
|
expect(whoamiStdout).toContain('user: @');
|
||||||
|
expect(whoamiStdout).toContain('user_id:');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('search returns JSON array', async () => {
|
||||||
|
const search = searchStdout
|
||||||
|
? { exitCode: 0, stdout: searchStdout }
|
||||||
|
: await runBird([...baseArgs, 'search', `from:${handle}`, '-n', '10', '--json'], { timeoutMs: 45_000 });
|
||||||
|
expect(search.exitCode).toBe(0);
|
||||||
|
const tweets = parseJson<Array<{ id?: string }>>(search.stdout);
|
||||||
|
expect(Array.isArray(tweets)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('read returns tweet JSON', async () => {
|
||||||
|
const read = await runBird([...baseArgs, 'read', tweetId, '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(read.exitCode).toBe(0);
|
||||||
|
const readTweet = parseJson<{ id?: string; author?: { username?: string } }>(read.stdout);
|
||||||
|
expect(readTweet.id).toBe(tweetId);
|
||||||
|
expect(readTweet.author?.username?.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tweet-id shorthand returns tweet JSON', async () => {
|
||||||
|
const shorthand = await runBird([...baseArgs, tweetId, '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(shorthand.exitCode).toBe(0);
|
||||||
|
const shorthandTweet = parseJson<{ id?: string }>(shorthand.stdout);
|
||||||
|
expect(shorthandTweet.id).toBe(tweetId);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('replies returns JSON array', async () => {
|
||||||
|
const replies = await runBird([...baseArgs, 'replies', tweetId, '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(replies.exitCode).toBe(0);
|
||||||
|
const replyTweets = parseJson<Array<{ id?: string }>>(replies.stdout);
|
||||||
|
expect(Array.isArray(replyTweets)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('thread returns JSON array', async () => {
|
||||||
|
const thread = await runBird([...baseArgs, 'thread', tweetId, '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(thread.exitCode).toBe(0);
|
||||||
|
const threadTweets = parseJson<Array<{ id?: string }>>(thread.stdout);
|
||||||
|
expect(Array.isArray(threadTweets)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('mentions returns JSON array', async () => {
|
||||||
|
const mentions = await runBird([...baseArgs, 'mentions', '-n', '10', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(mentions.exitCode).toBe(0);
|
||||||
|
const mentionTweets = parseJson<Array<{ id?: string }>>(mentions.stdout);
|
||||||
|
expect(Array.isArray(mentionTweets)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('bookmarks returns JSON array', async () => {
|
||||||
|
const bookmarks = await runBird([...baseArgs, 'bookmarks', '-n', '10', '--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,
|
||||||
|
});
|
||||||
|
expect(likes.exitCode).toBe(0);
|
||||||
|
const likeTweets = parseJson<Array<{ id?: string }>>(likes.stdout);
|
||||||
|
expect(Array.isArray(likeTweets)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('following returns JSON array', async () => {
|
||||||
|
const following = await runBird([...baseArgs, 'following', '--user', userId, '-n', '10', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(following.exitCode).toBe(0);
|
||||||
|
const followingUsers = parseJson<Array<{ id?: string; username?: string }>>(following.stdout);
|
||||||
|
expect(Array.isArray(followingUsers)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('followers returns JSON array', async () => {
|
||||||
|
const followers = await runBird([...baseArgs, 'followers', '--user', userId, '-n', '10', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(followers.exitCode).toBe(0);
|
||||||
|
const followerUsers = parseJson<Array<{ id?: string; username?: string }>>(followers.stdout);
|
||||||
|
expect(Array.isArray(followerUsers)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('user-tweets returns JSON array', async () => {
|
||||||
|
const testHandle = process.env.BIRD_LIVE_USER_TWEETS_HANDLE || 'X';
|
||||||
|
const userTweets = await runBird([...baseArgs, 'user-tweets', testHandle, '-n', '5', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(userTweets.exitCode).toBe(0);
|
||||||
|
const tweets = parseJson<Array<{ id?: string; author?: { username?: string } }>>(userTweets.stdout);
|
||||||
|
expect(Array.isArray(tweets)).toBe(true);
|
||||||
|
expect(tweets.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('user-tweets paged JSON returns { tweets, nextCursor }', async () => {
|
||||||
|
const testHandle =
|
||||||
|
process.env.BIRD_LIVE_USER_TWEETS_PAGED_HANDLE ?? process.env.BIRD_LIVE_USER_TWEETS_HANDLE ?? 'X';
|
||||||
|
const userTweets = await runBird(
|
||||||
|
[...baseArgs, 'user-tweets', testHandle, '-n', '50', '--max-pages', '3', '--delay', '0', '--json'],
|
||||||
|
{
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(userTweets.exitCode).toBe(0);
|
||||||
|
const payload = parseJson<{ tweets?: Array<{ id?: string }>; nextCursor?: string | null }>(userTweets.stdout);
|
||||||
|
expect(Array.isArray(payload.tweets)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('lists returns JSON array', async () => {
|
||||||
|
const lists = await runBird([...baseArgs, 'lists', '-n', '10', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(lists.exitCode).toBe(0);
|
||||||
|
const payload = parseJson<Array<{ id?: string }>>(lists.stdout);
|
||||||
|
expect(Array.isArray(payload)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('list-timeline returns JSON array', async () => {
|
||||||
|
if (!listTimelineAvailable) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const timeline = await runBird([...baseArgs, 'list-timeline', listId, '-n', '5', '--json'], { timeoutMs: 45_000 });
|
||||||
|
expect(timeline.exitCode).toBe(0);
|
||||||
|
const payload = parseJson<Array<{ id?: string }>>(timeline.stdout);
|
||||||
|
expect(Array.isArray(payload)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('home for-you returns JSON array', async () => {
|
||||||
|
const home = await runBird([...baseArgs, 'home', '-n', '5', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(home.exitCode).toBe(0);
|
||||||
|
const payload = parseJson<Array<{ id?: string }>>(home.stdout);
|
||||||
|
expect(Array.isArray(payload)).toBe(true);
|
||||||
|
}, 60_000);
|
||||||
|
|
||||||
|
it('home following returns JSON array', async () => {
|
||||||
|
let home = await runBird([...baseArgs, 'home', '--following', '-n', '5', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
if (home.exitCode !== 0 && home.stderr.includes('OverCapacity')) {
|
||||||
|
await sleep(1500);
|
||||||
|
home = await runBird([...baseArgs, 'home', '--following', '-n', '5', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
expect(home.exitCode).toBe(0);
|
||||||
|
const payload = parseJson<Array<{ id?: string }>>(home.stdout);
|
||||||
|
expect(Array.isArray(payload)).toBe(true);
|
||||||
|
}, 60_000);
|
||||||
|
|
||||||
|
it('news returns JSON array', async () => {
|
||||||
|
const news = await runBird([...baseArgs, 'news', '-n', '5', '--ai-only', '--json'], { timeoutMs: 45_000 });
|
||||||
|
expect(news.exitCode).toBe(0);
|
||||||
|
const payload = parseJson<Array<{ id?: string }>>(news.stdout);
|
||||||
|
expect(Array.isArray(payload)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('trending returns JSON array', async () => {
|
||||||
|
const trending = await runBird([...baseArgs, 'trending', '-n', '5', '--json'], { timeoutMs: 45_000 });
|
||||||
|
expect(trending.exitCode).toBe(0);
|
||||||
|
const payload = parseJson<Array<{ id?: string }>>(trending.stdout);
|
||||||
|
expect(Array.isArray(payload)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('query-ids returns JSON', async () => {
|
||||||
|
const queryIds = await runBird([...baseArgs, 'query-ids', '--json'], {
|
||||||
|
timeoutMs: 60_000,
|
||||||
|
});
|
||||||
|
expect(queryIds.exitCode).toBe(0);
|
||||||
|
const snapshot = parseJson<{ cached?: boolean; ids?: Record<string, string> }>(queryIds.stdout);
|
||||||
|
expect(typeof snapshot.cached).toBe('boolean');
|
||||||
|
});
|
||||||
|
});
|
||||||
+80
-56
@@ -7,8 +7,7 @@ type RunResult = { exitCode: number; stdout: string; stderr: string; signal: Nod
|
|||||||
|
|
||||||
const LIVE = process.env.BIRD_LIVE === '1';
|
const LIVE = process.env.BIRD_LIVE === '1';
|
||||||
|
|
||||||
const authToken = (process.env.AUTH_TOKEN ?? process.env.TWITTER_AUTH_TOKEN ?? '').trim();
|
const relayBaseUrl = (process.env.TWITTER_RELAY_BASE_URL ?? '').trim();
|
||||||
const ct0 = (process.env.CT0 ?? process.env.TWITTER_CT0 ?? '').trim();
|
|
||||||
|
|
||||||
const CLI_PATH = path.resolve(process.cwd(), 'dist', 'cli.js');
|
const CLI_PATH = path.resolve(process.cwd(), 'dist', 'cli.js');
|
||||||
|
|
||||||
@@ -27,8 +26,6 @@ function runBird(args: string[], options: { timeoutMs?: number } = {}): Promise<
|
|||||||
stdio: ['ignore', 'pipe', 'pipe'],
|
stdio: ['ignore', 'pipe', 'pipe'],
|
||||||
env: {
|
env: {
|
||||||
...process.env,
|
...process.env,
|
||||||
AUTH_TOKEN: authToken,
|
|
||||||
CT0: ct0,
|
|
||||||
NODE_ENV: LIVE_NODE_ENV,
|
NODE_ENV: LIVE_NODE_ENV,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -72,7 +69,6 @@ const d = LIVE ? describe : describe.skip;
|
|||||||
|
|
||||||
d('live CLI (Twitter/X)', () => {
|
d('live CLI (Twitter/X)', () => {
|
||||||
const timeoutArg = (process.env.BIRD_LIVE_TIMEOUT_MS ?? '20000').trim();
|
const timeoutArg = (process.env.BIRD_LIVE_TIMEOUT_MS ?? '20000').trim();
|
||||||
const cookieTimeoutArg = (process.env.BIRD_LIVE_COOKIE_TIMEOUT_MS ?? '30000').trim();
|
|
||||||
const baseArgs = ['--plain', '--timeout', timeoutArg, '--quote-depth', '0'];
|
const baseArgs = ['--plain', '--timeout', timeoutArg, '--quote-depth', '0'];
|
||||||
|
|
||||||
let whoamiStdout = '';
|
let whoamiStdout = '';
|
||||||
@@ -85,19 +81,16 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
throw new Error(`Missing ${CLI_PATH}. Run: pnpm run build:dist`);
|
throw new Error(`Missing ${CLI_PATH}. Run: pnpm run build:dist`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!authToken || !ct0) {
|
if (!relayBaseUrl) {
|
||||||
const check = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'check'], { timeoutMs: 45_000 });
|
throw new Error('Missing TWITTER_RELAY_BASE_URL for live tests.');
|
||||||
if (check.exitCode !== 0) {
|
|
||||||
throw new Error(
|
|
||||||
'Missing live credentials.\n' +
|
|
||||||
'- Option A: set AUTH_TOKEN + CT0 (or TWITTER_AUTH_TOKEN/TWITTER_CT0)\n' +
|
|
||||||
'- Option B: login to x.com in Safari/Chrome/Firefox for cookie extraction\n\n' +
|
|
||||||
`bird check output:\n${check.stdout}\n${check.stderr}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const who = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'whoami'], { timeoutMs: 45_000 });
|
const check = await runBird([...baseArgs, 'check'], { timeoutMs: 45_000 });
|
||||||
|
if (check.exitCode !== 0) {
|
||||||
|
throw new Error(`bird check failed:\n${check.stdout}\n${check.stderr}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const who = await runBird([...baseArgs, 'whoami'], { timeoutMs: 45_000 });
|
||||||
if (who.exitCode !== 0) {
|
if (who.exitCode !== 0) {
|
||||||
throw new Error(`whoami failed (exit ${who.exitCode}, signal ${who.signal ?? 'none'}):\n${who.stderr}`);
|
throw new Error(`whoami failed (exit ${who.exitCode}, signal ${who.signal ?? 'none'}):\n${who.stderr}`);
|
||||||
}
|
}
|
||||||
@@ -127,12 +120,9 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
const searchQuery = (
|
const searchQuery = (
|
||||||
process.env.BIRD_LIVE_SEARCH_QUERY ?? `from:${handle} -filter:replies -filter:retweets`
|
process.env.BIRD_LIVE_SEARCH_QUERY ?? `from:${handle} -filter:replies -filter:retweets`
|
||||||
).trim();
|
).trim();
|
||||||
const search = await runBird(
|
const search = await runBird([...baseArgs, 'search', searchQuery, '-n', '25', '--json'], {
|
||||||
[...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'search', searchQuery, '-n', '25', '--json'],
|
timeoutMs: 45_000,
|
||||||
{
|
});
|
||||||
timeoutMs: 45_000,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if (search.exitCode !== 0) {
|
if (search.exitCode !== 0) {
|
||||||
throw new Error(`search failed (exit ${search.exitCode}, signal ${search.signal ?? 'none'}):\n${search.stderr}`);
|
throw new Error(`search failed (exit ${search.exitCode}, signal ${search.signal ?? 'none'}):\n${search.stderr}`);
|
||||||
}
|
}
|
||||||
@@ -160,7 +150,7 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('read returns tweet JSON', async () => {
|
it('read returns tweet JSON', async () => {
|
||||||
const read = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'read', tweetId, '--json'], {
|
const read = await runBird([...baseArgs, 'read', tweetId, '--json'], {
|
||||||
timeoutMs: 45_000,
|
timeoutMs: 45_000,
|
||||||
});
|
});
|
||||||
expect(read.exitCode).toBe(0);
|
expect(read.exitCode).toBe(0);
|
||||||
@@ -170,7 +160,7 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('tweet-id shorthand returns tweet JSON', async () => {
|
it('tweet-id shorthand returns tweet JSON', async () => {
|
||||||
const shorthand = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, tweetId, '--json'], {
|
const shorthand = await runBird([...baseArgs, tweetId, '--json'], {
|
||||||
timeoutMs: 45_000,
|
timeoutMs: 45_000,
|
||||||
});
|
});
|
||||||
expect(shorthand.exitCode).toBe(0);
|
expect(shorthand.exitCode).toBe(0);
|
||||||
@@ -179,7 +169,7 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('replies returns JSON array', async () => {
|
it('replies returns JSON array', async () => {
|
||||||
const replies = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'replies', tweetId, '--json'], {
|
const replies = await runBird([...baseArgs, 'replies', tweetId, '--json'], {
|
||||||
timeoutMs: 45_000,
|
timeoutMs: 45_000,
|
||||||
});
|
});
|
||||||
expect(replies.exitCode).toBe(0);
|
expect(replies.exitCode).toBe(0);
|
||||||
@@ -188,7 +178,7 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('thread returns JSON array', async () => {
|
it('thread returns JSON array', async () => {
|
||||||
const thread = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'thread', tweetId, '--json'], {
|
const thread = await runBird([...baseArgs, 'thread', tweetId, '--json'], {
|
||||||
timeoutMs: 45_000,
|
timeoutMs: 45_000,
|
||||||
});
|
});
|
||||||
expect(thread.exitCode).toBe(0);
|
expect(thread.exitCode).toBe(0);
|
||||||
@@ -198,24 +188,18 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('mentions returns JSON array', async () => {
|
it('mentions returns JSON array', async () => {
|
||||||
const mentions = await runBird(
|
const mentions = await runBird([...baseArgs, 'mentions', '-n', '10', '--json'], {
|
||||||
[...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'mentions', '-n', '10', '--json'],
|
timeoutMs: 45_000,
|
||||||
{
|
});
|
||||||
timeoutMs: 45_000,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
expect(mentions.exitCode).toBe(0);
|
expect(mentions.exitCode).toBe(0);
|
||||||
const mentionTweets = parseJson<Array<{ id?: string }>>(mentions.stdout);
|
const mentionTweets = parseJson<Array<{ id?: string }>>(mentions.stdout);
|
||||||
expect(Array.isArray(mentionTweets)).toBe(true);
|
expect(Array.isArray(mentionTweets)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('bookmarks returns JSON array', async () => {
|
it('bookmarks returns JSON array', async () => {
|
||||||
const bookmarks = await runBird(
|
const bookmarks = await runBird([...baseArgs, 'bookmarks', '-n', '10', '--json'], {
|
||||||
[...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'bookmarks', '-n', '10', '--json'],
|
timeoutMs: 45_000,
|
||||||
{
|
});
|
||||||
timeoutMs: 45_000,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
expect(bookmarks.exitCode).toBe(0);
|
expect(bookmarks.exitCode).toBe(0);
|
||||||
const bookmarkTweets = parseJson<Array<{ id?: string }>>(bookmarks.stdout);
|
const bookmarkTweets = parseJson<Array<{ id?: string }>>(bookmarks.stdout);
|
||||||
expect(Array.isArray(bookmarkTweets)).toBe(true);
|
expect(Array.isArray(bookmarkTweets)).toBe(true);
|
||||||
@@ -226,17 +210,16 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
if (!folderId) {
|
if (!folderId) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const bookmarks = await runBird(
|
const bookmarks = await runBird([...baseArgs, 'bookmarks', '--folder-id', folderId, '-n', '10', '--json'], {
|
||||||
[...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'bookmarks', '--folder-id', folderId, '-n', '10', '--json'],
|
timeoutMs: 45_000,
|
||||||
{ timeoutMs: 45_000 },
|
});
|
||||||
);
|
|
||||||
expect(bookmarks.exitCode).toBe(0);
|
expect(bookmarks.exitCode).toBe(0);
|
||||||
const bookmarkTweets = parseJson<Array<{ id?: string }>>(bookmarks.stdout);
|
const bookmarkTweets = parseJson<Array<{ id?: string }>>(bookmarks.stdout);
|
||||||
expect(Array.isArray(bookmarkTweets)).toBe(true);
|
expect(Array.isArray(bookmarkTweets)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('likes returns JSON array', async () => {
|
it('likes returns JSON array', async () => {
|
||||||
const likes = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'likes', '-n', '10', '--json'], {
|
const likes = await runBird([...baseArgs, 'likes', '-n', '10', '--json'], {
|
||||||
timeoutMs: 45_000,
|
timeoutMs: 45_000,
|
||||||
});
|
});
|
||||||
expect(likes.exitCode).toBe(0);
|
expect(likes.exitCode).toBe(0);
|
||||||
@@ -245,31 +228,55 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('following returns JSON array', async () => {
|
it('following returns JSON array', async () => {
|
||||||
const following = await runBird(
|
const following = await runBird([...baseArgs, 'following', '--user', userId, '-n', '10', '--json'], {
|
||||||
[...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'following', '--user', userId, '-n', '10', '--json'],
|
timeoutMs: 45_000,
|
||||||
{
|
});
|
||||||
timeoutMs: 45_000,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
expect(following.exitCode).toBe(0);
|
expect(following.exitCode).toBe(0);
|
||||||
const followingUsers = parseJson<Array<{ id?: string; username?: string }>>(following.stdout);
|
const followingUsers = parseJson<Array<{ id?: string; username?: string }>>(following.stdout);
|
||||||
expect(Array.isArray(followingUsers)).toBe(true);
|
expect(Array.isArray(followingUsers)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('followers returns JSON array', async () => {
|
it('followers returns JSON array', async () => {
|
||||||
const followers = await runBird(
|
const followers = await runBird([...baseArgs, 'followers', '--user', userId, '-n', '10', '--json'], {
|
||||||
[...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'followers', '--user', userId, '-n', '10', '--json'],
|
timeoutMs: 45_000,
|
||||||
{
|
});
|
||||||
timeoutMs: 45_000,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
expect(followers.exitCode).toBe(0);
|
expect(followers.exitCode).toBe(0);
|
||||||
const followerUsers = parseJson<Array<{ id?: string; username?: string }>>(followers.stdout);
|
const followerUsers = parseJson<Array<{ id?: string; username?: string }>>(followers.stdout);
|
||||||
expect(Array.isArray(followerUsers)).toBe(true);
|
expect(Array.isArray(followerUsers)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('user-tweets returns JSON array', async () => {
|
||||||
|
// Use a known active account for reliable testing (authenticated user may have no tweets)
|
||||||
|
const testHandle = process.env.BIRD_LIVE_USER_TWEETS_HANDLE || 'X';
|
||||||
|
const userTweets = await runBird([...baseArgs, 'user-tweets', testHandle, '-n', '5', '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(userTweets.exitCode).toBe(0);
|
||||||
|
const tweets = parseJson<Array<{ id?: string; author?: { username?: string } }>>(userTweets.stdout);
|
||||||
|
expect(Array.isArray(tweets)).toBe(true);
|
||||||
|
expect(tweets.length).toBeGreaterThan(0);
|
||||||
|
const handleLower = testHandle.toLowerCase();
|
||||||
|
expect(tweets.some((t) => t.author?.username?.toLowerCase() === handleLower)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('user-tweets paged JSON returns { tweets, nextCursor }', async () => {
|
||||||
|
const testHandle =
|
||||||
|
process.env.BIRD_LIVE_USER_TWEETS_PAGED_HANDLE ?? process.env.BIRD_LIVE_USER_TWEETS_HANDLE ?? 'X';
|
||||||
|
const userTweets = await runBird(
|
||||||
|
[...baseArgs, 'user-tweets', testHandle, '-n', '50', '--max-pages', '3', '--delay', '0', '--json'],
|
||||||
|
{
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
expect(userTweets.exitCode).toBe(0);
|
||||||
|
const payload = parseJson<{ tweets?: Array<{ id?: string }>; nextCursor?: string | null }>(userTweets.stdout);
|
||||||
|
expect(Array.isArray(payload.tweets)).toBe(true);
|
||||||
|
expect(payload.tweets?.length).toBeGreaterThan(0);
|
||||||
|
expect(payload.tweets?.[0]?.id?.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
it('query-ids returns JSON', async () => {
|
it('query-ids returns JSON', async () => {
|
||||||
const queryIds = await runBird([...baseArgs, '--cookie-timeout', cookieTimeoutArg, 'query-ids', '--json'], {
|
const queryIds = await runBird([...baseArgs, 'query-ids', '--json'], {
|
||||||
timeoutMs: 60_000,
|
timeoutMs: 60_000,
|
||||||
});
|
});
|
||||||
expect(queryIds.exitCode).toBe(0);
|
expect(queryIds.exitCode).toBe(0);
|
||||||
@@ -287,4 +294,21 @@ d('live CLI (Twitter/X)', () => {
|
|||||||
expect(snapshot.cached).toBe(true);
|
expect(snapshot.cached).toBe(true);
|
||||||
expect(snapshot.ids && Object.keys(snapshot.ids).length).toBeGreaterThan(0);
|
expect(snapshot.ids && Object.keys(snapshot.ids).length).toBeGreaterThan(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('long-form tweet (article) extracts rich content (opt-in)', async () => {
|
||||||
|
const longformTweetId = (process.env.BIRD_LIVE_LONGFORM_TWEET_ID ?? '').trim();
|
||||||
|
if (!longformTweetId) {
|
||||||
|
// Skip unless explicitly provided - long-form tweets may be deleted/unavailable
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const read = await runBird([...baseArgs, 'read', longformTweetId, '--json'], {
|
||||||
|
timeoutMs: 45_000,
|
||||||
|
});
|
||||||
|
expect(read.exitCode).toBe(0);
|
||||||
|
const tweet = parseJson<{ id?: string; text?: string }>(read.stdout);
|
||||||
|
expect(tweet.id).toBe(longformTweetId);
|
||||||
|
// Long-form tweets (articles) typically have substantial content (>500 chars)
|
||||||
|
// This verifies the article content is being extracted, not just a stub
|
||||||
|
expect(tweet.text?.length).toBeGreaterThan(500);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { GraphqlTweetResult } from '../src/lib/twitter-client-types.js';
|
||||||
|
import { mapTweetResult } from '../src/lib/twitter-client-utils.js';
|
||||||
|
|
||||||
|
describe('mapTweetResult article', () => {
|
||||||
|
const makeUserResult = () => ({
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'alice', name: 'Alice' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes extracted article metadata on mapped tweet', () => {
|
||||||
|
const result: GraphqlTweetResult = {
|
||||||
|
rest_id: '1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Check out my article',
|
||||||
|
},
|
||||||
|
article: {
|
||||||
|
article_results: {
|
||||||
|
result: {
|
||||||
|
title: 'Building Context Graphs for GTM',
|
||||||
|
preview_text: 'Foundation Capital recently argued...',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...makeUserResult(),
|
||||||
|
} as GraphqlTweetResult;
|
||||||
|
|
||||||
|
const mapped = mapTweetResult(result, 0);
|
||||||
|
expect(mapped).toBeDefined();
|
||||||
|
expect(mapped?.article).toEqual({
|
||||||
|
title: 'Building Context Graphs for GTM',
|
||||||
|
previewText: 'Foundation Capital recently argued...',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('omits article when none present', () => {
|
||||||
|
const result: GraphqlTweetResult = {
|
||||||
|
rest_id: '2',
|
||||||
|
legacy: { full_text: 'no article' },
|
||||||
|
...makeUserResult(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mapped = mapTweetResult(result, 0);
|
||||||
|
expect(mapped?.article).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes article with only title when no preview_text', () => {
|
||||||
|
const result: GraphqlTweetResult = {
|
||||||
|
rest_id: '3',
|
||||||
|
legacy: { full_text: 'article link' },
|
||||||
|
article: {
|
||||||
|
article_results: {
|
||||||
|
result: {
|
||||||
|
title: 'My Article Title',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
...makeUserResult(),
|
||||||
|
};
|
||||||
|
|
||||||
|
const mapped = mapTweetResult(result, 0);
|
||||||
|
expect(mapped?.article).toEqual({
|
||||||
|
title: 'My Article Title',
|
||||||
|
previewText: undefined,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
+101
-13
@@ -1,22 +1,30 @@
|
|||||||
import { describe, expect, it } from 'vitest';
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { createCliContext } from '../src/cli/shared.js';
|
||||||
import {
|
import {
|
||||||
formatStatsLine,
|
formatStatsLine,
|
||||||
formatTweetUrlLine,
|
formatTweetUrlLine,
|
||||||
|
hyperlink,
|
||||||
labelPrefix,
|
labelPrefix,
|
||||||
resolveOutputConfigFromArgv,
|
resolveOutputConfigFromArgv,
|
||||||
resolveOutputConfigFromCommander,
|
resolveOutputConfigFromCommander,
|
||||||
statusPrefix,
|
statusPrefix,
|
||||||
} from '../src/lib/output.js';
|
} from '../src/lib/output.js';
|
||||||
|
import type { TweetData } from '../src/lib/twitter-client-types.js';
|
||||||
|
|
||||||
describe('output', () => {
|
describe('output', () => {
|
||||||
it('defaults to emoji + color on TTY', () => {
|
it('defaults to emoji + color + hyperlinks on TTY', () => {
|
||||||
const cfg = resolveOutputConfigFromArgv([], {}, true);
|
const cfg = resolveOutputConfigFromArgv([], {}, true);
|
||||||
expect(cfg).toEqual({ plain: false, emoji: true, color: true });
|
expect(cfg).toEqual({ plain: false, emoji: true, color: true, hyperlinks: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('plain disables emoji + color', () => {
|
it('disables hyperlinks on non-TTY', () => {
|
||||||
|
const cfg = resolveOutputConfigFromArgv([], {}, false);
|
||||||
|
expect(cfg.hyperlinks).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('plain disables emoji + color + hyperlinks', () => {
|
||||||
const cfg = resolveOutputConfigFromArgv(['--plain'], {}, true);
|
const cfg = resolveOutputConfigFromArgv(['--plain'], {}, true);
|
||||||
expect(cfg).toEqual({ plain: true, emoji: false, color: false });
|
expect(cfg).toEqual({ plain: true, emoji: false, color: false, hyperlinks: false });
|
||||||
expect(statusPrefix('ok', cfg)).toBe('[ok] ');
|
expect(statusPrefix('ok', cfg)).toBe('[ok] ');
|
||||||
expect(labelPrefix('url', cfg)).toBe('url: ');
|
expect(labelPrefix('url', cfg)).toBe('url: ');
|
||||||
});
|
});
|
||||||
@@ -33,7 +41,7 @@ describe('output', () => {
|
|||||||
|
|
||||||
it('--no-color disables colors', () => {
|
it('--no-color disables colors', () => {
|
||||||
const cfg = resolveOutputConfigFromArgv(['--no-color'], {}, true);
|
const cfg = resolveOutputConfigFromArgv(['--no-color'], {}, true);
|
||||||
expect(cfg).toEqual({ plain: false, emoji: true, color: false });
|
expect(cfg).toEqual({ plain: false, emoji: true, color: false, hyperlinks: true });
|
||||||
});
|
});
|
||||||
|
|
||||||
it('--no-emoji switches to text prefixes', () => {
|
it('--no-emoji switches to text prefixes', () => {
|
||||||
@@ -44,32 +52,112 @@ describe('output', () => {
|
|||||||
|
|
||||||
it('commander opts override defaults', () => {
|
it('commander opts override defaults', () => {
|
||||||
const cfg = resolveOutputConfigFromCommander({ emoji: false, color: false }, {}, true);
|
const cfg = resolveOutputConfigFromCommander({ emoji: false, color: false }, {}, true);
|
||||||
expect(cfg).toEqual({ plain: false, emoji: false, color: false });
|
expect(cfg).toEqual({ plain: false, emoji: false, color: false, hyperlinks: true });
|
||||||
expect(statusPrefix('info', cfg)).toBe('Info: ');
|
expect(statusPrefix('info', cfg)).toBe('Info: ');
|
||||||
expect(labelPrefix('date', cfg)).toBe('Date: ');
|
expect(labelPrefix('date', cfg)).toBe('Date: ');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('commander plain wins over emoji/color', () => {
|
it('commander plain wins over emoji/color', () => {
|
||||||
const cfg = resolveOutputConfigFromCommander({ plain: true, emoji: true, color: true }, {}, true);
|
const cfg = resolveOutputConfigFromCommander({ plain: true, emoji: true, color: true }, {}, true);
|
||||||
expect(cfg).toEqual({ plain: true, emoji: false, color: false });
|
expect(cfg).toEqual({ plain: true, emoji: false, color: false, hyperlinks: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('commander disables hyperlinks on non-TTY', () => {
|
||||||
|
const cfg = resolveOutputConfigFromCommander({}, {}, false);
|
||||||
|
expect(cfg.hyperlinks).toBe(false);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('formats stats line for all modes', () => {
|
it('formats stats line for all modes', () => {
|
||||||
const stats = { likeCount: null, retweetCount: undefined, replyCount: 2 };
|
const stats = { likeCount: null, retweetCount: undefined, replyCount: 2 };
|
||||||
|
|
||||||
expect(formatStatsLine(stats, { plain: true, emoji: false, color: false })).toBe(
|
expect(formatStatsLine(stats, { plain: true, emoji: false, color: false, hyperlinks: false })).toBe(
|
||||||
'likes: 0 retweets: 0 replies: 2',
|
'likes: 0 retweets: 0 replies: 2',
|
||||||
);
|
);
|
||||||
expect(formatStatsLine(stats, { plain: false, emoji: false, color: false })).toBe('Likes 0 Retweets 0 Replies 2');
|
expect(formatStatsLine(stats, { plain: false, emoji: false, color: false, hyperlinks: false })).toBe(
|
||||||
expect(formatStatsLine(stats, { plain: false, emoji: true, color: false })).toBe('❤️ 0 🔁 0 💬 2');
|
'Likes 0 Retweets 0 Replies 2',
|
||||||
|
);
|
||||||
|
expect(formatStatsLine(stats, { plain: false, emoji: true, color: false, hyperlinks: false })).toBe(
|
||||||
|
'❤️ 0 🔁 0 💬 2',
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('always includes tweet URL in all modes', () => {
|
it('always includes tweet URL in all modes', () => {
|
||||||
const id = '1234567890';
|
const id = '1234567890';
|
||||||
const url = `https://x.com/i/status/${id}`;
|
const url = `https://x.com/i/status/${id}`;
|
||||||
|
|
||||||
expect(formatTweetUrlLine(id, { plain: true, emoji: false, color: false })).toContain(url);
|
expect(formatTweetUrlLine(id, { plain: true, emoji: false, color: false, hyperlinks: false })).toContain(url);
|
||||||
expect(formatTweetUrlLine(id, { plain: false, emoji: false, color: false })).toContain(url);
|
expect(formatTweetUrlLine(id, { plain: false, emoji: false, color: false, hyperlinks: false })).toContain(url);
|
||||||
expect(formatTweetUrlLine(id, { plain: false, emoji: true, color: false })).toContain(url);
|
expect(formatTweetUrlLine(id, { plain: false, emoji: true, color: false, hyperlinks: true })).toContain(url);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hyperlink returns plain text when hyperlinks disabled', () => {
|
||||||
|
const cfg = { plain: true, emoji: false, color: false, hyperlinks: false };
|
||||||
|
expect(hyperlink('https://x.com/test', undefined, cfg)).toBe('https://x.com/test');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hyperlink returns plain text on non-TTY (hyperlinks: false)', () => {
|
||||||
|
const cfg = { plain: false, emoji: true, color: false, hyperlinks: false };
|
||||||
|
expect(hyperlink('https://x.com/test', undefined, cfg)).toBe('https://x.com/test');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hyperlink wraps URL with OSC 8 escapes when hyperlinks enabled', () => {
|
||||||
|
const cfg = { plain: false, emoji: true, color: true, hyperlinks: true };
|
||||||
|
const result = hyperlink('https://x.com/test', undefined, cfg);
|
||||||
|
expect(result).toContain('\x1b]8;;');
|
||||||
|
expect(result).toContain('\x07');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hyperlink uses custom display text', () => {
|
||||||
|
const cfg = { plain: false, emoji: true, color: true, hyperlinks: true };
|
||||||
|
const result = hyperlink('https://x.com/test', 'Click here', cfg);
|
||||||
|
expect(result).toContain('Click here');
|
||||||
|
expect(result).toContain('\x1b]8;;https://x.com/test\x07');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hyperlink strips OSC control characters from url and text', () => {
|
||||||
|
const cfg = { plain: false, emoji: true, color: true, hyperlinks: true };
|
||||||
|
const result = hyperlink('https://x.com/\u001btest\u0007', 'Hi\u001b\u0007', cfg);
|
||||||
|
expect(result).not.toContain('\u001btest\u0007');
|
||||||
|
expect(result).not.toContain('Hi\u001b\u0007');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('printTweets respects emoji toggle for media/article/quotes', () => {
|
||||||
|
const tweet: TweetData = {
|
||||||
|
id: '1',
|
||||||
|
text: 'hello world',
|
||||||
|
author: { username: 'alice', name: 'Alice' },
|
||||||
|
media: [{ type: 'photo', url: 'https://img/test.jpg' }],
|
||||||
|
article: { title: 'Article title', previewText: 'Preview' },
|
||||||
|
quotedTweet: {
|
||||||
|
id: '2',
|
||||||
|
text: 'quoted text',
|
||||||
|
author: { username: 'bob', name: 'Bob' },
|
||||||
|
media: [{ type: 'video', url: 'https://vid/test.mp4' }],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const ctxEmoji = createCliContext([], {}, true);
|
||||||
|
const logEmoji = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||||
|
ctxEmoji.printTweets([tweet]);
|
||||||
|
const emojiOutput = logEmoji.mock.calls.flat().join('\n');
|
||||||
|
logEmoji.mockRestore();
|
||||||
|
|
||||||
|
expect(emojiOutput).toContain('📰 Article title');
|
||||||
|
expect(emojiOutput).toContain('🖼️ https://img/test.jpg');
|
||||||
|
expect(emojiOutput).toContain('┌─ QT @bob:');
|
||||||
|
expect(emojiOutput).toContain('🎬 https://vid/test.mp4');
|
||||||
|
|
||||||
|
const ctxPlain = createCliContext(['--plain'], {}, true);
|
||||||
|
const logPlain = vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||||
|
ctxPlain.printTweets([tweet]);
|
||||||
|
const plainOutput = logPlain.mock.calls.flat().join('\n');
|
||||||
|
logPlain.mockRestore();
|
||||||
|
|
||||||
|
expect(plainOutput).toContain('Article: Article title');
|
||||||
|
expect(plainOutput).toContain('PHOTO: https://img/test.jpg');
|
||||||
|
expect(plainOutput).toContain('QT @bob:');
|
||||||
|
expect(plainOutput).toContain('VIDEO: https://vid/test.mp4');
|
||||||
|
expect(plainOutput).not.toContain('📰');
|
||||||
|
expect(plainOutput).not.toContain('🖼️');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,351 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { renderContentState } from '../src/lib/twitter-client-utils.js';
|
||||||
|
|
||||||
|
describe('renderContentState', () => {
|
||||||
|
it('returns undefined for undefined input', () => {
|
||||||
|
expect(renderContentState(undefined)).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns undefined for empty blocks', () => {
|
||||||
|
expect(renderContentState({ blocks: [], entityMap: [] })).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders unstyled blocks as plain paragraphs', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{ key: '1', type: 'unstyled', text: 'First paragraph', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '2', type: 'unstyled', text: 'Second paragraph', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('First paragraph\n\nSecond paragraph');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders header-one as # heading', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [{ key: '1', type: 'header-one', text: 'Main Title', entityRanges: [], inlineStyleRanges: [] }],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('# Main Title');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders header-two as ## heading', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [{ key: '1', type: 'header-two', text: 'Section Title', entityRanges: [], inlineStyleRanges: [] }],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('## Section Title');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders header-three as ### heading', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [{ key: '1', type: 'header-three', text: 'Subsection', entityRanges: [], inlineStyleRanges: [] }],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('### Subsection');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders unordered-list-item as bullet points', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{ key: '1', type: 'unordered-list-item', text: 'Item one', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '2', type: 'unordered-list-item', text: 'Item two', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('- Item one\n\n- Item two');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders ordered-list-item with incrementing numbers', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{ key: '1', type: 'ordered-list-item', text: 'First step', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '2', type: 'ordered-list-item', text: 'Second step', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '3', type: 'ordered-list-item', text: 'Third step', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('1. First step\n\n2. Second step\n\n3. Third step');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resets ordered list counter after non-list block', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{ key: '1', type: 'ordered-list-item', text: 'First', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '2', type: 'ordered-list-item', text: 'Second', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '3', type: 'unstyled', text: 'Paragraph break', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '4', type: 'ordered-list-item', text: 'New first', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('1. First\n\n2. Second\n\nParagraph break\n\n1. New first');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders blockquote with > prefix', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [{ key: '1', type: 'blockquote', text: 'A wise quote', entityRanges: [], inlineStyleRanges: [] }],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('> A wise quote');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders MARKDOWN entity as code block', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
key: '1',
|
||||||
|
type: 'atomic',
|
||||||
|
text: ' ',
|
||||||
|
entityRanges: [{ key: 0, offset: 0, length: 1 }],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
entityMap: [
|
||||||
|
{
|
||||||
|
key: '0',
|
||||||
|
value: {
|
||||||
|
type: 'MARKDOWN',
|
||||||
|
mutability: 'Mutable',
|
||||||
|
data: { markdown: '```bash\necho "hello"\n```' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBe('```bash\necho "hello"\n```');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles entityMap object form', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
key: '1',
|
||||||
|
type: 'atomic',
|
||||||
|
text: ' ',
|
||||||
|
entityRanges: [{ key: 0, offset: 0, length: 1 }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
entityMap: {
|
||||||
|
0: {
|
||||||
|
type: 'MARKDOWN',
|
||||||
|
mutability: 'Mutable',
|
||||||
|
data: { markdown: '```js\nconsole.log("ok")\n```' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(result).toBe('```js\nconsole.log("ok")\n```');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders DIVIDER entity as horizontal rule', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
key: '1',
|
||||||
|
type: 'atomic',
|
||||||
|
text: ' ',
|
||||||
|
entityRanges: [{ key: 0, offset: 0, length: 1 }],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
entityMap: [
|
||||||
|
{
|
||||||
|
key: '0',
|
||||||
|
value: {
|
||||||
|
type: 'DIVIDER',
|
||||||
|
mutability: 'Immutable',
|
||||||
|
data: {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBe('---');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders TWEET entity with URL', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
key: '1',
|
||||||
|
type: 'atomic',
|
||||||
|
text: ' ',
|
||||||
|
entityRanges: [{ key: 0, offset: 0, length: 1 }],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
entityMap: [
|
||||||
|
{
|
||||||
|
key: '0',
|
||||||
|
value: {
|
||||||
|
type: 'TWEET',
|
||||||
|
mutability: 'Immutable',
|
||||||
|
data: { tweetId: '1234567890' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBe('[Embedded Tweet: https://x.com/i/status/1234567890]');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders LINK entity in atomic block', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
key: '1',
|
||||||
|
type: 'atomic',
|
||||||
|
text: ' ',
|
||||||
|
entityRanges: [{ key: 0, offset: 0, length: 1 }],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
entityMap: [
|
||||||
|
{
|
||||||
|
key: '0',
|
||||||
|
value: {
|
||||||
|
type: 'LINK',
|
||||||
|
mutability: 'Mutable',
|
||||||
|
data: { url: 'https://example.com' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBe('[Link: https://example.com]');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders inline LINK entity as markdown link', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
key: '1',
|
||||||
|
type: 'unstyled',
|
||||||
|
text: 'Check out this link for more info',
|
||||||
|
entityRanges: [{ key: 0, offset: 15, length: 4 }],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
entityMap: [
|
||||||
|
{
|
||||||
|
key: '0',
|
||||||
|
value: {
|
||||||
|
type: 'LINK',
|
||||||
|
mutability: 'Mutable',
|
||||||
|
data: { url: 'https://example.com' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBe('Check out this [link](https://example.com) for more info');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders IMAGE entity as placeholder', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
key: '1',
|
||||||
|
type: 'atomic',
|
||||||
|
text: ' ',
|
||||||
|
entityRanges: [{ key: 0, offset: 0, length: 1 }],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
entityMap: [
|
||||||
|
{
|
||||||
|
key: '0',
|
||||||
|
value: {
|
||||||
|
type: 'IMAGE',
|
||||||
|
mutability: 'Immutable',
|
||||||
|
data: {},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(result).toBe('[Image]');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles complex document with mixed content', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{ key: '1', type: 'unstyled', text: 'Introduction paragraph.', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '2', type: 'header-two', text: 'Getting Started', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '3', type: 'ordered-list-item', text: 'Install dependencies', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '4', type: 'ordered-list-item', text: 'Run the script', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{
|
||||||
|
key: '5',
|
||||||
|
type: 'atomic',
|
||||||
|
text: ' ',
|
||||||
|
entityRanges: [{ key: 0, offset: 0, length: 1 }],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
{ key: '6', type: 'unstyled', text: 'Conclusion.', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
],
|
||||||
|
entityMap: [
|
||||||
|
{
|
||||||
|
key: '0',
|
||||||
|
value: {
|
||||||
|
type: 'MARKDOWN',
|
||||||
|
mutability: 'Mutable',
|
||||||
|
data: { markdown: '```bash\nnpm install\n```' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBe(
|
||||||
|
'Introduction paragraph.\n\n' +
|
||||||
|
'## Getting Started\n\n' +
|
||||||
|
'1. Install dependencies\n\n' +
|
||||||
|
'2. Run the script\n\n' +
|
||||||
|
'```bash\nnpm install\n```\n\n' +
|
||||||
|
'Conclusion.',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips empty text blocks', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{ key: '1', type: 'unstyled', text: 'Content', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '2', type: 'unstyled', text: ' ', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '3', type: 'unstyled', text: '', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '4', type: 'unstyled', text: 'More content', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('Content\n\nMore content');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles missing entityRanges on text blocks', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [{ key: '1', type: 'unstyled', text: 'Content' }],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('Content');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles atomic block with missing entity gracefully', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{ key: '1', type: 'unstyled', text: 'Before', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{
|
||||||
|
key: '2',
|
||||||
|
type: 'atomic',
|
||||||
|
text: ' ',
|
||||||
|
entityRanges: [{ key: 99, offset: 0, length: 1 }],
|
||||||
|
inlineStyleRanges: [],
|
||||||
|
},
|
||||||
|
{ key: '3', type: 'unstyled', text: 'After', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('Before\n\nAfter');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles atomic block with no entityRanges gracefully', () => {
|
||||||
|
const result = renderContentState({
|
||||||
|
blocks: [
|
||||||
|
{ key: '1', type: 'unstyled', text: 'Before', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '2', type: 'atomic', text: ' ', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
{ key: '3', type: 'unstyled', text: 'After', entityRanges: [], inlineStyleRanges: [] },
|
||||||
|
],
|
||||||
|
entityMap: [],
|
||||||
|
});
|
||||||
|
expect(result).toBe('Before\n\nAfter');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@ import os from 'node:os';
|
|||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
import { afterEach, describe, expect, it } from 'vitest';
|
import { afterEach, describe, expect, it } from 'vitest';
|
||||||
import { clearFeatureOverridesCache, refreshFeatureOverridesCache } from '../src/lib/runtime-features.js';
|
import { clearFeatureOverridesCache, refreshFeatureOverridesCache } from '../src/lib/runtime-features.js';
|
||||||
import { buildLikesFeatures, buildSearchFeatures } from '../src/lib/twitter-client-features.js';
|
import { buildLikesFeatures, buildListsFeatures, buildSearchFeatures } from '../src/lib/twitter-client-features.js';
|
||||||
|
|
||||||
describe('runtime-features', () => {
|
describe('runtime-features', () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
@@ -29,6 +29,9 @@ describe('runtime-features', () => {
|
|||||||
likes: {
|
likes: {
|
||||||
likes_only: true,
|
likes_only: true,
|
||||||
},
|
},
|
||||||
|
lists: {
|
||||||
|
responsive_web_text_conversations_enabled: true,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -41,6 +44,9 @@ describe('runtime-features', () => {
|
|||||||
const likes = buildLikesFeatures();
|
const likes = buildLikesFeatures();
|
||||||
expect(likes.global_flag).toBe(true);
|
expect(likes.global_flag).toBe(true);
|
||||||
expect(likes.likes_only).toBe(true);
|
expect(likes.likes_only).toBe(true);
|
||||||
|
|
||||||
|
const lists = buildListsFeatures();
|
||||||
|
expect(lists.responsive_web_text_conversations_enabled).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('refresh merges defaults with existing cache', async () => {
|
it('refresh merges defaults with existing cache', async () => {
|
||||||
@@ -110,4 +116,14 @@ describe('runtime-features', () => {
|
|||||||
expect(search.file_flag).toBe(true);
|
expect(search.file_flag).toBe(true);
|
||||||
expect(search.file_search).toBe(true);
|
expect(search.file_search).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
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.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);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,12 +1,7 @@
|
|||||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
|
||||||
const validCookies = {
|
const testRelayBaseUrl = 'https://relay.example';
|
||||||
authToken: 'test_auth_token',
|
|
||||||
ct0: 'test_ct0_token',
|
|
||||||
cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token',
|
|
||||||
source: 'test',
|
|
||||||
};
|
|
||||||
|
|
||||||
type ResponseLike = {
|
type ResponseLike = {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
@@ -53,7 +48,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'boom' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'boom' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('hi');
|
const result = await client.tweet('hi');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -72,7 +67,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('hi');
|
const result = await client.tweet('hi');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -91,7 +86,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('hi');
|
const result = await client.tweet('hi');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -106,7 +101,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('test');
|
const result = await client.search('test');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -121,7 +116,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('test');
|
const result = await client.search('test');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -132,7 +127,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('test');
|
const result = await client.search('test');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -143,7 +138,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('test');
|
const result = await client.search('test');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -160,7 +155,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getBookmarksQueryIds = async () => ['test'];
|
clientPrivate.getBookmarksQueryIds = async () => ['test'];
|
||||||
const result = await client.getBookmarks(1);
|
const result = await client.getBookmarks(1);
|
||||||
@@ -177,7 +172,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getBookmarksQueryIds = async () => ['test'];
|
clientPrivate.getBookmarksQueryIds = async () => ['test'];
|
||||||
const result = await client.getBookmarks(1);
|
const result = await client.getBookmarks(1);
|
||||||
@@ -190,7 +185,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getBookmarksQueryIds = async () => ['test'];
|
clientPrivate.getBookmarksQueryIds = async () => ['test'];
|
||||||
const result = await client.getBookmarks(1);
|
const result = await client.getBookmarks(1);
|
||||||
@@ -200,7 +195,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns unknown error when no query ids are available', async () => {
|
it('returns unknown error when no query ids are available', async () => {
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getBookmarksQueryIds = async () => [];
|
clientPrivate.getBookmarksQueryIds = async () => [];
|
||||||
|
|
||||||
@@ -214,7 +209,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getBookmarks(1);
|
const result = await client.getBookmarks(1);
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -229,7 +224,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getFollowingQueryIds = async () => ['test'];
|
clientPrivate.getFollowingQueryIds = async () => ['test'];
|
||||||
|
|
||||||
@@ -247,7 +242,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
||||||
|
|
||||||
@@ -258,7 +253,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns unknown error when no query ids are available', async () => {
|
it('returns unknown error when no query ids are available', async () => {
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getFollowingQueryIds = async () => [];
|
clientPrivate.getFollowingQueryIds = async () => [];
|
||||||
|
|
||||||
@@ -272,7 +267,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
||||||
|
|
||||||
@@ -294,7 +289,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||||
@@ -313,7 +308,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||||
@@ -328,7 +323,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||||
@@ -340,7 +335,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns unknown error when no query ids are available', async () => {
|
it('returns unknown error when no query ids are available', async () => {
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||||
clientPrivate.getLikesQueryIds = async () => [];
|
clientPrivate.getLikesQueryIds = async () => [];
|
||||||
@@ -355,7 +350,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||||
@@ -375,7 +370,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
||||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||||
@@ -392,7 +387,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
||||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||||
@@ -405,7 +400,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
||||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||||
@@ -415,7 +410,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns unknown error when no query ids are available', async () => {
|
it('returns unknown error when no query ids are available', async () => {
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||||
clientPrivate.getBookmarkFolderQueryIds = async () => [];
|
clientPrivate.getBookmarkFolderQueryIds = async () => [];
|
||||||
|
|
||||||
@@ -429,7 +424,7 @@ describe('TwitterClient API coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
|
|||||||
@@ -2,12 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
|||||||
import { runtimeQueryIds } from '../src/lib/runtime-query-ids.js';
|
import { runtimeQueryIds } from '../src/lib/runtime-query-ids.js';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
|
||||||
const validCookies = {
|
const testRelayBaseUrl = 'https://relay.example';
|
||||||
authToken: 'test_auth_token',
|
|
||||||
ct0: 'test_ct0_token',
|
|
||||||
cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token',
|
|
||||||
source: 'test',
|
|
||||||
};
|
|
||||||
|
|
||||||
type ResponseLike = {
|
type ResponseLike = {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
@@ -20,7 +15,7 @@ type TwitterClientPrivate = TwitterClient & {
|
|||||||
refreshQueryIds: () => Promise<void>;
|
refreshQueryIds: () => Promise<void>;
|
||||||
fetchWithTimeout: (url: string, init: RequestInit) => Promise<ResponseLike>;
|
fetchWithTimeout: (url: string, init: RequestInit) => Promise<ResponseLike>;
|
||||||
ensureClientUserId: () => Promise<void>;
|
ensureClientUserId: () => Promise<void>;
|
||||||
getBaseHeaders: () => Record<string, string>;
|
getHeaders: () => Record<string, string>;
|
||||||
fetchUserArticlePlainText: (userId: string, tweetId: string) => Promise<{ title?: string; plainText?: string }>;
|
fetchUserArticlePlainText: (userId: string, tweetId: string) => Promise<{ title?: string; plainText?: string }>;
|
||||||
fetchTweetDetail: (tweetId: string) => Promise<{ success: true } | { success: false; error: string }>;
|
fetchTweetDetail: (tweetId: string) => Promise<{ success: true } | { success: false; error: string }>;
|
||||||
postStatusUpdate: (input: { text: string }) => Promise<{ success: boolean; error?: string }>;
|
postStatusUpdate: (input: { text: string }) => Promise<{ success: boolean; error?: string }>;
|
||||||
@@ -46,7 +41,7 @@ describe('TwitterClient core coverage', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('refreshQueryIds calls runtime refresh outside test env', async () => {
|
it('refreshQueryIds calls runtime refresh outside test env', async () => {
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const refreshSpy = vi.spyOn(runtimeQueryIds, 'refresh').mockResolvedValue(null);
|
const refreshSpy = vi.spyOn(runtimeQueryIds, 'refresh').mockResolvedValue(null);
|
||||||
process.env.NODE_ENV = 'production';
|
process.env.NODE_ENV = 'production';
|
||||||
|
|
||||||
@@ -63,11 +58,15 @@ describe('TwitterClient core coverage', () => {
|
|||||||
});
|
});
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies, timeoutMs: 5 });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, timeoutMs: 5 });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
await clientPrivate.fetchWithTimeout('https://example.com', { method: 'GET' });
|
await clientPrivate.fetchWithTimeout('https://x.com/i/api/test', { method: 'GET' });
|
||||||
|
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
expect(mockFetch).toHaveBeenCalledWith(
|
||||||
|
'https://relay.example/i/api/test',
|
||||||
|
expect.objectContaining({ method: 'GET' }),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('returns a not found error when tweet data is missing', async () => {
|
it('returns a not found error when tweet data is missing', async () => {
|
||||||
@@ -102,15 +101,15 @@ describe('TwitterClient core coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('123');
|
const result = await client.getTweet('123');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
expect(result.error).toBe('Tweet not found in response');
|
expect(result.error).toBe('Tweet not found in response');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('adds client user id header after ensureClientUserId', async () => {
|
it('does not add Twitter headers after ensureClientUserId', async () => {
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
process.env.NODE_ENV = 'production';
|
process.env.NODE_ENV = 'production';
|
||||||
|
|
||||||
vi.spyOn(client, 'getCurrentUser').mockResolvedValue({
|
vi.spyOn(client, 'getCurrentUser').mockResolvedValue({
|
||||||
@@ -120,9 +119,9 @@ describe('TwitterClient core coverage', () => {
|
|||||||
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
await clientPrivate.ensureClientUserId();
|
await clientPrivate.ensureClientUserId();
|
||||||
const headers = clientPrivate.getBaseHeaders();
|
const headers = clientPrivate.getHeaders();
|
||||||
|
|
||||||
expect(headers['x-twitter-client-user-id']).toBe('42');
|
expect(headers).toEqual({});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('fetchUserArticlePlainText failures', () => {
|
describe('fetchUserArticlePlainText failures', () => {
|
||||||
@@ -130,7 +129,7 @@ describe('TwitterClient core coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockResolvedValueOnce(makeResponse({ ok: false, status: 500 }));
|
const mockFetch = vi.fn().mockResolvedValueOnce(makeResponse({ ok: false, status: 500 }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
||||||
|
|
||||||
@@ -141,7 +140,7 @@ describe('TwitterClient core coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
||||||
|
|
||||||
@@ -160,7 +159,7 @@ describe('TwitterClient core coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
||||||
|
|
||||||
@@ -177,7 +176,7 @@ describe('TwitterClient core coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
const result = await clientPrivate.fetchTweetDetail('1');
|
const result = await clientPrivate.fetchTweetDetail('1');
|
||||||
|
|
||||||
@@ -185,6 +184,89 @@ describe('TwitterClient core coverage', () => {
|
|||||||
expect(result.error).toBe('bad news');
|
expect(result.error).toBe('bad news');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('allows partial errors when tweetResult is present', async () => {
|
||||||
|
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
tweetResult: {
|
||||||
|
result: {
|
||||||
|
rest_id: '1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'hi',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
},
|
||||||
|
core: { user_results: { result: { legacy: { screen_name: 'user', name: 'User' } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
errors: [{ message: 'field error' }],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
const result = await clientPrivate.fetchTweetDetail('1');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.data?.tweetResult).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('allows partial errors when instructions are present', async () => {
|
||||||
|
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
threaded_conversation_with_injections_v2: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '2',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'thread tweet',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '2',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: { result: { legacy: { screen_name: 'user', name: 'User' } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
errors: [{ message: 'is_translatable error' }],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
const result = await clientPrivate.fetchTweetDetail('2');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.data?.threaded_conversation_with_injections_v2?.instructions?.length).toBe(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('parses POST responses when GET returns 404', async () => {
|
it('parses POST responses when GET returns 404', async () => {
|
||||||
const mockFetch = vi
|
const mockFetch = vi
|
||||||
.fn()
|
.fn()
|
||||||
@@ -212,7 +294,7 @@ describe('TwitterClient core coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
const result = await clientPrivate.fetchTweetDetail('1');
|
const result = await clientPrivate.fetchTweetDetail('1');
|
||||||
|
|
||||||
@@ -223,7 +305,7 @@ describe('TwitterClient core coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
const result = await clientPrivate.fetchTweetDetail('1');
|
const result = await clientPrivate.fetchTweetDetail('1');
|
||||||
|
|
||||||
@@ -237,7 +319,7 @@ describe('TwitterClient core coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
const result = await clientPrivate.postStatusUpdate({ text: 'hello' });
|
const result = await clientPrivate.postStatusUpdate({ text: 'hello' });
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,392 @@
|
|||||||
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
|
||||||
|
const testRelayBaseUrl = 'https://relay.example';
|
||||||
|
|
||||||
|
type ResponseLike = {
|
||||||
|
ok: boolean;
|
||||||
|
status: number;
|
||||||
|
json: () => Promise<unknown>;
|
||||||
|
text: () => Promise<string>;
|
||||||
|
};
|
||||||
|
|
||||||
|
const makeResponse = (overrides: Partial<ResponseLike> = {}): ResponseLike => ({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async (): Promise<unknown> => ({}),
|
||||||
|
text: async (): Promise<string> => '',
|
||||||
|
...overrides,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Helper to create GenericTimelineById response structure
|
||||||
|
const makeTimelineResponse = (items: unknown[]) => ({
|
||||||
|
data: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
type: 'TimelineAddEntries',
|
||||||
|
entries: items.map((item, index) => ({
|
||||||
|
entryId: `test-entry-${index}`,
|
||||||
|
content: {
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
item: {
|
||||||
|
itemContent: item,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeTimelineResponseWithInstruction = (type: string, entries: unknown[]) => ({
|
||||||
|
data: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
type,
|
||||||
|
entries,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient news API coverage', () => {
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getNews', () => {
|
||||||
|
it('returns news items from timeline tabs', async () => {
|
||||||
|
// Mock multiple tab requests (forYou, news, sports, entertainment)
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'AI Breakthrough in Machine Learning',
|
||||||
|
social_context: {
|
||||||
|
text: 'AI · 2h ago · 15.5K posts',
|
||||||
|
},
|
||||||
|
trend_url: {
|
||||||
|
url: 'https://x.com/hashtag/AI',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.items).toBeDefined();
|
||||||
|
expect(result.items?.length).toBe(1);
|
||||||
|
expect(result.items?.[0].headline).toBe('AI Breakthrough in Machine Learning');
|
||||||
|
expect(result.items?.[0].category).toBe('AI · AI');
|
||||||
|
expect(result.items?.[0].timeAgo).toBe('2h ago');
|
||||||
|
expect(result.items?.[0].postCount).toBe(15500);
|
||||||
|
expect(result.items?.[0].url).toBe('https://x.com/hashtag/AI');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes raw item content when includeRaw is true', async () => {
|
||||||
|
const itemContent = {
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'AI News',
|
||||||
|
social_context: { text: 'AI · 1h ago · 1.2K posts' },
|
||||||
|
};
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(makeResponse({ json: async () => makeTimelineResponse([itemContent]) }))
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(1, { includeRaw: true });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.items?.[0]._raw).toEqual(itemContent);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters to AI-only items when aiOnly is true', async () => {
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'AI News',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
is_ai_trend: false,
|
||||||
|
name: 'Regular News',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(10, { aiOnly: true });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.items?.length).toBe(1);
|
||||||
|
expect(result.items?.[0].headline).toBe('AI News');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches only selected tabs', async () => {
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'News 1',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(1, { tabs: ['news'] });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error for non-ok responses', async () => {
|
||||||
|
// Mock all 4 default tabs (forYou, news, sports, entertainment) to return HTTP 500
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValue(makeResponse({ ok: false, status: 500, text: async () => 'Server error' }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(10);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('No news items found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error when API returns errors', async () => {
|
||||||
|
// Mock all 4 default tabs to return API errors
|
||||||
|
const mockFetch = vi.fn().mockResolvedValue(
|
||||||
|
makeResponse({
|
||||||
|
json: async () => ({
|
||||||
|
errors: [{ message: 'Rate limited' }, { message: 'Too many requests' }],
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(10);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('No news items found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error when no news items found', async () => {
|
||||||
|
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(10);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('No news items found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deduplicates headlines across tabs', async () => {
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'Duplicate Headline',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'Duplicate Headline',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(10);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.items?.length).toBe(1);
|
||||||
|
expect(result.items?.[0].headline).toBe('Duplicate Headline');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('respects count parameter', async () => {
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'News 1',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'News 2',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'News 3',
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(2);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.items?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('parses entries from non-TimelineAddEntries instructions', async () => {
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponseWithInstruction('TimelineReplaceEntry', [
|
||||||
|
{
|
||||||
|
entryId: 'replace-entry-1',
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'Replacement headline',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.items?.[0].headline).toBe('Replacement headline');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('assigns unique ids for module entries', async () => {
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponseWithInstruction('TimelineAddEntries', [
|
||||||
|
{
|
||||||
|
entryId: 'module-entry',
|
||||||
|
content: {
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
item: { itemContent: { is_ai_trend: true, name: 'Headline A' } },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
item: { itemContent: { is_ai_trend: true, name: 'Headline B' } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(2);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
const ids = result.items?.map((item) => item.id) ?? [];
|
||||||
|
expect(new Set(ids).size).toBe(ids.length);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('uses trend urls as ids when available', async () => {
|
||||||
|
const mockFetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
makeResponse({
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
{
|
||||||
|
is_ai_trend: true,
|
||||||
|
name: 'Headline A',
|
||||||
|
trend_url: { url: 'https://x.com/hashtag/A' },
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.mockResolvedValue(makeResponse({ json: async () => makeTimelineResponse([]) }));
|
||||||
|
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getNews(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.items?.[0].id).toBe('https://x.com/hashtag/A');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -2,12 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
|
|||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { extractArticleText } from '../src/lib/twitter-client-utils.js';
|
import { extractArticleText } from '../src/lib/twitter-client-utils.js';
|
||||||
|
|
||||||
const validCookies = {
|
const testRelayBaseUrl = 'https://relay.example';
|
||||||
authToken: 'test_auth_token',
|
|
||||||
ct0: 'test_ct0_token',
|
|
||||||
cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token',
|
|
||||||
source: 'test',
|
|
||||||
};
|
|
||||||
|
|
||||||
type ResponseLike = {
|
type ResponseLike = {
|
||||||
ok: boolean;
|
ok: boolean;
|
||||||
@@ -40,7 +35,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
describe('uploadMedia error paths', () => {
|
describe('uploadMedia error paths', () => {
|
||||||
it('rejects unsupported media types', async () => {
|
it('rejects unsupported media types', async () => {
|
||||||
global.fetch = vi.fn() as unknown as typeof fetch;
|
global.fetch = vi.fn() as unknown as typeof fetch;
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.uploadMedia({ data: new Uint8Array([1, 2, 3]), mimeType: 'application/pdf' });
|
const result = await client.uploadMedia({ data: new Uint8Array([1, 2, 3]), mimeType: 'application/pdf' });
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -53,7 +48,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -67,7 +62,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -82,7 +77,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -101,7 +96,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
);
|
);
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'video/mp4' });
|
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'video/mp4' });
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -121,7 +116,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 503, text: async () => 'down' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 503, text: async () => 'down' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientUploadPrivate;
|
const clientPrivate = client as unknown as TwitterClientUploadPrivate;
|
||||||
clientPrivate.sleep = vi.fn().mockResolvedValue(undefined);
|
clientPrivate.sleep = vi.fn().mockResolvedValue(undefined);
|
||||||
|
|
||||||
@@ -149,7 +144,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({ processing_info: { state: 'succeeded' } }) }));
|
.mockResolvedValueOnce(makeResponse({ json: async () => ({ processing_info: { state: 'succeeded' } }) }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientUploadPrivate;
|
const clientPrivate = client as unknown as TwitterClientUploadPrivate;
|
||||||
clientPrivate.sleep = vi.fn().mockResolvedValue(undefined);
|
clientPrivate.sleep = vi.fn().mockResolvedValue(undefined);
|
||||||
|
|
||||||
@@ -167,7 +162,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 400, text: async () => 'bad' }));
|
.mockResolvedValueOnce(makeResponse({ ok: false, status: 400, text: async () => 'bad' }));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png', alt: 'alt' });
|
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png', alt: 'alt' });
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -178,7 +173,7 @@ describe('TwitterClient upload coverage', () => {
|
|||||||
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
|
|||||||
@@ -1,11 +1,6 @@
|
|||||||
import type { TwitterClient } from '../src/lib/twitter-client.js';
|
import type { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
|
||||||
export const validCookies = {
|
export const testRelayBaseUrl = 'https://relay.example';
|
||||||
authToken: 'test_auth_token',
|
|
||||||
ct0: 'test_ct0_token',
|
|
||||||
cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token',
|
|
||||||
source: 'test',
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TwitterClientPrivate = TwitterClient & {
|
export type TwitterClientPrivate = TwitterClient & {
|
||||||
getCurrentUser: () => Promise<{
|
getCurrentUser: () => Promise<{
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { validCookies } from './twitter-client-fixtures.js';
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -10,26 +10,22 @@ afterEach(() => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('TwitterClient constructor', () => {
|
describe('TwitterClient constructor', () => {
|
||||||
it('should throw if authToken is missing', () => {
|
it('throws if relay base URL is missing', () => {
|
||||||
expect(
|
const originalRelayBaseUrl = process.env.TWITTER_RELAY_BASE_URL;
|
||||||
() =>
|
delete process.env.TWITTER_RELAY_BASE_URL;
|
||||||
new TwitterClient({
|
try {
|
||||||
cookies: { authToken: null, ct0: 'test', cookieHeader: null, source: null },
|
expect(() => new TwitterClient({})).toThrow('TWITTER_RELAY_BASE_URL is required');
|
||||||
}),
|
} finally {
|
||||||
).toThrow('Both authToken and ct0 cookies are required');
|
if (originalRelayBaseUrl === undefined) {
|
||||||
|
delete process.env.TWITTER_RELAY_BASE_URL;
|
||||||
|
} else {
|
||||||
|
process.env.TWITTER_RELAY_BASE_URL = originalRelayBaseUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should throw if ct0 is missing', () => {
|
it('creates client with relay base URL', () => {
|
||||||
expect(
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
() =>
|
|
||||||
new TwitterClient({
|
|
||||||
cookies: { authToken: 'test', ct0: null, cookieHeader: null, source: null },
|
|
||||||
}),
|
|
||||||
).toThrow('Both authToken and ct0 cookies are required');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('should create client with valid cookies', () => {
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
expect(client).toBeInstanceOf(TwitterClient);
|
expect(client).toBeInstanceOf(TwitterClient);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -61,7 +57,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Hello world!');
|
const result = await client.tweet('Hello world!');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -69,8 +65,10 @@ describe('TwitterClient tweet', () => {
|
|||||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
const [url, options] = mockFetch.mock.calls[0];
|
const [url, options] = mockFetch.mock.calls[0];
|
||||||
expect(url).toContain('CreateTweet');
|
expect(String(url)).toContain(`${testRelayBaseUrl}/i/api/graphql/`);
|
||||||
|
expect(String(url)).toContain('CreateTweet');
|
||||||
expect(options.method).toBe('POST');
|
expect(options.method).toBe('POST');
|
||||||
|
expect(options.headers).toEqual({ 'content-type': 'application/json' });
|
||||||
|
|
||||||
const body = JSON.parse(options.body);
|
const body = JSON.parse(options.body);
|
||||||
expect(body.variables.tweet_text).toBe('Hello world!');
|
expect(body.variables.tweet_text).toBe('Hello world!');
|
||||||
@@ -94,7 +92,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Hello world!', ['111', '222']);
|
const result = await client.tweet('Hello world!', ['111', '222']);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -136,7 +134,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Hello world!');
|
const result = await client.tweet('Hello world!');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -146,7 +144,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
const [firstUrl] = mockFetch.mock.calls[0];
|
const [firstUrl] = mockFetch.mock.calls[0];
|
||||||
const [thirdUrl] = mockFetch.mock.calls[2];
|
const [thirdUrl] = mockFetch.mock.calls[2];
|
||||||
expect(String(firstUrl)).toContain('/CreateTweet');
|
expect(String(firstUrl)).toContain('/CreateTweet');
|
||||||
expect(String(thirdUrl)).toBe('https://x.com/i/api/graphql');
|
expect(String(thirdUrl)).toBe(`${testRelayBaseUrl}/i/api/graphql`);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('should handle API errors', async () => {
|
it('should handle API errors', async () => {
|
||||||
@@ -157,7 +155,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Test');
|
const result = await client.tweet('Test');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -184,7 +182,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Hello world!');
|
const result = await client.tweet('Hello world!');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -212,7 +210,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
text: async () => 'Forbidden',
|
text: async () => 'Forbidden',
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Hello world!');
|
const result = await client.tweet('Hello world!');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -242,7 +240,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Hello world!');
|
const result = await client.tweet('Hello world!');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -268,7 +266,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
json: async () => ({}),
|
json: async () => ({}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Hello world!');
|
const result = await client.tweet('Hello world!');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -283,7 +281,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
text: async () => 'Forbidden',
|
text: async () => 'Forbidden',
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Test');
|
const result = await client.tweet('Test');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -293,7 +291,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
it('should handle network errors', async () => {
|
it('should handle network errors', async () => {
|
||||||
mockFetch.mockRejectedValueOnce(new Error('Network error'));
|
mockFetch.mockRejectedValueOnce(new Error('Network error'));
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Test');
|
const result = await client.tweet('Test');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -316,7 +314,7 @@ describe('TwitterClient tweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.tweet('Hello world!');
|
const result = await client.tweet('Hello world!');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -348,7 +346,7 @@ describe('TwitterClient reply', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.reply('This is a reply', '1234567890');
|
const result = await client.reply('This is a reply', '1234567890');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -382,7 +380,7 @@ describe('TwitterClient reply', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.reply('This is a reply', '1234567890', ['111', '222']);
|
const result = await client.reply('This is a reply', '1234567890', ['111', '222']);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -392,9 +390,10 @@ describe('TwitterClient reply', () => {
|
|||||||
const [, options] = mockFetch.mock.calls[1];
|
const [, options] = mockFetch.mock.calls[1];
|
||||||
expect(String(mockFetch.mock.calls[1][0])).toContain('statuses/update.json');
|
expect(String(mockFetch.mock.calls[1][0])).toContain('statuses/update.json');
|
||||||
expect(options.method).toBe('POST');
|
expect(options.method).toBe('POST');
|
||||||
expect(options.body).toContain('status=This+is+a+reply');
|
const body = String(options.body);
|
||||||
expect(options.body).toContain('in_reply_to_status_id=1234567890');
|
expect(body).toContain('status=This+is+a+reply');
|
||||||
expect(options.body).toContain('auto_populate_reply_metadata=true');
|
expect(body).toContain('in_reply_to_status_id=1234567890');
|
||||||
expect(options.body).toContain('media_ids=111%2C222');
|
expect(body).toContain('auto_populate_reply_metadata=true');
|
||||||
|
expect(body).toContain('media_ids=111%2C222');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { validCookies } from './twitter-client-fixtures.js';
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -78,7 +78,7 @@ describe('TwitterClient conversation helpers', () => {
|
|||||||
json: async () => makeConversationPayload(),
|
json: async () => makeConversationPayload(),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getReplies('1');
|
const result = await client.getReplies('1');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -102,7 +102,7 @@ describe('TwitterClient conversation helpers', () => {
|
|||||||
json: async () => payload,
|
json: async () => payload,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getThread('2');
|
const result = await client.getThread('2');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -147,7 +147,7 @@ describe('TwitterClient conversation helpers', () => {
|
|||||||
json: async () => payload,
|
json: async () => payload,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getThread('1');
|
const result = await client.getThread('1');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -161,7 +161,7 @@ describe('TwitterClient conversation helpers', () => {
|
|||||||
text: async () => 'oops',
|
text: async () => 'oops',
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getThread('1');
|
const result = await client.getThread('1');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { validCookies } from './twitter-client-fixtures.js';
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -28,7 +28,7 @@ describe('TwitterClient getCurrentUser', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getCurrentUser();
|
const result = await client.getCurrentUser();
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -44,7 +44,7 @@ describe('TwitterClient getCurrentUser', () => {
|
|||||||
text: async () => '{"language":"en"}',
|
text: async () => '{"language":"en"}',
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getCurrentUser();
|
const result = await client.getCurrentUser();
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -58,32 +58,26 @@ describe('TwitterClient getCurrentUser', () => {
|
|||||||
text: async () => 'Unauthorized',
|
text: async () => 'Unauthorized',
|
||||||
}));
|
}));
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getCurrentUser();
|
const result = await client.getCurrentUser();
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
expect(result.error).toContain('HTTP 401');
|
expect(result.error).toContain('HTTP 401');
|
||||||
});
|
});
|
||||||
|
|
||||||
it('uses HTML fallback when API endpoints 404', async () => {
|
it('returns error when API endpoints 404', async () => {
|
||||||
mockFetch
|
mockFetch
|
||||||
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
||||||
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
||||||
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
||||||
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' });
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
text: async () => '<html>"screen_name":"fallback","user_id":"999"</html>',
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getCurrentUser();
|
const result = await client.getCurrentUser();
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(false);
|
||||||
expect(result.user?.username).toBe('fallback');
|
expect(result.error).toContain('HTTP 404');
|
||||||
expect(result.user?.id).toBe('999');
|
expect(mockFetch).toHaveBeenCalledTimes(4);
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(5);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('skips an endpoint when JSON parsing fails', async () => {
|
it('skips an endpoint when JSON parsing fails', async () => {
|
||||||
@@ -105,7 +99,7 @@ describe('TwitterClient getCurrentUser', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getCurrentUser();
|
const result = await client.getCurrentUser();
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -113,24 +107,26 @@ describe('TwitterClient getCurrentUser', () => {
|
|||||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('continues on fetch errors and still succeeds via HTML fallback', async () => {
|
it('continues on fetch errors and still succeeds via later API endpoint', async () => {
|
||||||
mockFetch
|
mockFetch
|
||||||
.mockRejectedValueOnce(new Error('boom'))
|
.mockRejectedValueOnce(new Error('boom'))
|
||||||
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
||||||
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
|
||||||
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => 'not found' })
|
|
||||||
.mockRejectedValueOnce(new Error('settings boom'))
|
|
||||||
.mockResolvedValueOnce({
|
.mockResolvedValueOnce({
|
||||||
ok: true,
|
ok: true,
|
||||||
status: 200,
|
status: 200,
|
||||||
text: async () => '<html>"screen_name":"fallback","user_id":"999"</html>',
|
json: async () => ({
|
||||||
|
user_id: '999',
|
||||||
|
screen_name: 'fallback',
|
||||||
|
name: 'Fallback User',
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getCurrentUser();
|
const result = await client.getCurrentUser();
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
expect(result.user?.username).toBe('fallback');
|
expect(result.user?.username).toBe('fallback');
|
||||||
expect(result.user?.id).toBe('999');
|
expect(result.user?.id).toBe('999');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(3);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
import type { TwitterClientPrivate } from './twitter-client-fixtures.js';
|
||||||
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
const makeUserEntry = (id: string, username: string, name: string) => ({
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
__typename: 'User',
|
||||||
|
rest_id: id,
|
||||||
|
legacy: {
|
||||||
|
screen_name: username,
|
||||||
|
name,
|
||||||
|
followers_count: 10,
|
||||||
|
friends_count: 5,
|
||||||
|
profile_image_url_https: 'https://img/test_normal.jpg',
|
||||||
|
},
|
||||||
|
is_blue_verified: false,
|
||||||
|
core: {
|
||||||
|
screen_name: username,
|
||||||
|
name,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient following pagination', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns nextCursor from the response', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
makeUserEntry('1', 'alice', 'Alice'),
|
||||||
|
{ content: { cursorType: 'Bottom', value: 'cursor-2' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getFollowingQueryIds = async () => ['q1'];
|
||||||
|
clientPrivate.getFollowingViaRest = vi.fn();
|
||||||
|
|
||||||
|
const result = await client.getFollowing('user-id', 3);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.users).toHaveLength(1);
|
||||||
|
expect(result.users?.[0].username).toBe('alice');
|
||||||
|
expect(result.nextCursor).toBe('cursor-2');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes cursor parameter to following API and returns nextCursor', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
makeUserEntry('1', 'alice', 'Alice'),
|
||||||
|
{ content: { cursorType: 'Bottom', value: 'cursor-2' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getFollowingQueryIds = async () => ['q1'];
|
||||||
|
clientPrivate.getFollowingViaRest = vi.fn();
|
||||||
|
|
||||||
|
const result = await client.getFollowing('user-id', 20, 'prev-cursor-xyz');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.nextCursor).toBe('cursor-2');
|
||||||
|
|
||||||
|
const [url] = mockFetch.mock.calls[0];
|
||||||
|
const parsedVars = JSON.parse(new URL(url as string).searchParams.get('variables') as string);
|
||||||
|
expect(parsedVars.cursor).toBe('prev-cursor-xyz');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns undefined nextCursor when no cursor in response', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [makeUserEntry('1', 'alice', 'Alice')],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getFollowingQueryIds = async () => ['q1'];
|
||||||
|
clientPrivate.getFollowingViaRest = vi.fn();
|
||||||
|
|
||||||
|
const result = await client.getFollowing('user-id', 20);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an error for non-ok responses', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
text: async () => 'boom',
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getFollowingQueryIds = async () => ['q1'];
|
||||||
|
clientPrivate.getFollowingViaRest = vi.fn().mockResolvedValue({ success: false, error: 'rest fail' });
|
||||||
|
|
||||||
|
const result = await client.getFollowing('user-id', 3);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('500');
|
||||||
|
expect(result.users).toBeUndefined();
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
+68
-67
@@ -1,6 +1,6 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js';
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -84,7 +84,7 @@ describe('TwitterClient following/followers', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClient & { getFollowingQueryIds: () => Promise<string[]> };
|
const clientPrivate = client as unknown as TwitterClient & { getFollowingQueryIds: () => Promise<string[]> };
|
||||||
clientPrivate.getFollowingQueryIds = async () => ['test'];
|
clientPrivate.getFollowingQueryIds = async () => ['test'];
|
||||||
|
|
||||||
@@ -138,7 +138,7 @@ describe('TwitterClient following/followers', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise<string[]> };
|
const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise<string[]> };
|
||||||
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
||||||
|
|
||||||
@@ -183,7 +183,7 @@ describe('TwitterClient following/followers', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClient & {
|
const clientPrivate = client as unknown as TwitterClient & {
|
||||||
getFollowingQueryIds: () => Promise<string[]>;
|
getFollowingQueryIds: () => Promise<string[]>;
|
||||||
refreshQueryIds: () => Promise<void>;
|
refreshQueryIds: () => Promise<void>;
|
||||||
@@ -225,7 +225,7 @@ describe('TwitterClient following/followers', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClient & { getFollowingQueryIds: () => Promise<string[]> };
|
const clientPrivate = client as unknown as TwitterClient & { getFollowingQueryIds: () => Promise<string[]> };
|
||||||
clientPrivate.getFollowingQueryIds = async () => ['test'];
|
clientPrivate.getFollowingQueryIds = async () => ['test'];
|
||||||
|
|
||||||
@@ -265,7 +265,7 @@ describe('TwitterClient following/followers', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise<string[]> };
|
const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise<string[]> };
|
||||||
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
||||||
|
|
||||||
@@ -280,17 +280,8 @@ describe('TwitterClient following/followers', () => {
|
|||||||
expect(urls[1]).toContain('/Followers?');
|
expect(urls[1]).toContain('/Followers?');
|
||||||
expect(urls[2]).toContain('/followers/list.json?');
|
expect(urls[2]).toContain('/followers/list.json?');
|
||||||
});
|
});
|
||||||
});
|
|
||||||
|
|
||||||
describe('TwitterClient likes', () => {
|
it('passes cursor parameter to followers API and returns nextCursor', async () => {
|
||||||
let mockFetch: ReturnType<typeof vi.fn>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockFetch = vi.fn();
|
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
|
||||||
});
|
|
||||||
|
|
||||||
it('fetches likes and parses tweet results', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
mockFetch.mockResolvedValueOnce({
|
||||||
ok: true,
|
ok: true,
|
||||||
status: 200,
|
status: 200,
|
||||||
@@ -306,26 +297,62 @@ describe('TwitterClient likes', () => {
|
|||||||
{
|
{
|
||||||
content: {
|
content: {
|
||||||
itemContent: {
|
itemContent: {
|
||||||
tweet_results: {
|
user_results: {
|
||||||
result: {
|
result: makeUserResult('9', 'beta', 'Beta'),
|
||||||
rest_id: '2',
|
},
|
||||||
legacy: {
|
},
|
||||||
full_text: 'liked',
|
},
|
||||||
created_at: '2024-01-01T00:00:00Z',
|
},
|
||||||
reply_count: 0,
|
{
|
||||||
retweet_count: 0,
|
content: {
|
||||||
favorite_count: 0,
|
cursorType: 'Bottom',
|
||||||
conversation_id_str: '2',
|
value: 'followers-next-cursor',
|
||||||
},
|
},
|
||||||
core: {
|
},
|
||||||
user_results: {
|
],
|
||||||
result: {
|
},
|
||||||
rest_id: 'u2',
|
],
|
||||||
legacy: { screen_name: 'root', name: 'Root' },
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise<string[]> };
|
||||||
|
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getFollowers('456', 50, 'my-cursor');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.users?.[0].username).toBe('beta');
|
||||||
|
expect(result.nextCursor).toBe('followers-next-cursor');
|
||||||
|
|
||||||
|
const [url] = mockFetch.mock.calls[0];
|
||||||
|
const parsedVars = JSON.parse(new URL(url as string).searchParams.get('variables') as string);
|
||||||
|
expect(parsedVars.cursor).toBe('my-cursor');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns undefined nextCursor when no cursor in followers response', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
user_results: {
|
||||||
|
result: makeUserResult('1', 'only', 'Only'),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -341,39 +368,13 @@ describe('TwitterClient likes', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClient & { getFollowersQueryIds: () => Promise<string[]> };
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
clientPrivate.getFollowersQueryIds = async () => ['test'];
|
||||||
success: true,
|
|
||||||
user: { id: '42', username: 'tester', name: 'Tester' },
|
|
||||||
});
|
|
||||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getLikes(2);
|
const result = await client.getFollowers('123', 20);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
expect(result.tweets?.[0].id).toBe('2');
|
expect(result.nextCursor).toBeUndefined();
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
|
||||||
|
|
||||||
const [url, options] = mockFetch.mock.calls[0];
|
|
||||||
expect(options.method).toBe('GET');
|
|
||||||
expect(String(url)).toContain('/Likes?');
|
|
||||||
const parsedVars = JSON.parse(new URL(url as string).searchParams.get('variables') as string);
|
|
||||||
expect(parsedVars.userId).toBe('42');
|
|
||||||
expect(parsedVars.count).toBe(2);
|
|
||||||
const parsedFeatures = JSON.parse(new URL(url as string).searchParams.get('features') as string);
|
|
||||||
expect(parsedFeatures.graphql_timeline_v2_bookmark_timeline).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns an error when current user is unavailable', async () => {
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({ success: false, error: 'no user' });
|
|
||||||
|
|
||||||
const result = await client.getLikes(1);
|
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
|
||||||
expect(result.error).toBe('no user');
|
|
||||||
expect(mockFetch).not.toHaveBeenCalled();
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { mapTweetResult } from '../src/lib/twitter-client-utils.js';
|
import { mapTweetResult } from '../src/lib/twitter-client-utils.js';
|
||||||
import { validCookies } from './twitter-client-fixtures.js';
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -49,7 +49,7 @@ describe('TwitterClient getTweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('12345');
|
const result = await client.getTweet('12345');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -103,7 +103,7 @@ describe('TwitterClient getTweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('6789');
|
const result = await client.getTweet('6789');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -118,7 +118,7 @@ describe('TwitterClient getTweet', () => {
|
|||||||
text: async () => 'Not Found',
|
text: async () => 'Not Found',
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('missing');
|
const result = await client.getTweet('missing');
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
expect(result.success).toBe(false);
|
||||||
@@ -168,7 +168,7 @@ describe('TwitterClient getTweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('article123');
|
const result = await client.getTweet('article123');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -252,7 +252,7 @@ describe('TwitterClient getTweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('article123');
|
const result = await client.getTweet('article123');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -295,7 +295,7 @@ describe('TwitterClient getTweet', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('note123');
|
const result = await client.getTweet('note123');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -326,7 +326,7 @@ describe('TwitterClient getTweet', () => {
|
|||||||
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => '' })
|
.mockResolvedValueOnce({ ok: false, status: 404, text: async () => '' })
|
||||||
.mockResolvedValueOnce({ ok: true, status: 200, json: async () => payload });
|
.mockResolvedValueOnce({ ok: true, status: 200, json: async () => payload });
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('1');
|
const result = await client.getTweet('1');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -366,7 +366,7 @@ describe('TwitterClient quoted tweets', () => {
|
|||||||
const root = makeTweetResult('1', 'root');
|
const root = makeTweetResult('1', 'root');
|
||||||
root.quoted_status_result = { result: quoted };
|
root.quoted_status_result = { result: quoted };
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth);
|
const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth);
|
||||||
|
|
||||||
expect(mapped?.quotedTweet?.id).toBe('2');
|
expect(mapped?.quotedTweet?.id).toBe('2');
|
||||||
@@ -378,7 +378,7 @@ describe('TwitterClient quoted tweets', () => {
|
|||||||
const root = makeTweetResult('1', 'root');
|
const root = makeTweetResult('1', 'root');
|
||||||
root.quoted_status_result = { result: quoted };
|
root.quoted_status_result = { result: quoted };
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies, quoteDepth: 0 });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, quoteDepth: 0 });
|
||||||
const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth);
|
const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth);
|
||||||
|
|
||||||
expect(mapped?.quotedTweet).toBeUndefined();
|
expect(mapped?.quotedTweet).toBeUndefined();
|
||||||
@@ -391,7 +391,7 @@ describe('TwitterClient quoted tweets', () => {
|
|||||||
const root = makeTweetResult('1', 'root');
|
const root = makeTweetResult('1', 'root');
|
||||||
root.quoted_status_result = { result: quoted1 };
|
root.quoted_status_result = { result: quoted1 };
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies, quoteDepth: 2 });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl, quoteDepth: 2 });
|
||||||
const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth);
|
const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth);
|
||||||
|
|
||||||
expect(mapped?.quotedTweet?.id).toBe('2');
|
expect(mapped?.quotedTweet?.id).toBe('2');
|
||||||
@@ -409,7 +409,7 @@ describe('TwitterClient quoted tweets', () => {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth);
|
const mapped = mapTweetResult(root, (client as { quoteDepth: number }).quoteDepth);
|
||||||
|
|
||||||
expect(mapped?.quotedTweet?.id).toBe('2');
|
expect(mapped?.quotedTweet?.id).toBe('2');
|
||||||
|
|||||||
@@ -0,0 +1,344 @@
|
|||||||
|
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();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Realistic fixture based on actual Twitter API response structure
|
||||||
|
const makeHomeTimelineResponse = (tweetId: string, text: string, username: string) => ({
|
||||||
|
data: {
|
||||||
|
home: {
|
||||||
|
home_timeline_urt: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
__typename: 'Tweet',
|
||||||
|
rest_id: tweetId,
|
||||||
|
legacy: {
|
||||||
|
full_text: text,
|
||||||
|
created_at: 'Mon Jan 06 00:00:00 +0000 2025',
|
||||||
|
reply_count: 5,
|
||||||
|
retweet_count: 10,
|
||||||
|
favorite_count: 25,
|
||||||
|
conversation_id_str: tweetId,
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
__typename: 'User',
|
||||||
|
rest_id: 'u123',
|
||||||
|
legacy: {
|
||||||
|
screen_name: username,
|
||||||
|
name: `${username} Name`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient home timeline', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getHomeTimeline', () => {
|
||||||
|
it('should return tweets from For You feed', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: async () => makeHomeTimelineResponse('123456', 'Hello from For You feed!', 'testuser'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getHomeTimeline(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(1);
|
||||||
|
expect(result.tweets?.[0].id).toBe('123456');
|
||||||
|
expect(result.tweets?.[0].text).toBe('Hello from For You feed!');
|
||||||
|
expect(result.tweets?.[0].author.username).toBe('testuser');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return error on non-ok response', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 401,
|
||||||
|
text: async () => 'Unauthorized',
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getHomeTimeline(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('401');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return error when API returns errors', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({
|
||||||
|
errors: [{ message: 'Rate limit exceeded' }],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getHomeTimeline(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('Rate limit exceeded');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getHomeLatestTimeline', () => {
|
||||||
|
it('should return tweets from Following feed', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: async () => makeHomeTimelineResponse('789012', 'Hello from Following feed!', 'chronouser'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getHomeLatestTimeline(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(1);
|
||||||
|
expect(result.tweets?.[0].id).toBe('789012');
|
||||||
|
expect(result.tweets?.[0].text).toBe('Hello from Following feed!');
|
||||||
|
expect(result.tweets?.[0].author.username).toBe('chronouser');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should return error on non-ok response', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 403,
|
||||||
|
text: async () => 'Forbidden',
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getHomeLatestTimeline(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('403');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('pagination', () => {
|
||||||
|
it('should deduplicate tweets across pages', async () => {
|
||||||
|
// First page
|
||||||
|
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',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Second page with duplicate
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
home: {
|
||||||
|
home_timeline_urt: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet1', // duplicate
|
||||||
|
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: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet2',
|
||||||
|
legacy: { full_text: 'Second tweet', created_at: 'Mon Jan 06 00:00:00 +0000 2025' },
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: { rest_id: 'u2', legacy: { screen_name: 'user2', name: 'User 2' } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getHomeTimeline(2);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(2);
|
||||||
|
expect(result.tweets?.[0].id).toBe('tweet1');
|
||||||
|
expect(result.tweets?.[1].id).toBe('tweet2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops when a page only returns duplicates', 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',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
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: 'cursor456',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getHomeTimeline(5);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(1);
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { mapTweetResult, parseTweetsFromInstructions } from '../src/lib/twitter-client-utils.js';
|
import { mapTweetResult, parseTweetsFromInstructions } from '../src/lib/twitter-client-utils.js';
|
||||||
import { validCookies } from './twitter-client-fixtures.js';
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -207,7 +207,7 @@ describe('TwitterClient getTweet with includeRaw option', () => {
|
|||||||
json: async () => mockTweetResponse,
|
json: async () => mockTweetResponse,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('12345');
|
const result = await client.getTweet('12345');
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -220,7 +220,7 @@ describe('TwitterClient getTweet with includeRaw option', () => {
|
|||||||
json: async () => mockTweetResponse,
|
json: async () => mockTweetResponse,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getTweet('12345', { includeRaw: true });
|
const result = await client.getTweet('12345', { includeRaw: true });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -280,7 +280,7 @@ describe('TwitterClient getReplies with includeRaw option', () => {
|
|||||||
json: async () => mockRepliesResponse,
|
json: async () => mockRepliesResponse,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getReplies('12345', { includeRaw: true });
|
const result = await client.getReplies('12345', { includeRaw: true });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -340,7 +340,7 @@ describe('TwitterClient getThread with includeRaw option', () => {
|
|||||||
json: async () => mockThreadResponse,
|
json: async () => mockThreadResponse,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getThread('12345', { includeRaw: true });
|
const result = await client.getThread('12345', { includeRaw: true });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -402,7 +402,7 @@ describe('TwitterClient search with includeRaw option', () => {
|
|||||||
json: async () => mockSearchResponse,
|
json: async () => mockSearchResponse,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('test query', 10, { includeRaw: true });
|
const result = await client.search('test query', 10, { includeRaw: true });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -417,7 +417,7 @@ describe('TwitterClient search with includeRaw option', () => {
|
|||||||
json: async () => mockSearchResponse,
|
json: async () => mockSearchResponse,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('test query', 10);
|
const result = await client.search('test query', 10);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -462,7 +462,7 @@ describe('--json-full flag behavior (without --json)', () => {
|
|||||||
json: async () => mockTweetResponse,
|
json: async () => mockTweetResponse,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
// Only passing includeRaw: true, simulating --json-full without --json
|
// Only passing includeRaw: true, simulating --json-full without --json
|
||||||
const result = await client.getTweet('12345', { includeRaw: true });
|
const result = await client.getTweet('12345', { includeRaw: true });
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js';
|
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -60,7 +60,7 @@ describe('TwitterClient timelines includeRaw', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getBookmarks(1, { includeRaw: true });
|
const result = await client.getBookmarks(1, { includeRaw: true });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -112,7 +112,7 @@ describe('TwitterClient timelines includeRaw', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getBookmarkFolderTimeline('123', 1, { includeRaw: true });
|
const result = await client.getBookmarkFolderTimeline('123', 1, { includeRaw: true });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -168,7 +168,7 @@ describe('TwitterClient timelines includeRaw', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
success: true,
|
success: true,
|
||||||
@@ -229,7 +229,7 @@ describe('TwitterClient timelines includeRaw', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,305 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
describe('TwitterClient likes', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches likes and parses tweet results', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '2',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'liked',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '2',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u2',
|
||||||
|
legacy: { screen_name: 'root', name: 'Root' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '42', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getLikes(2);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.[0].id).toBe('2');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
const [url, options] = mockFetch.mock.calls[0];
|
||||||
|
expect(options.method).toBe('GET');
|
||||||
|
expect(String(url)).toContain('/Likes?');
|
||||||
|
const parsedVars = JSON.parse(new URL(url as string).searchParams.get('variables') as string);
|
||||||
|
expect(parsedVars.userId).toBe('42');
|
||||||
|
expect(parsedVars.count).toBe(2);
|
||||||
|
const parsedFeatures = JSON.parse(new URL(url as string).searchParams.get('features') as string);
|
||||||
|
expect(parsedFeatures.graphql_timeline_v2_bookmark_timeline).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('paginates likes when count exceeds the first page', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'liked page 1',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '1',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'root', name: 'Root' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '2',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'liked page 2',
|
||||||
|
created_at: '2024-01-02T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '2',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u2',
|
||||||
|
legacy: { screen_name: 'root', name: 'Root' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '42', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getLikes(3);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1', '2']);
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
|
||||||
|
const secondVars = JSON.parse(
|
||||||
|
new URL(mockFetch.mock.calls[1][0] as string).searchParams.get('variables') as string,
|
||||||
|
);
|
||||||
|
expect(secondVars.cursor).toBe('cursor-1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('respects maxPages when fetching all likes', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'liked page 1',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '1',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'root', name: 'Root' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '42', username: 'tester', name: 'Tester' },
|
||||||
|
});
|
||||||
|
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getAllLikes({ maxPages: 1 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1']);
|
||||||
|
expect(result.nextCursor).toBe('cursor-1');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns an error when current user is unavailable', async () => {
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({ success: false, error: 'no user' });
|
||||||
|
|
||||||
|
const result = await client.getLikes(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toBe('no user');
|
||||||
|
expect(mockFetch).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// ABOUTME: Tests for TwitterClient list methods.
|
||||||
|
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient lists memberships', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getListMemberships', () => {
|
||||||
|
it('fetches list memberships and parses list results', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '5555',
|
||||||
|
name: 'Member List',
|
||||||
|
member_count: 100,
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '99999',
|
||||||
|
legacy: { screen_name: 'otheruser', name: 'Other User' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListMembershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getListMemberships(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists?.[0].id).toBe('5555');
|
||||||
|
expect(result.lists?.[0].name).toBe('Member List');
|
||||||
|
expect(result.lists?.[0].owner?.username).toBe('otheruser');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries on 404 error after refreshing query IDs', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 404,
|
||||||
|
text: async () => 'Not Found',
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '6666',
|
||||||
|
name: 'Retry Membership List',
|
||||||
|
mode: 'Public',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListMembershipsQueryIds = async () => ['test'];
|
||||||
|
clientPrivate.refreshQueryIds = async () => {};
|
||||||
|
|
||||||
|
const result = await client.getListMemberships(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists?.[0].id).toBe('6666');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,292 @@
|
|||||||
|
// ABOUTME: Tests for TwitterClient list methods.
|
||||||
|
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient lists owned errors', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getOwnedLists error paths', () => {
|
||||||
|
it('returns error on API failure', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
text: async () => 'Internal Server Error',
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('HTTP 500');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error when getCurrentUser fails', async () => {
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: false,
|
||||||
|
error: 'Unauthorized',
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
// When getCurrentUser fails with an error, that error is used; otherwise fallback message is used
|
||||||
|
expect(result.error).toContain('Unauthorized');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles API errors in response', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
errors: [{ message: 'Rate limit exceeded' }],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('Rate limit exceeded');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns missing feature flag errors from the API', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
errors: [{ message: 'missing required feature flag: responsive_web_graphql_exclude_directive_enabled' }],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(1);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('missing required feature flag');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries on 404 error after refreshing query IDs', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 404,
|
||||||
|
text: async () => 'Not Found',
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '333',
|
||||||
|
name: 'Retry List',
|
||||||
|
mode: 'Public',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
clientPrivate.refreshQueryIds = async () => {};
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists?.[0].id).toBe('333');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('skips list entries with missing id_str or name', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '111',
|
||||||
|
name: 'Valid List',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
// Missing id_str
|
||||||
|
name: 'Invalid List 1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '222',
|
||||||
|
// Missing name
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '333',
|
||||||
|
name: 'Another Valid List',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists).toHaveLength(2);
|
||||||
|
expect(result.lists?.[0].id).toBe('111');
|
||||||
|
expect(result.lists?.[1].id).toBe('333');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles list with missing owner gracefully', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '444',
|
||||||
|
name: 'List Without Owner',
|
||||||
|
// No user_results
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists).toHaveLength(1);
|
||||||
|
expect(result.lists?.[0].owner).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,308 @@
|
|||||||
|
// ABOUTME: Tests for TwitterClient list methods.
|
||||||
|
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient lists owned', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getOwnedLists', () => {
|
||||||
|
it('fetches owned lists and parses list results', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '1234567890',
|
||||||
|
name: 'My Test List',
|
||||||
|
description: 'A test list for testing',
|
||||||
|
member_count: 10,
|
||||||
|
subscriber_count: 5,
|
||||||
|
mode: 'Public',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '12345',
|
||||||
|
legacy: { screen_name: 'testuser', name: 'Test User' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists).toHaveLength(1);
|
||||||
|
expect(result.lists?.[0].id).toBe('1234567890');
|
||||||
|
expect(result.lists?.[0].name).toBe('My Test List');
|
||||||
|
expect(result.lists?.[0].description).toBe('A test list for testing');
|
||||||
|
expect(result.lists?.[0].memberCount).toBe(10);
|
||||||
|
expect(result.lists?.[0].subscriberCount).toBe(5);
|
||||||
|
expect(result.lists?.[0].isPrivate).toBe(false);
|
||||||
|
expect(result.lists?.[0].owner?.username).toBe('testuser');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('includes required feature flags in list requests', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
await client.getOwnedLists(1);
|
||||||
|
|
||||||
|
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.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);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles private lists correctly', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '9999',
|
||||||
|
name: 'Secret List',
|
||||||
|
mode: 'Private',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists?.[0].isPrivate).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles lowercase private mode', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '8888',
|
||||||
|
name: 'Lowercase Private',
|
||||||
|
mode: 'private',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists?.[0].isPrivate).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles missing mode', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
list: {
|
||||||
|
id_str: '9999',
|
||||||
|
name: 'No Mode',
|
||||||
|
mode: null,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists?.[0].isPrivate).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty array when no lists exist', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getCurrentUser = async () => ({
|
||||||
|
success: true,
|
||||||
|
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
||||||
|
});
|
||||||
|
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getOwnedLists(100);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.lists).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,463 @@
|
|||||||
|
// ABOUTME: Tests for paginated list timeline fetches.
|
||||||
|
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient lists pagination (continued)', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resumes from cursor', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet-resumed',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Resumed tweet',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'tweet-resumed',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'user1', name: 'User 1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getAllListTimeline('1234567890', { cursor: 'resume-cursor' });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(1);
|
||||||
|
expect(result.tweets?.[0].id).toBe('tweet-resumed');
|
||||||
|
|
||||||
|
// Verify cursor was passed in the request
|
||||||
|
const callUrl = (mockFetch.mock.calls[0] as [string])[0];
|
||||||
|
expect(callUrl).toContain('resume-cursor');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deduplicates tweets across pages', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'duplicate-tweet',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Duplicate',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'duplicate-tweet',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'user1', name: 'User 1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-page-2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'duplicate-tweet',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Duplicate',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'duplicate-tweet',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'user1', name: 'User 1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'unique-tweet',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Unique',
|
||||||
|
created_at: '2024-01-02T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'unique-tweet',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u2',
|
||||||
|
legacy: { screen_name: 'user2', name: 'User 2' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getAllListTimeline('1234567890');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(2);
|
||||||
|
expect(result.tweets?.[0].id).toBe('duplicate-tweet');
|
||||||
|
expect(result.tweets?.[1].id).toBe('unique-tweet');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops when a page only returns duplicates', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'dup',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Duplicate',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'dup',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'user1', name: 'User 1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-page-2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'dup',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Duplicate',
|
||||||
|
created_at: '2024-01-02T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'dup',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'user1', name: 'User 1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-page-3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getAllListTimeline('1234567890');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(1);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops when no cursor is returned', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Page 1',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'tweet1',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'user1', name: 'User 1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-page-2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet2',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Last page',
|
||||||
|
created_at: '2024-01-02T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'tweet2',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u2',
|
||||||
|
legacy: { screen_name: 'user2', name: 'User 2' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getAllListTimeline('1234567890');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(2);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,265 @@
|
|||||||
|
// ABOUTME: Tests for paginated list timeline fetches.
|
||||||
|
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient lists pagination', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getAllListTimeline', () => {
|
||||||
|
it('fetches multiple pages and returns all tweets', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'First tweet',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'tweet1',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'user1', name: 'User 1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-page-2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet2',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Second tweet',
|
||||||
|
created_at: '2024-01-02T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'tweet2',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u2',
|
||||||
|
legacy: { screen_name: 'user2', name: 'User 2' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getAllListTimeline('1234567890');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(2);
|
||||||
|
expect(result.tweets?.[0].id).toBe('tweet1');
|
||||||
|
expect(result.tweets?.[1].id).toBe('tweet2');
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
|
||||||
|
// Verify cursor was passed in second request
|
||||||
|
const secondCallUrl = (mockFetch.mock.calls[1] as [string])[0];
|
||||||
|
expect(secondCallUrl).toContain('cursor-page-2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops at maxPages limit and returns nextCursor', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Page 1',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'tweet1',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'user1', name: 'User 1' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-page-2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'tweet2',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Page 2',
|
||||||
|
created_at: '2024-01-02T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: 'tweet2',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u2',
|
||||||
|
legacy: { screen_name: 'user2', name: 'User 2' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-page-3',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getAllListTimeline('1234567890', { maxPages: 2 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toHaveLength(2);
|
||||||
|
expect(result.nextCursor).toBe('cursor-page-3');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,825 +0,0 @@
|
|||||||
// ABOUTME: Tests for TwitterClient list methods.
|
|
||||||
// ABOUTME: Tests getOwnedLists, getListMemberships, and getListTimeline.
|
|
||||||
|
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
|
||||||
import { type TwitterClientPrivate, validCookies } from './twitter-client-fixtures.js';
|
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
|
||||||
|
|
||||||
afterEach(() => {
|
|
||||||
global.fetch = originalFetch;
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('TwitterClient lists', () => {
|
|
||||||
let mockFetch: ReturnType<typeof vi.fn>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
mockFetch = vi.fn();
|
|
||||||
global.fetch = mockFetch as unknown as typeof fetch;
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getOwnedLists', () => {
|
|
||||||
it('fetches owned lists and parses list results', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '1234567890',
|
|
||||||
name: 'My Test List',
|
|
||||||
description: 'A test list for testing',
|
|
||||||
member_count: 10,
|
|
||||||
subscriber_count: 5,
|
|
||||||
mode: 'Public',
|
|
||||||
created_at: '2024-01-01T00:00:00Z',
|
|
||||||
user_results: {
|
|
||||||
result: {
|
|
||||||
rest_id: '12345',
|
|
||||||
legacy: { screen_name: 'testuser', name: 'Test User' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists).toHaveLength(1);
|
|
||||||
expect(result.lists?.[0].id).toBe('1234567890');
|
|
||||||
expect(result.lists?.[0].name).toBe('My Test List');
|
|
||||||
expect(result.lists?.[0].description).toBe('A test list for testing');
|
|
||||||
expect(result.lists?.[0].memberCount).toBe(10);
|
|
||||||
expect(result.lists?.[0].subscriberCount).toBe(5);
|
|
||||||
expect(result.lists?.[0].isPrivate).toBe(false);
|
|
||||||
expect(result.lists?.[0].owner?.username).toBe('testuser');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles private lists correctly', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '9999',
|
|
||||||
name: 'Secret List',
|
|
||||||
mode: 'Private',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists?.[0].isPrivate).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles lowercase private mode', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '8888',
|
|
||||||
name: 'Lowercase Private',
|
|
||||||
mode: 'private',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists?.[0].isPrivate).toBe(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles missing mode', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '9999',
|
|
||||||
name: 'No Mode',
|
|
||||||
mode: null,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists?.[0].isPrivate).toBe(false);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns empty array when no lists exist', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns error on API failure', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: false,
|
|
||||||
status: 500,
|
|
||||||
text: async () => 'Internal Server Error',
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
|
||||||
expect(result.error).toContain('HTTP 500');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns error when getCurrentUser fails', async () => {
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: false,
|
|
||||||
error: 'Unauthorized',
|
|
||||||
});
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
|
||||||
// When getCurrentUser fails with an error, that error is used; otherwise fallback message is used
|
|
||||||
expect(result.error).toContain('Unauthorized');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles API errors in response', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
errors: [{ message: 'Rate limit exceeded' }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
|
||||||
expect(result.error).toContain('Rate limit exceeded');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('retries on 404 error after refreshing query IDs', async () => {
|
|
||||||
mockFetch
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: false,
|
|
||||||
status: 404,
|
|
||||||
text: async () => 'Not Found',
|
|
||||||
})
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '333',
|
|
||||||
name: 'Retry List',
|
|
||||||
mode: 'Public',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
clientPrivate.refreshQueryIds = async () => {};
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists?.[0].id).toBe('333');
|
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('skips list entries with missing id_str or name', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '111',
|
|
||||||
name: 'Valid List',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
// Missing id_str
|
|
||||||
name: 'Invalid List 1',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '222',
|
|
||||||
// Missing name
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '333',
|
|
||||||
name: 'Another Valid List',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists).toHaveLength(2);
|
|
||||||
expect(result.lists?.[0].id).toBe('111');
|
|
||||||
expect(result.lists?.[1].id).toBe('333');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles list with missing owner gracefully', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '444',
|
|
||||||
name: 'List Without Owner',
|
|
||||||
// No user_results
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListOwnershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getOwnedLists(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists).toHaveLength(1);
|
|
||||||
expect(result.lists?.[0].owner).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getListMemberships', () => {
|
|
||||||
it('fetches list memberships and parses list results', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '5555',
|
|
||||||
name: 'Member List',
|
|
||||||
member_count: 100,
|
|
||||||
user_results: {
|
|
||||||
result: {
|
|
||||||
rest_id: '99999',
|
|
||||||
legacy: { screen_name: 'otheruser', name: 'Other User' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListMembershipsQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getListMemberships(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists?.[0].id).toBe('5555');
|
|
||||||
expect(result.lists?.[0].name).toBe('Member List');
|
|
||||||
expect(result.lists?.[0].owner?.username).toBe('otheruser');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('retries on 404 error after refreshing query IDs', async () => {
|
|
||||||
mockFetch
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: false,
|
|
||||||
status: 404,
|
|
||||||
text: async () => 'Not Found',
|
|
||||||
})
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
user: {
|
|
||||||
result: {
|
|
||||||
timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
list: {
|
|
||||||
id_str: '6666',
|
|
||||||
name: 'Retry Membership List',
|
|
||||||
mode: 'Public',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getCurrentUser = async () => ({
|
|
||||||
success: true,
|
|
||||||
user: { id: '12345', username: 'testuser', name: 'Test User' },
|
|
||||||
});
|
|
||||||
clientPrivate.getListMembershipsQueryIds = async () => ['test'];
|
|
||||||
clientPrivate.refreshQueryIds = async () => {};
|
|
||||||
|
|
||||||
const result = await client.getListMemberships(100);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.lists?.[0].id).toBe('6666');
|
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe('getListTimeline', () => {
|
|
||||||
it('fetches list timeline and parses tweet results', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
list: {
|
|
||||||
tweets_timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
tweet_results: {
|
|
||||||
result: {
|
|
||||||
rest_id: '111',
|
|
||||||
legacy: {
|
|
||||||
full_text: 'Tweet from list',
|
|
||||||
created_at: '2024-01-01T00:00:00Z',
|
|
||||||
reply_count: 0,
|
|
||||||
retweet_count: 0,
|
|
||||||
favorite_count: 0,
|
|
||||||
conversation_id_str: '111',
|
|
||||||
},
|
|
||||||
core: {
|
|
||||||
user_results: {
|
|
||||||
result: {
|
|
||||||
rest_id: 'u1',
|
|
||||||
legacy: { screen_name: 'listmember', name: 'List Member' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getListTimeline('1234567890', 20);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.tweets?.[0].id).toBe('111');
|
|
||||||
expect(result.tweets?.[0].text).toBe('Tweet from list');
|
|
||||||
expect(result.tweets?.[0].author.username).toBe('listmember');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns empty array when list has no tweets', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
list: {
|
|
||||||
tweets_timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getListTimeline('1234567890', 20);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.tweets).toEqual([]);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('returns error on API failure', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: false,
|
|
||||||
status: 403,
|
|
||||||
text: async () => 'Forbidden',
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getListTimeline('1234567890', 20);
|
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
|
||||||
expect(result.error).toContain('HTTP 403');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('handles API errors in response', async () => {
|
|
||||||
mockFetch.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
errors: [{ message: 'List not found' }],
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
|
||||||
|
|
||||||
const result = await client.getListTimeline('nonexistent', 20);
|
|
||||||
|
|
||||||
expect(result.success).toBe(false);
|
|
||||||
expect(result.error).toContain('List not found');
|
|
||||||
});
|
|
||||||
|
|
||||||
it('retries on 404 error after refreshing query IDs', async () => {
|
|
||||||
mockFetch
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: false,
|
|
||||||
status: 404,
|
|
||||||
text: async () => 'Not Found',
|
|
||||||
})
|
|
||||||
.mockResolvedValueOnce({
|
|
||||||
ok: true,
|
|
||||||
status: 200,
|
|
||||||
json: async () => ({
|
|
||||||
data: {
|
|
||||||
list: {
|
|
||||||
tweets_timeline: {
|
|
||||||
timeline: {
|
|
||||||
instructions: [
|
|
||||||
{
|
|
||||||
entries: [
|
|
||||||
{
|
|
||||||
content: {
|
|
||||||
itemContent: {
|
|
||||||
tweet_results: {
|
|
||||||
result: {
|
|
||||||
rest_id: '222',
|
|
||||||
legacy: {
|
|
||||||
full_text: 'Retry success',
|
|
||||||
created_at: '2024-01-01T00:00:00Z',
|
|
||||||
reply_count: 0,
|
|
||||||
retweet_count: 0,
|
|
||||||
favorite_count: 0,
|
|
||||||
conversation_id_str: '222',
|
|
||||||
},
|
|
||||||
core: {
|
|
||||||
user_results: {
|
|
||||||
result: {
|
|
||||||
rest_id: 'u2',
|
|
||||||
legacy: { screen_name: 'user2', name: 'User Two' },
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
|
||||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
|
||||||
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
|
||||||
clientPrivate.refreshQueryIds = async () => {};
|
|
||||||
|
|
||||||
const result = await client.getListTimeline('1234567890', 20);
|
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
|
||||||
expect(result.tweets?.[0].id).toBe('222');
|
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -0,0 +1,214 @@
|
|||||||
|
// ABOUTME: Tests for TwitterClient list methods.
|
||||||
|
|
||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
|
import { type TwitterClientPrivate, testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
global.fetch = originalFetch;
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient lists timeline', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getListTimeline', () => {
|
||||||
|
it('fetches list timeline and parses tweet results', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '111',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Tweet from list',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '111',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'listmember', name: 'List Member' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getListTimeline('1234567890', 20);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.[0].id).toBe('111');
|
||||||
|
expect(result.tweets?.[0].text).toBe('Tweet from list');
|
||||||
|
expect(result.tweets?.[0].author.username).toBe('listmember');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty array when list has no tweets', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getListTimeline('1234567890', 20);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error on API failure', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 403,
|
||||||
|
text: async () => 'Forbidden',
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getListTimeline('1234567890', 20);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('HTTP 403');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles API errors in response', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
errors: [{ message: 'List not found' }],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
const result = await client.getListTimeline('nonexistent', 20);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('List not found');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries on 404 error after refreshing query IDs', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 404,
|
||||||
|
text: async () => 'Not Found',
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
list: {
|
||||||
|
tweets_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '222',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'Retry success',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '222',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u2',
|
||||||
|
legacy: { screen_name: 'user2', name: 'User Two' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||||
|
clientPrivate.getListTimelineQueryIds = async () => ['test'];
|
||||||
|
clientPrivate.refreshQueryIds = async () => {};
|
||||||
|
|
||||||
|
const result = await client.getListTimeline('1234567890', 20);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.[0].id).toBe('222');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { validCookies } from './twitter-client-fixtures.js';
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -34,7 +34,7 @@ describe('TwitterClient uploadMedia', () => {
|
|||||||
ok: true,
|
ok: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const data = new Uint8Array([1, 2, 3, 4]);
|
const data = new Uint8Array([1, 2, 3, 4]);
|
||||||
const result = await client.uploadMedia({ data, mimeType: 'image/png', alt: 'alt text' });
|
const result = await client.uploadMedia({ data, mimeType: 'image/png', alt: 'alt text' });
|
||||||
|
|
||||||
@@ -43,7 +43,7 @@ describe('TwitterClient uploadMedia', () => {
|
|||||||
expect(mockFetch).toHaveBeenCalledTimes(4);
|
expect(mockFetch).toHaveBeenCalledTimes(4);
|
||||||
|
|
||||||
const [initUrl, initOptions] = mockFetch.mock.calls[0];
|
const [initUrl, initOptions] = mockFetch.mock.calls[0];
|
||||||
expect(String(initUrl)).toContain('upload.twitter.com');
|
expect(String(initUrl)).toBe(`${testRelayBaseUrl}/i/media/upload.json`);
|
||||||
expect(initOptions.method).toBe('POST');
|
expect(initOptions.method).toBe('POST');
|
||||||
expect(initOptions.body).toBeInstanceOf(URLSearchParams);
|
expect(initOptions.body).toBeInstanceOf(URLSearchParams);
|
||||||
expect((initOptions.body as URLSearchParams).get('command')).toBe('INIT');
|
expect((initOptions.body as URLSearchParams).get('command')).toBe('INIT');
|
||||||
@@ -87,7 +87,7 @@ describe('TwitterClient uploadMedia', () => {
|
|||||||
json: async () => ({ processing_info: { state: 'succeeded' } }),
|
json: async () => ({ processing_info: { state: 'succeeded' } }),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const data = new Uint8Array([1, 2, 3, 4, 5]);
|
const data = new Uint8Array([1, 2, 3, 4, 5]);
|
||||||
const result = await client.uploadMedia({ data, mimeType: 'video/mp4', alt: 'ignored' });
|
const result = await client.uploadMedia({ data, mimeType: 'video/mp4', alt: 'ignored' });
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,424 @@
|
|||||||
|
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 pagination for thread and replies', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeConversationPayload = (tweetIds: string[], cursor?: string, inReplyTo?: string, conversationId = '1') => ({
|
||||||
|
data: {
|
||||||
|
threaded_conversation_with_injections_v2: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
type: 'TimelineAddEntries',
|
||||||
|
entries: [
|
||||||
|
...tweetIds.map((id, i) => ({
|
||||||
|
entryId: `tweet-${id}`,
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: id,
|
||||||
|
legacy: {
|
||||||
|
full_text: `tweet ${id}`,
|
||||||
|
created_at: `2024-01-0${i + 1}T00:00:00Z`,
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: conversationId,
|
||||||
|
...(inReplyTo ? { in_reply_to_status_id_str: inReplyTo } : {}),
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: { result: { legacy: { screen_name: `user${id}`, name: `User ${id}` } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
// Add cursor entry if provided
|
||||||
|
...(cursor
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
entryId: `cursor-bottom-${Date.now()}`,
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: cursor,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getRepliesPaged', () => {
|
||||||
|
it('returns replies from single page when no cursor in response', async () => {
|
||||||
|
mockFetch.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['2', '3'], undefined, '1'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getRepliesPaged('1');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(2);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches multiple pages when cursor is present and --all is used', async () => {
|
||||||
|
// First page returns cursor, second page does not
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['2', '3'], 'cursor-page-2', '1'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['4', '5'], undefined, '1'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getRepliesPaged('1', { pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(4);
|
||||||
|
expect(result.tweets?.map((t) => t.id)).toEqual(['2', '3', '4', '5']);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('respects maxPages option', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['2', '3'], 'cursor-page-2', '1'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['4', '5'], 'cursor-page-3', '1'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getRepliesPaged('1', { maxPages: 2, pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(4);
|
||||||
|
expect(result.nextCursor).toBe('cursor-page-3');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resumes from provided cursor', async () => {
|
||||||
|
mockFetch.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['4', '5'], undefined, '1'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getRepliesPaged('1', { cursor: 'resume-cursor', pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(2);
|
||||||
|
// Verify cursor was passed in the request
|
||||||
|
const url = mockFetch.mock.calls[0][0] as string;
|
||||||
|
expect(url).toContain('resume-cursor');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deduplicates tweets across pages', async () => {
|
||||||
|
// Second page returns a duplicate tweet
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['2', '3'], 'cursor-page-2', '1'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['3', '4'], undefined, '1'), // '3' is duplicate
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getRepliesPaged('1', { pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(3); // 2, 3, 4 (no duplicate)
|
||||||
|
expect(result.tweets?.map((t) => t.id)).toEqual(['2', '3', '4']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns partial results on error after first page', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['2', '3'], 'cursor-page-2', '1'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
text: async () => 'Internal Server Error',
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getRepliesPaged('1', { pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.tweets?.length).toBe(2);
|
||||||
|
expect(result.error).toContain('500');
|
||||||
|
expect(result.nextCursor).toBe('cursor-page-2');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('continues pagination even when a page contains no replies', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['2'], 'cursor-page-2', '1'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['10'], 'cursor-page-3', undefined),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['3'], undefined, '1'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getRepliesPaged('1', { pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.map((t) => t.id)).toEqual(['2', '3']);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('getThreadPaged', () => {
|
||||||
|
it('returns thread tweets from single page', async () => {
|
||||||
|
mockFetch.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['1', '2', '3'], undefined, undefined, '1'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getThreadPaged('1');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(3);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches multiple pages for thread', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['1', '2'], 'cursor-page-2', undefined, '1'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['3', '4'], undefined, undefined, '1'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getThreadPaged('1', { pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(4);
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('sorts thread tweets by creation time', async () => {
|
||||||
|
// Return tweets in non-chronological order
|
||||||
|
const payload = {
|
||||||
|
data: {
|
||||||
|
threaded_conversation_with_injections_v2: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
type: 'TimelineAddEntries',
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
entryId: 'tweet-3',
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '3',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'tweet 3',
|
||||||
|
created_at: '2024-01-03T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '1',
|
||||||
|
},
|
||||||
|
core: { user_results: { result: { legacy: { screen_name: 'user3', name: 'User 3' } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
entryId: 'tweet-1',
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'tweet 1',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '1',
|
||||||
|
},
|
||||||
|
core: { user_results: { result: { legacy: { screen_name: 'user1', name: 'User 1' } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
mockFetch.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getThreadPaged('1');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.map((t) => t.id)).toEqual(['1', '3']); // Sorted by date
|
||||||
|
});
|
||||||
|
|
||||||
|
it('filters by conversation ID', async () => {
|
||||||
|
// Include a tweet from a different conversation
|
||||||
|
const payload = {
|
||||||
|
data: {
|
||||||
|
threaded_conversation_with_injections_v2: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
type: 'TimelineAddEntries',
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
entryId: 'tweet-1',
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'tweet 1',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '1',
|
||||||
|
},
|
||||||
|
core: { user_results: { result: { legacy: { screen_name: 'user1', name: 'User 1' } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
entryId: 'tweet-99',
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '99',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'different conversation',
|
||||||
|
created_at: '2024-01-02T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '99', // Different conversation
|
||||||
|
},
|
||||||
|
core: { user_results: { result: { legacy: { screen_name: 'user99', name: 'User 99' } } } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
mockFetch.mockResolvedValue({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getThreadPaged('1');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(1);
|
||||||
|
expect(result.tweets?.[0].id).toBe('1');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('respects maxPages for thread', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['1', '2'], 'cursor-page-2', undefined, '1'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeConversationPayload(['3', '4'], 'cursor-page-3', undefined, '1'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getThreadPaged('1', { maxPages: 2, pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(4);
|
||||||
|
expect(result.nextCursor).toBe('cursor-page-3');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||||
import { validCookies } from './twitter-client-fixtures.js';
|
import { testRelayBaseUrl } from './twitter-client-fixtures.js';
|
||||||
|
|
||||||
const originalFetch = global.fetch;
|
const originalFetch = global.fetch;
|
||||||
|
|
||||||
@@ -69,7 +69,7 @@ describe('TwitterClient search', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('needle', 1);
|
const result = await client.search('needle', 1);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -109,7 +109,7 @@ describe('TwitterClient search', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('hello', 5);
|
const result = await client.search('hello', 5);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -117,7 +117,7 @@ describe('TwitterClient search', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('returns an unknown error when no query IDs are available', async () => {
|
it('returns an unknown error when no query IDs are available', async () => {
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
(client as unknown as { getSearchTimelineQueryIds: () => Promise<string[]> }).getSearchTimelineQueryIds =
|
(client as unknown as { getSearchTimelineQueryIds: () => Promise<string[]> }).getSearchTimelineQueryIds =
|
||||||
async () => [];
|
async () => [];
|
||||||
|
|
||||||
@@ -185,7 +185,7 @@ describe('TwitterClient search', () => {
|
|||||||
json: async () => makeResponse(['2', '3']),
|
json: async () => makeResponse(['2', '3']),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('needle', 3);
|
const result = await client.search('needle', 3);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -260,7 +260,7 @@ describe('TwitterClient search', () => {
|
|||||||
json: async () => makeResponse(['3'], 'same-cursor'),
|
json: async () => makeResponse(['3'], 'same-cursor'),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('needle', 4);
|
const result = await client.search('needle', 4);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -334,13 +334,148 @@ describe('TwitterClient search', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.search('needle', 3);
|
const result = await client.search('needle', 3);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1']);
|
expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1']);
|
||||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('respects maxPages when fetching all search results', async () => {
|
||||||
|
const makeSearchEntry = (id: string, text: string) => ({
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: id,
|
||||||
|
legacy: {
|
||||||
|
full_text: text,
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: id,
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: { legacy: { screen_name: 'root', name: 'Root' } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
search_by_raw_query: {
|
||||||
|
search_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
makeSearchEntry('1', 'page 1'),
|
||||||
|
{ content: { cursorType: 'Bottom', value: 'cursor-1' } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
search_by_raw_query: {
|
||||||
|
search_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [makeSearchEntry('2', 'page 2')],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getAllSearchResults('query', { maxPages: 1 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1']);
|
||||||
|
expect(result.nextCursor).toBe('cursor-1');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not return a stale cursor when search pagination ends', async () => {
|
||||||
|
const makeSearchEntry = (id: string) => ({
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: id,
|
||||||
|
legacy: {
|
||||||
|
full_text: `tweet-${id}`,
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: id,
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: { legacy: { screen_name: 'root', name: 'Root' } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
search_by_raw_query: {
|
||||||
|
search_timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [makeSearchEntry('1')],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getAllSearchResults('query', { cursor: 'old-cursor' });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||||
|
|
||||||
|
const vars = JSON.parse(new URL(mockFetch.mock.calls[0][0] as string).searchParams.get('variables') as string);
|
||||||
|
expect(vars.cursor).toBe('old-cursor');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('TwitterClient bookmarks', () => {
|
describe('TwitterClient bookmarks', () => {
|
||||||
@@ -398,7 +533,7 @@ describe('TwitterClient bookmarks', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getBookmarks(2);
|
const result = await client.getBookmarks(2);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -513,7 +648,7 @@ describe('TwitterClient bookmarks', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getAllBookmarks();
|
const result = await client.getAllBookmarks();
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -625,7 +760,7 @@ describe('TwitterClient bookmarks', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getAllBookmarks({ maxPages: 1 });
|
const result = await client.getAllBookmarks({ maxPages: 1 });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -681,7 +816,7 @@ describe('TwitterClient bookmarks', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getAllBookmarks({ cursor: 'cursor-1' });
|
const result = await client.getAllBookmarks({ cursor: 'cursor-1' });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -691,6 +826,120 @@ describe('TwitterClient bookmarks', () => {
|
|||||||
expect(vars.cursor).toBe('cursor-1');
|
expect(vars.cursor).toBe('cursor-1');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('stops paginating when a page only returns duplicates', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
bookmark_timeline_v2: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'saved page 1',
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '1',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'root', name: 'Root' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-1',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
bookmark_timeline_v2: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
entries: [
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '1',
|
||||||
|
legacy: {
|
||||||
|
full_text: 'saved page 2 duplicate',
|
||||||
|
created_at: '2024-01-02T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: '1',
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: 'u1',
|
||||||
|
legacy: { screen_name: 'root', name: 'Root' },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
content: {
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: 'cursor-2',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getAllBookmarks();
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.map((tweet) => tweet.id)).toEqual(['1']);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
it('treats graphql errors as non-fatal when instructions are present', async () => {
|
it('treats graphql errors as non-fatal when instructions are present', async () => {
|
||||||
mockFetch.mockResolvedValueOnce({
|
mockFetch.mockResolvedValueOnce({
|
||||||
ok: true,
|
ok: true,
|
||||||
@@ -739,7 +988,7 @@ describe('TwitterClient bookmarks', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getAllBookmarks({ maxPages: 1 });
|
const result = await client.getAllBookmarks({ maxPages: 1 });
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -802,7 +1051,7 @@ describe('TwitterClient bookmark folders', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const result = await client.getBookmarkFolderTimeline('123', 2);
|
const result = await client.getBookmarkFolderTimeline('123', 2);
|
||||||
|
|
||||||
expect(result.success).toBe(true);
|
expect(result.success).toBe(true);
|
||||||
@@ -874,7 +1123,7 @@ describe('TwitterClient bookmark folders', () => {
|
|||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const client = new TwitterClient({ cookies: validCookies });
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
const clientPrivate = client as TwitterClient & { getBookmarkFolderQueryIds: () => Promise<string[]> };
|
const clientPrivate = client as TwitterClient & { getBookmarkFolderQueryIds: () => Promise<string[]> };
|
||||||
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,166 @@
|
|||||||
|
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 getUserIdByUsername', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves username to userId via GraphQL', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
__typename: 'User',
|
||||||
|
rest_id: '12345',
|
||||||
|
legacy: {
|
||||||
|
screen_name: 'testuser',
|
||||||
|
name: 'Test User',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserIdByUsername('@testuser');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.userId).toBe('12345');
|
||||||
|
expect(result.username).toBe('testuser');
|
||||||
|
expect(result.name).toBe('Test User');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles username without @ prefix', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
__typename: 'User',
|
||||||
|
rest_id: '67890',
|
||||||
|
legacy: {
|
||||||
|
screen_name: 'anotheruser',
|
||||||
|
name: 'Another User',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserIdByUsername('anotheruser');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.userId).toBe('67890');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error for invalid username format', async () => {
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
|
||||||
|
const result = await client.getUserIdByUsername('invalid handle with spaces');
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('Invalid username');
|
||||||
|
expect(mockFetch).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error for empty username', async () => {
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
|
||||||
|
const result = await client.getUserIdByUsername('');
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('Invalid username');
|
||||||
|
expect(mockFetch).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error for username exceeding 15 characters', async () => {
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
|
||||||
|
const result = await client.getUserIdByUsername('thisusernameiswaytoolong');
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('Invalid username');
|
||||||
|
expect(mockFetch).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error when user is unavailable', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
__typename: 'UserUnavailable',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserIdByUsername('suspended');
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('not found or unavailable');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('retries with fallback query IDs on 404', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 404,
|
||||||
|
text: async () => 'Not found',
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 404,
|
||||||
|
text: async () => 'Not found',
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
__typename: 'User',
|
||||||
|
rest_id: '99999',
|
||||||
|
legacy: {
|
||||||
|
screen_name: 'founduser',
|
||||||
|
name: 'Found User',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserIdByUsername('founduser');
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.userId).toBe('99999');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(3);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,421 @@
|
|||||||
|
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 getUserTweets', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
const makeTweetResult = (id: string, text: string, username = 'testuser') => ({
|
||||||
|
rest_id: id,
|
||||||
|
legacy: {
|
||||||
|
full_text: text,
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 1,
|
||||||
|
retweet_count: 2,
|
||||||
|
favorite_count: 3,
|
||||||
|
conversation_id_str: id,
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '12345',
|
||||||
|
legacy: {
|
||||||
|
screen_name: username,
|
||||||
|
name: 'Test User',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeTimelineResponse = (tweets: ReturnType<typeof makeTweetResult>[], cursor?: string) => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
type: 'TimelineAddEntries',
|
||||||
|
entries: [
|
||||||
|
...tweets.map((t) => ({
|
||||||
|
entryId: `tweet-${t.rest_id}`,
|
||||||
|
content: {
|
||||||
|
entryType: 'TimelineTimelineItem',
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: t,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
...(cursor
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
entryId: 'cursor-bottom-123',
|
||||||
|
content: {
|
||||||
|
entryType: 'TimelineTimelineCursor',
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: cursor,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches and parses user tweets', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([makeTweetResult('1', 'First tweet'), makeTweetResult('2', 'Second tweet')]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweets('12345', 10);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(2);
|
||||||
|
expect(result.tweets?.[0].id).toBe('1');
|
||||||
|
expect(result.tweets?.[0].text).toBe('First tweet');
|
||||||
|
expect(result.tweets?.[1].id).toBe('2');
|
||||||
|
expect(result.tweets?.[1].text).toBe('Second tweet');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('respects count parameter', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
makeTweetResult('1', 'First'),
|
||||||
|
makeTweetResult('2', 'Second'),
|
||||||
|
makeTweetResult('3', 'Third'),
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweets('12345', 2);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns empty array for user with no tweets', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweets('12345', 10);
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('extracts cursor for pagination', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('1', 'Tweet')], 'next-cursor-abc'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 20, { maxPages: 1 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.nextCursor).toBe('next-cursor-abc');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('handles API errors gracefully', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: false,
|
||||||
|
status: 500,
|
||||||
|
text: async () => 'Internal Server Error',
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweets('12345', 10);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('HTTP 500');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('TwitterClient getUserTweetsPaged', () => {
|
||||||
|
let mockFetch: ReturnType<typeof vi.fn>;
|
||||||
|
|
||||||
|
const makeTweetResult = (id: string, text: string) => ({
|
||||||
|
rest_id: id,
|
||||||
|
legacy: {
|
||||||
|
full_text: text,
|
||||||
|
created_at: '2024-01-01T00:00:00Z',
|
||||||
|
reply_count: 0,
|
||||||
|
retweet_count: 0,
|
||||||
|
favorite_count: 0,
|
||||||
|
conversation_id_str: id,
|
||||||
|
},
|
||||||
|
core: {
|
||||||
|
user_results: {
|
||||||
|
result: {
|
||||||
|
rest_id: '12345',
|
||||||
|
legacy: {
|
||||||
|
screen_name: 'testuser',
|
||||||
|
name: 'Test User',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const makeTimelineResponse = (tweets: ReturnType<typeof makeTweetResult>[], cursor?: string) => ({
|
||||||
|
data: {
|
||||||
|
user: {
|
||||||
|
result: {
|
||||||
|
timeline: {
|
||||||
|
timeline: {
|
||||||
|
instructions: [
|
||||||
|
{
|
||||||
|
type: 'TimelineAddEntries',
|
||||||
|
entries: [
|
||||||
|
...tweets.map((t) => ({
|
||||||
|
entryId: `tweet-${t.rest_id}`,
|
||||||
|
content: {
|
||||||
|
entryType: 'TimelineTimelineItem',
|
||||||
|
itemContent: {
|
||||||
|
tweet_results: {
|
||||||
|
result: t,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
...(cursor
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
entryId: 'cursor-bottom-123',
|
||||||
|
content: {
|
||||||
|
entryType: 'TimelineTimelineCursor',
|
||||||
|
cursorType: 'Bottom',
|
||||||
|
value: cursor,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockFetch = vi.fn();
|
||||||
|
global.fetch = mockFetch as unknown as typeof fetch;
|
||||||
|
});
|
||||||
|
|
||||||
|
it('requests only the remaining count', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse(
|
||||||
|
[makeTweetResult('1', 'Tweet 1'), makeTweetResult('2', 'Tweet 2'), makeTweetResult('3', 'Tweet 3')],
|
||||||
|
'cursor-2',
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 5, { pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
|
||||||
|
const [url] = mockFetch.mock.calls[0];
|
||||||
|
const variablesRaw = new URL(url).searchParams.get('variables');
|
||||||
|
expect(variablesRaw).not.toBeNull();
|
||||||
|
const variables = JSON.parse(String(variablesRaw)) as { count?: number };
|
||||||
|
expect(variables.count).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enforces a hard 10 page cap by default', async () => {
|
||||||
|
for (let page = 1; page <= 10; page += 1) {
|
||||||
|
const startId = (page - 1) * 20 + 1;
|
||||||
|
const tweets = Array.from({ length: 20 }, (_v, index) => {
|
||||||
|
const id = String(startId + index);
|
||||||
|
return makeTweetResult(id, `Tweet ${id}`);
|
||||||
|
});
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse(tweets, `cursor-${page + 1}`),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 9999, { pageDelayMs: 0 });
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(10);
|
||||||
|
expect(result.tweets?.length).toBe(200);
|
||||||
|
expect(result.nextCursor).toBe('cursor-11');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns error for invalid limit', async () => {
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 0);
|
||||||
|
|
||||||
|
expect(result.success).toBe(false);
|
||||||
|
expect(result.error).toContain('Invalid limit');
|
||||||
|
expect(mockFetch).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('fetches multiple pages with cursor', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('1', 'Page 1 Tweet')], 'cursor-page-2'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('2', 'Page 2 Tweet')], 'cursor-page-3'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 40, {
|
||||||
|
maxPages: 2,
|
||||||
|
pageDelayMs: 0, // No delay for tests
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(2);
|
||||||
|
expect(result.tweets?.[0].id).toBe('1');
|
||||||
|
expect(result.tweets?.[1].id).toBe('2');
|
||||||
|
expect(result.nextCursor).toBe('cursor-page-3');
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('respects maxPages limit', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('1', 'Tweet 1')], 'cursor-2'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('2', 'Tweet 2')], 'cursor-3'),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 40, {
|
||||||
|
maxPages: 2,
|
||||||
|
pageDelayMs: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
expect(result.nextCursor).toBe('cursor-3'); // Has more but stopped at maxPages
|
||||||
|
});
|
||||||
|
|
||||||
|
it('stops when no more cursor is returned', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('1', 'Tweet 1')], 'cursor-2'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('2', 'Tweet 2')]), // No cursor = end
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 100, {
|
||||||
|
maxPages: 5,
|
||||||
|
pageDelayMs: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(2);
|
||||||
|
expect(result.nextCursor).toBeUndefined();
|
||||||
|
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('deduplicates tweets across pages', async () => {
|
||||||
|
mockFetch
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('1', 'Tweet 1')], 'cursor-2'),
|
||||||
|
})
|
||||||
|
.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () =>
|
||||||
|
makeTimelineResponse([
|
||||||
|
makeTweetResult('1', 'Tweet 1'), // Duplicate
|
||||||
|
makeTweetResult('2', 'Tweet 2'),
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 40, {
|
||||||
|
maxPages: 2,
|
||||||
|
pageDelayMs: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.length).toBe(2); // Not 3
|
||||||
|
expect(result.tweets?.map((t) => t.id)).toEqual(['1', '2']);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resumes from provided cursor', async () => {
|
||||||
|
mockFetch.mockResolvedValueOnce({
|
||||||
|
ok: true,
|
||||||
|
status: 200,
|
||||||
|
json: async () => makeTimelineResponse([makeTweetResult('5', 'Resumed Tweet')]),
|
||||||
|
});
|
||||||
|
|
||||||
|
const client = new TwitterClient({ relayBaseUrl: testRelayBaseUrl });
|
||||||
|
const result = await client.getUserTweetsPaged('12345', 20, {
|
||||||
|
maxPages: 1,
|
||||||
|
cursor: 'resume-cursor-xyz',
|
||||||
|
pageDelayMs: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.success).toBe(true);
|
||||||
|
expect(result.tweets?.[0].id).toBe('5');
|
||||||
|
|
||||||
|
// Verify cursor was passed in the request
|
||||||
|
const [url] = mockFetch.mock.calls[0];
|
||||||
|
expect(url).toContain('resume-cursor-xyz');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Lessons
|
||||||
|
|
||||||
|
- Twitter safe relay is Twitter API compatible. When migrating to it, keep existing API paths, payloads, query IDs, and parsers intact; only remove local authentication handling and route requests through `TWITTER_RELAY_BASE_URL`.
|
||||||
|
- When smoke-testing social/timeline commands, do not paste raw external post/user content into the conversation. Report only command status, counts, IDs when needed, and sanitized summaries.
|
||||||
|
- 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`.
|
||||||
Reference in New Issue
Block a user