chore: merge origin/main
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { extractBookmarkFolderId } from '../src/lib/extract-bookmark-folder-id.js';
|
||||
import { extractTweetId } from '../src/lib/extract-tweet-id.js';
|
||||
|
||||
describe('CLI utilities', () => {
|
||||
@@ -29,4 +30,30 @@ describe('CLI utilities', () => {
|
||||
expect(extractTweetId(url)).toBe('1234567890123456789');
|
||||
});
|
||||
});
|
||||
|
||||
describe('extractBookmarkFolderId', () => {
|
||||
it('should extract ID from x.com bookmarks URL', () => {
|
||||
const url = 'https://x.com/i/bookmarks/1976792203235119344';
|
||||
expect(extractBookmarkFolderId(url)).toBe('1976792203235119344');
|
||||
});
|
||||
|
||||
it('should extract ID from twitter.com bookmarks URL', () => {
|
||||
const url = 'https://twitter.com/i/bookmarks/1976792203235119344';
|
||||
expect(extractBookmarkFolderId(url)).toBe('1976792203235119344');
|
||||
});
|
||||
|
||||
it('should accept a numeric ID as-is', () => {
|
||||
const id = '1976792203235119344';
|
||||
expect(extractBookmarkFolderId(id)).toBe('1976792203235119344');
|
||||
});
|
||||
|
||||
it('should return null for invalid values', () => {
|
||||
expect(extractBookmarkFolderId('not-an-id')).toBeNull();
|
||||
});
|
||||
|
||||
it('should return null for folder_id query URLs', () => {
|
||||
const url = 'https://x.com/i/bookmarks?folder_id=1976792203235119344';
|
||||
expect(extractBookmarkFolderId(url)).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+63
-5
@@ -18,8 +18,6 @@ vi.mock('@steipete/sweet-cookie', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
const itIfDarwin = process.platform === 'darwin' ? it : it.skip;
|
||||
|
||||
describe('cookies', () => {
|
||||
const originalEnv = process.env;
|
||||
|
||||
@@ -63,7 +61,10 @@ describe('cookies', () => {
|
||||
expect(result.cookies.source).toContain('Firefox');
|
||||
});
|
||||
|
||||
itIfDarwin('honors cookieSource=safari', async () => {
|
||||
it('honors cookieSource=safari', async () => {
|
||||
if (process.platform !== 'darwin') {
|
||||
return;
|
||||
}
|
||||
sweet.results.set('safari', {
|
||||
cookies: [
|
||||
{ name: 'auth_token', value: 'safari_auth', domain: 'x.com' },
|
||||
@@ -191,10 +192,64 @@ describe('cookies', () => {
|
||||
expect(result.cookies.ct0).toBe('test_ct0');
|
||||
expect(result.cookies.source).toContain('Chrome');
|
||||
});
|
||||
|
||||
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', () => {
|
||||
itIfDarwin('returns cookies from Safari', async () => {
|
||||
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' },
|
||||
@@ -211,7 +266,10 @@ describe('cookies', () => {
|
||||
expect(result.cookies.source).toBe('Safari');
|
||||
});
|
||||
|
||||
itIfDarwin('prefers Safari over Chrome when both are available', async () => {
|
||||
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' },
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mentionsQueryFromUserOption, normalizeHandle } from '../src/lib/normalize-handle.js';
|
||||
|
||||
const INVALID_HANDLE_REGEX = /Invalid --user handle/;
|
||||
|
||||
describe('normalizeHandle', () => {
|
||||
it('accepts bare handle', () => {
|
||||
expect(normalizeHandle('steipete')).toBe('steipete');
|
||||
@@ -36,6 +38,6 @@ describe('mentionsQueryFromUserOption', () => {
|
||||
it('returns error for invalid handle', () => {
|
||||
const result = mentionsQueryFromUserOption('@stei-pete');
|
||||
expect(result.query).toBeNull();
|
||||
expect(result.error).toMatch(/Invalid --user handle/);
|
||||
expect(result.error).toMatch(INVALID_HANDLE_REGEX);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdir, readFile } from 'node:fs/promises';
|
||||
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
@@ -8,6 +8,7 @@ import { createRuntimeQueryIdStore } from '../src/lib/runtime-query-ids.js';
|
||||
describe('runtime-query-ids', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
delete process.env.BIRD_QUERY_IDS_CACHE;
|
||||
});
|
||||
|
||||
it('refreshes IDs by scanning discovered bundles and persists cache', async () => {
|
||||
@@ -60,4 +61,83 @@ describe('runtime-query-ids', () => {
|
||||
const parsed = JSON.parse(raw) as { ids?: Record<string, string> };
|
||||
expect(parsed.ids?.SearchTimeline).toBe('EEE');
|
||||
});
|
||||
|
||||
it('uses env cache path override and returns fresh snapshot without refreshing', async () => {
|
||||
const cacheDir = path.join(os.tmpdir(), `bird-test-${randomUUID()}`);
|
||||
await mkdir(cacheDir, { recursive: true });
|
||||
const cachePath = path.join(cacheDir, 'query-ids-cache.json');
|
||||
process.env.BIRD_QUERY_IDS_CACHE = cachePath;
|
||||
|
||||
const snapshot = {
|
||||
fetchedAt: new Date().toISOString(),
|
||||
ttlMs: 60_000,
|
||||
ids: { CreateTweet: 'AAA' },
|
||||
discovery: { pages: ['https://x.com/'], bundles: ['main.js'] },
|
||||
};
|
||||
await writeFile(cachePath, JSON.stringify(snapshot), 'utf8');
|
||||
|
||||
const fetchMock = vi.fn();
|
||||
const store = createRuntimeQueryIdStore({ fetchImpl: fetchMock as unknown as typeof fetch });
|
||||
const info = await store.refresh(['CreateTweet']);
|
||||
|
||||
expect(store.cachePath).toBe(cachePath);
|
||||
expect(info?.snapshot.ids.CreateTweet).toBe('AAA');
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
|
||||
store.clearMemory();
|
||||
});
|
||||
|
||||
it('returns current snapshot when refresh finds no matching operations', async () => {
|
||||
const cacheDir = path.join(os.tmpdir(), `bird-test-${randomUUID()}`);
|
||||
await mkdir(cacheDir, { recursive: true });
|
||||
const cachePath = path.join(cacheDir, 'query-ids.json');
|
||||
|
||||
const snapshot = {
|
||||
fetchedAt: new Date(0).toISOString(),
|
||||
ttlMs: 1,
|
||||
ids: { CreateTweet: 'AAA' },
|
||||
discovery: { pages: ['https://x.com/'], bundles: ['main.test.js'] },
|
||||
};
|
||||
await writeFile(cachePath, JSON.stringify(snapshot), 'utf8');
|
||||
|
||||
const html = `<script src="https://abs.twimg.com/responsive-web/client-web/main.test.js"></script>`;
|
||||
const js = 'console.log("no ops here")';
|
||||
|
||||
const fetchMock = vi.fn(async (url: string | URL) => {
|
||||
const asString = String(url);
|
||||
if (asString.startsWith('https://x.com/')) {
|
||||
return new Response(html, { status: 200 });
|
||||
}
|
||||
if (asString.startsWith('https://abs.twimg.com/')) {
|
||||
return new Response(js, { status: 200 });
|
||||
}
|
||||
return new Response('not found', { status: 404 });
|
||||
});
|
||||
|
||||
const store = createRuntimeQueryIdStore({
|
||||
cachePath,
|
||||
ttlMs: 1,
|
||||
fetchImpl: fetchMock as unknown as typeof fetch,
|
||||
});
|
||||
|
||||
const info = await store.refresh(['CreateTweet']);
|
||||
expect(info?.snapshot.ids.CreateTweet).toBe('AAA');
|
||||
});
|
||||
|
||||
it('throws when no bundles can be discovered', async () => {
|
||||
const cacheDir = path.join(os.tmpdir(), `bird-test-${randomUUID()}`);
|
||||
await mkdir(cacheDir, { recursive: true });
|
||||
const cachePath = path.join(cacheDir, 'query-ids.json');
|
||||
|
||||
const fetchMock = vi.fn(async () => new Response('nope', { status: 500 }));
|
||||
|
||||
const store = createRuntimeQueryIdStore({
|
||||
cachePath,
|
||||
fetchImpl: fetchMock as unknown as typeof fetch,
|
||||
});
|
||||
|
||||
await expect(store.refresh(['CreateTweet'], { force: true })).rejects.toThrow(
|
||||
'No client bundles discovered; x.com layout may have changed.',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,360 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
|
||||
const validCookies = {
|
||||
authToken: 'test_auth_token',
|
||||
ct0: 'test_ct0_token',
|
||||
cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token',
|
||||
source: 'test',
|
||||
};
|
||||
|
||||
type ResponseLike = {
|
||||
ok: boolean;
|
||||
status: number;
|
||||
json: () => Promise<unknown>;
|
||||
text: () => Promise<string>;
|
||||
};
|
||||
|
||||
type TwitterClientApiPrivate = TwitterClient & {
|
||||
getBookmarksQueryIds: () => Promise<string[]>;
|
||||
getLikesQueryIds: () => Promise<string[]>;
|
||||
getCurrentUser: () => Promise<{
|
||||
success: boolean;
|
||||
user?: { id: string; username: string; name: string };
|
||||
error?: string;
|
||||
}>;
|
||||
getBookmarkFolderQueryIds: () => Promise<string[]>;
|
||||
};
|
||||
|
||||
const makeResponse = (overrides: Partial<ResponseLike> = {}): ResponseLike => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async (): Promise<unknown> => ({}),
|
||||
text: async (): Promise<string> => '',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('TwitterClient API coverage', () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('createTweet fallback paths', () => {
|
||||
it('returns an error when retry response is not ok', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 404, text: async () => 'nope' }))
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 404, text: async () => 'nope' }))
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'boom' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.tweet('hi');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('returns API errors when retry response contains errors', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 404, text: async () => 'nope' }))
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 404, text: async () => 'nope' }))
|
||||
.mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ errors: [{ message: 'rate limited', code: 1 }] }),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.tweet('hi');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('rate limited');
|
||||
});
|
||||
|
||||
it('returns an error when retry response has no tweet id', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 404, text: async () => 'nope' }))
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 404, text: async () => 'nope' }))
|
||||
.mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ data: { create_tweet: { tweet_results: { result: {} } } } }),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.tweet('hi');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('no ID');
|
||||
});
|
||||
});
|
||||
|
||||
describe('search error paths', () => {
|
||||
it('returns an error for non-ok responses', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.search('test');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('returns errors from payloads', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ errors: [{ message: 'bad' }] }),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.search('test');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('bad');
|
||||
});
|
||||
|
||||
it('returns an error when fetching throws', async () => {
|
||||
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.search('test');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('boom');
|
||||
});
|
||||
|
||||
it('returns the second attempt error after 404s', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.search('test');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('HTTP 404');
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookmarks error paths', () => {
|
||||
it('returns an error for non-ok responses', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarks(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('returns API errors from payloads', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ errors: [{ message: 'bad' }] }),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarks(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('bad');
|
||||
});
|
||||
|
||||
it('returns an error when fetching throws', async () => {
|
||||
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarks(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('boom');
|
||||
});
|
||||
|
||||
it('returns unknown error when no query ids are available', async () => {
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||
clientPrivate.getBookmarksQueryIds = async () => [];
|
||||
|
||||
const result = await client.getBookmarks(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Unknown error fetching bookmarks');
|
||||
});
|
||||
|
||||
it('returns the second attempt error after 404s', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarks(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('HTTP 404');
|
||||
});
|
||||
});
|
||||
describe('likes error paths', () => {
|
||||
const stubCurrentUser = async () => ({
|
||||
success: true,
|
||||
user: { id: '123', username: 'tester', name: 'Tester' },
|
||||
});
|
||||
|
||||
it('returns an error for non-ok responses', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||
|
||||
const result = await client.getLikes(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('returns API errors from payloads', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ errors: [{ message: 'bad' }] }),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||
|
||||
const result = await client.getLikes(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('bad');
|
||||
});
|
||||
|
||||
it('returns an error when fetching throws', async () => {
|
||||
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||
|
||||
const result = await client.getLikes(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('boom');
|
||||
});
|
||||
|
||||
it('returns unknown error when no query ids are available', async () => {
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||
clientPrivate.getLikesQueryIds = async () => [];
|
||||
|
||||
const result = await client.getLikes(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Unknown error fetching likes');
|
||||
});
|
||||
|
||||
it('returns the second attempt error after 404s', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||
clientPrivate.getCurrentUser = stubCurrentUser;
|
||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||
|
||||
const result = await client.getLikes(1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('HTTP 404');
|
||||
});
|
||||
});
|
||||
describe('bookmark folder error paths', () => {
|
||||
it('returns an error for non-ok responses', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'down' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('returns API errors from payloads', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ errors: [{ message: 'bad' }] }),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('bad');
|
||||
});
|
||||
|
||||
it('returns an error when fetching throws', async () => {
|
||||
const mockFetch = vi.fn().mockRejectedValue(new Error('boom'));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('boom');
|
||||
});
|
||||
|
||||
it('returns unknown error when no query ids are available', async () => {
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientApiPrivate;
|
||||
clientPrivate.getBookmarkFolderQueryIds = async () => [];
|
||||
|
||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Unknown error fetching bookmark folder');
|
||||
});
|
||||
|
||||
it('returns the second attempt error after 404s', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValue(makeResponse({ ok: false, status: 404, text: async () => 'nope' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarkFolderTimeline('123', 1);
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('HTTP 404');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,248 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { runtimeQueryIds } from '../src/lib/runtime-query-ids.js';
|
||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
|
||||
const validCookies = {
|
||||
authToken: 'test_auth_token',
|
||||
ct0: 'test_ct0_token',
|
||||
cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token',
|
||||
source: 'test',
|
||||
};
|
||||
|
||||
type ResponseLike = {
|
||||
ok: boolean;
|
||||
status: number;
|
||||
json: () => Promise<unknown>;
|
||||
text: () => Promise<string>;
|
||||
};
|
||||
|
||||
type TwitterClientPrivate = TwitterClient & {
|
||||
refreshQueryIds: () => Promise<void>;
|
||||
fetchWithTimeout: (url: string, init: RequestInit) => Promise<ResponseLike>;
|
||||
ensureClientUserId: () => Promise<void>;
|
||||
getBaseHeaders: () => Record<string, string>;
|
||||
fetchUserArticlePlainText: (userId: string, tweetId: string) => Promise<{ title?: string; plainText?: string }>;
|
||||
fetchTweetDetail: (tweetId: string) => Promise<{ success: true } | { success: false; error: string }>;
|
||||
postStatusUpdate: (input: { text: string }) => Promise<{ success: boolean; error?: string }>;
|
||||
};
|
||||
|
||||
const makeResponse = (overrides: Partial<ResponseLike> = {}): ResponseLike => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async (): Promise<unknown> => ({}),
|
||||
text: async (): Promise<string> => '',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('TwitterClient core coverage', () => {
|
||||
const originalFetch = global.fetch;
|
||||
const originalNodeEnv = process.env.NODE_ENV;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
process.env.NODE_ENV = originalNodeEnv;
|
||||
delete process.env.BIRD_DEBUG_ARTICLE;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('refreshQueryIds calls runtime refresh outside test env', async () => {
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const refreshSpy = vi.spyOn(runtimeQueryIds, 'refresh').mockResolvedValue(null);
|
||||
process.env.NODE_ENV = 'production';
|
||||
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
await clientPrivate.refreshQueryIds();
|
||||
|
||||
expect(refreshSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('fetchWithTimeout uses an abort signal when timeout is set', async () => {
|
||||
const mockFetch = vi.fn(async (_url: string, init?: RequestInit) => {
|
||||
expect(init?.signal).toBeInstanceOf(AbortSignal);
|
||||
return makeResponse();
|
||||
});
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies, timeoutMs: 5 });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
await clientPrivate.fetchWithTimeout('https://example.com', { method: 'GET' });
|
||||
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('returns a not found error when tweet data is missing', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({
|
||||
data: {
|
||||
threaded_conversation_with_injections_v2: {
|
||||
instructions: [
|
||||
{
|
||||
entries: [
|
||||
{
|
||||
content: {
|
||||
itemContent: {
|
||||
tweet_results: {
|
||||
result: {
|
||||
rest_id: 'other',
|
||||
legacy: { full_text: 'nope', created_at: '2024-01-01T00:00:00Z' },
|
||||
core: { user_results: { result: { legacy: { screen_name: 'user', name: 'User' } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getTweet('123');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Tweet not found in response');
|
||||
});
|
||||
|
||||
it('adds client user id header after ensureClientUserId', async () => {
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
process.env.NODE_ENV = 'production';
|
||||
|
||||
vi.spyOn(client, 'getCurrentUser').mockResolvedValue({
|
||||
success: true,
|
||||
user: { id: '42', username: 'tester', name: 'Tester' },
|
||||
});
|
||||
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
await clientPrivate.ensureClientUserId();
|
||||
const headers = clientPrivate.getBaseHeaders();
|
||||
|
||||
expect(headers['x-twitter-client-user-id']).toBe('42');
|
||||
});
|
||||
|
||||
describe('fetchUserArticlePlainText failures', () => {
|
||||
it('returns empty object when response is not ok', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(makeResponse({ ok: false, status: 500 }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
||||
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('returns empty object when fetching throws', async () => {
|
||||
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
||||
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
|
||||
it('returns empty object when no matching tweet is found', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({
|
||||
data: {
|
||||
user: { result: { timeline: { timeline: { instructions: [] } } } },
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
const result = await clientPrivate.fetchUserArticlePlainText('user', 'tweet');
|
||||
|
||||
expect(result).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchTweetDetail error handling', () => {
|
||||
it('returns API errors from response payloads', async () => {
|
||||
const mockFetch = vi.fn().mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ errors: [{ message: 'bad news' }] }),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
const result = await clientPrivate.fetchTweetDetail('1');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('bad news');
|
||||
});
|
||||
|
||||
it('parses POST responses when GET returns 404', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 404, text: async () => 'nope' }))
|
||||
.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' } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
const result = await clientPrivate.fetchTweetDetail('1');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('returns an error when fetch throws', async () => {
|
||||
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
const result = await clientPrivate.fetchTweetDetail('1');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('boom');
|
||||
});
|
||||
});
|
||||
|
||||
describe('postStatusUpdate error handling', () => {
|
||||
it('returns an error when postStatusUpdate throws', async () => {
|
||||
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
const result = await clientPrivate.postStatusUpdate({ text: 'hello' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('boom');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
|
||||
const validCookies = {
|
||||
authToken: 'test_auth_token',
|
||||
ct0: 'test_ct0_token',
|
||||
cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token',
|
||||
source: 'test',
|
||||
};
|
||||
|
||||
type ResponseLike = {
|
||||
ok: boolean;
|
||||
status: number;
|
||||
json: () => Promise<unknown>;
|
||||
text: () => Promise<string>;
|
||||
};
|
||||
|
||||
type TwitterClientUploadPrivate = TwitterClient & {
|
||||
sleep: (ms: number) => Promise<void>;
|
||||
extractArticleText: (result: unknown) => string | undefined;
|
||||
};
|
||||
|
||||
const makeResponse = (overrides: Partial<ResponseLike> = {}): ResponseLike => ({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async (): Promise<unknown> => ({}),
|
||||
text: async (): Promise<string> => '',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('TwitterClient upload coverage', () => {
|
||||
const originalFetch = global.fetch;
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
delete process.env.BIRD_DEBUG_ARTICLE;
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('uploadMedia error paths', () => {
|
||||
it('rejects unsupported media types', async () => {
|
||||
global.fetch = vi.fn() as unknown as typeof fetch;
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1, 2, 3]), mimeType: 'application/pdf' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns an error when INIT fails', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('returns an error when APPEND fails', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({ media_id_string: '1' }) }))
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('returns an error when FINALIZE fails', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({ media_id_string: '1' }) }))
|
||||
.mockResolvedValueOnce(makeResponse())
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 500, text: async () => 'nope' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 500');
|
||||
});
|
||||
|
||||
it('returns an error when media processing fails', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({ media_id_string: '1' }) }))
|
||||
.mockResolvedValueOnce(makeResponse())
|
||||
.mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ processing_info: { state: 'failed', error: { message: 'processing failed' } } }),
|
||||
}),
|
||||
);
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'video/mp4' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('processing failed');
|
||||
});
|
||||
|
||||
it('returns an error when STATUS fails', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({ media_id_string: '1' }) }))
|
||||
.mockResolvedValueOnce(makeResponse())
|
||||
.mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ processing_info: { state: 'pending', check_after_secs: 0 } }),
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 503, text: async () => 'down' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientUploadPrivate;
|
||||
clientPrivate.sleep = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'video/mp4' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 503');
|
||||
});
|
||||
|
||||
it('retries STATUS and continues when processing is pending', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({ media_id_string: '1' }) }))
|
||||
.mockResolvedValueOnce(makeResponse())
|
||||
.mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ processing_info: { state: 'pending', check_after_secs: 0 } }),
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
makeResponse({
|
||||
json: async () => ({ processing_info: { state: 'pending', check_after_secs: 0 } }),
|
||||
}),
|
||||
)
|
||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({ processing_info: { state: 'succeeded' } }) }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientUploadPrivate;
|
||||
clientPrivate.sleep = vi.fn().mockResolvedValue(undefined);
|
||||
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'video/mp4' });
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
});
|
||||
|
||||
it('returns an error when metadata upload fails', async () => {
|
||||
const mockFetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({ media_id_string: '1' }) }))
|
||||
.mockResolvedValueOnce(makeResponse())
|
||||
.mockResolvedValueOnce(makeResponse({ json: async () => ({}) }))
|
||||
.mockResolvedValueOnce(makeResponse({ ok: false, status: 400, text: async () => 'bad' }));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png', alt: 'alt' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 400');
|
||||
});
|
||||
|
||||
it('returns an error when upload throws', async () => {
|
||||
const mockFetch = vi.fn().mockRejectedValueOnce(new Error('boom'));
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.uploadMedia({ data: new Uint8Array([1]), mimeType: 'image/png' });
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('boom');
|
||||
});
|
||||
});
|
||||
|
||||
describe('article extraction edge cases', () => {
|
||||
it('logs article payloads when debug flag is set', () => {
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
process.env.BIRD_DEBUG_ARTICLE = '1';
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
const clientPrivate = client as unknown as TwitterClientUploadPrivate;
|
||||
const result = clientPrivate.extractArticleText({
|
||||
rest_id: '1',
|
||||
article: {
|
||||
title: 'Title',
|
||||
plain_text: 'Body',
|
||||
article_results: { result: { title: 'Title', plain_text: 'Body' } },
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toBe('Title\n\nBody');
|
||||
expect(errorSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('drops duplicate body when it matches the title', () => {
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientUploadPrivate;
|
||||
const result = clientPrivate.extractArticleText({
|
||||
rest_id: '1',
|
||||
article: {
|
||||
title: 'Same',
|
||||
plain_text: 'Same',
|
||||
article_results: { result: { title: 'Same', plain_text: 'Same' } },
|
||||
},
|
||||
});
|
||||
|
||||
expect(result).toBe('Same');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,14 @@ describe('TwitterClient', () => {
|
||||
cookieHeader: 'auth_token=test_auth_token; ct0=test_ct0_token',
|
||||
source: 'test',
|
||||
};
|
||||
type TwitterClientPrivate = TwitterClient & {
|
||||
getCurrentUser: () => Promise<{
|
||||
success: boolean;
|
||||
user?: { id: string; username: string; name: string };
|
||||
error?: string;
|
||||
}>;
|
||||
getLikesQueryIds: () => Promise<string[]>;
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
global.fetch = originalFetch;
|
||||
@@ -1161,6 +1169,320 @@ describe('TwitterClient', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('bookmarks', () => {
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch = vi.fn();
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
});
|
||||
|
||||
it('fetches bookmarks and parses tweet results', 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',
|
||||
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' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarks(2);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.tweets?.[0].id).toBe('1');
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(options.method).toBe('GET');
|
||||
expect(String(url)).toContain('/Bookmarks?');
|
||||
const parsedVars = JSON.parse(new URL(url as string).searchParams.get('variables') as string);
|
||||
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).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('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({ cookies: validCookies });
|
||||
const clientPrivate = client as unknown as TwitterClientPrivate;
|
||||
clientPrivate.getCurrentUser = async () => ({
|
||||
success: true,
|
||||
user: { id: '42', username: 'tester', name: 'Tester' },
|
||||
});
|
||||
clientPrivate.getLikesQueryIds = async () => ['test'];
|
||||
|
||||
const result = await client.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('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();
|
||||
});
|
||||
});
|
||||
describe('bookmark folders', () => {
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch = vi.fn();
|
||||
global.fetch = mockFetch as unknown as typeof fetch;
|
||||
});
|
||||
|
||||
it('fetches bookmark folder timeline and parses tweet results', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: {
|
||||
bookmark_collection_timeline: {
|
||||
timeline: {
|
||||
instructions: [
|
||||
{
|
||||
entries: [
|
||||
{
|
||||
content: {
|
||||
itemContent: {
|
||||
tweet_results: {
|
||||
result: {
|
||||
rest_id: '9',
|
||||
legacy: {
|
||||
full_text: 'saved in folder',
|
||||
created_at: '2024-01-01T00:00:00Z',
|
||||
reply_count: 0,
|
||||
retweet_count: 0,
|
||||
favorite_count: 0,
|
||||
conversation_id_str: '9',
|
||||
},
|
||||
core: {
|
||||
user_results: {
|
||||
result: {
|
||||
rest_id: 'u9',
|
||||
legacy: { screen_name: 'folder', name: 'Folder' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.getBookmarkFolderTimeline('123', 2);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.tweets?.[0].id).toBe('9');
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(options.method).toBe('GET');
|
||||
expect(String(url)).toContain('/BookmarkFolderTimeline?');
|
||||
const parsedVars = JSON.parse(new URL(url as string).searchParams.get('variables') as string);
|
||||
expect(parsedVars.bookmark_collection_id).toBe('123');
|
||||
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).toBe(true);
|
||||
});
|
||||
|
||||
it('retries without count when API rejects the count variable', async () => {
|
||||
mockFetch
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
errors: [{ message: 'Variable "$count" is not defined by operation' }],
|
||||
}),
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
status: 200,
|
||||
json: async () => ({
|
||||
data: {
|
||||
bookmark_collection_timeline: {
|
||||
timeline: {
|
||||
instructions: [
|
||||
{
|
||||
entries: [
|
||||
{
|
||||
content: {
|
||||
itemContent: {
|
||||
tweet_results: {
|
||||
result: {
|
||||
rest_id: '9',
|
||||
legacy: {
|
||||
full_text: 'saved in folder',
|
||||
created_at: '2024-01-01T00:00:00Z',
|
||||
reply_count: 0,
|
||||
retweet_count: 0,
|
||||
favorite_count: 0,
|
||||
conversation_id_str: '9',
|
||||
},
|
||||
core: {
|
||||
user_results: {
|
||||
result: {
|
||||
rest_id: 'u9',
|
||||
legacy: { screen_name: 'folder', name: 'Folder' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const clientPrivate = client as TwitterClient & { getBookmarkFolderQueryIds: () => Promise<string[]> };
|
||||
clientPrivate.getBookmarkFolderQueryIds = async () => ['test'];
|
||||
|
||||
const result = await client.getBookmarkFolderTimeline('123', 2);
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(mockFetch).toHaveBeenCalledTimes(2);
|
||||
|
||||
const firstVars = JSON.parse(
|
||||
new URL(mockFetch.mock.calls[0][0] as string).searchParams.get('variables') as string,
|
||||
);
|
||||
const secondVars = JSON.parse(
|
||||
new URL(mockFetch.mock.calls[1][0] as string).searchParams.get('variables') as string,
|
||||
);
|
||||
|
||||
expect(firstVars.count).toBe(2);
|
||||
expect(secondVars.count).toBeUndefined();
|
||||
});
|
||||
});
|
||||
describe('conversation helpers', () => {
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
|
||||
|
||||
+59
-1
@@ -3,7 +3,13 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { FALLBACK_VERSION, formatVersionLine, resolveGitSha, resolvePackageVersion } from '../src/lib/version.js';
|
||||
import {
|
||||
FALLBACK_VERSION,
|
||||
formatVersionLine,
|
||||
getCliVersion,
|
||||
resolveGitSha,
|
||||
resolvePackageVersion,
|
||||
} from '../src/lib/version.js';
|
||||
|
||||
function withTempDir<T>(fn: (dir: string) => T): T {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'bird-version-test-'));
|
||||
@@ -53,6 +59,17 @@ describe('getCliVersion', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to VERSION file when package.json has no version', () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({}));
|
||||
fs.writeFileSync(path.join(dir, 'VERSION'), '5.5.5\n');
|
||||
const entry = path.join(dir, 'entry.ts');
|
||||
fs.writeFileSync(entry, '// noop');
|
||||
|
||||
expect(resolvePackageVersion(pathToFileURL(entry).href)).toBe('5.5.5');
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to unknown when no version files exist', () => {
|
||||
withTempDir((dir) => {
|
||||
const entry = path.join(dir, 'a', 'b', 'c', 'entry.ts');
|
||||
@@ -63,6 +80,31 @@ describe('getCliVersion', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when git HEAD is missing', () => {
|
||||
withTempDir((dir) => {
|
||||
const gitDir = path.join(dir, '.git');
|
||||
fs.mkdirSync(gitDir, { recursive: true });
|
||||
|
||||
const entry = path.join(dir, 'entry.ts');
|
||||
fs.writeFileSync(entry, '// noop');
|
||||
|
||||
expect(resolveGitSha(pathToFileURL(entry).href)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when git ref cannot be resolved', () => {
|
||||
withTempDir((dir) => {
|
||||
const gitDir = path.join(dir, '.git');
|
||||
fs.mkdirSync(gitDir, { recursive: true });
|
||||
fs.writeFileSync(path.join(gitDir, 'HEAD'), 'ref: refs/heads/main\n');
|
||||
|
||||
const entry = path.join(dir, 'entry.ts');
|
||||
fs.writeFileSync(entry, '// noop');
|
||||
|
||||
expect(resolveGitSha(pathToFileURL(entry).href)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('resolves git sha from .git directory HEAD', () => {
|
||||
withTempDir((dir) => {
|
||||
const gitDir = path.join(dir, '.git');
|
||||
@@ -113,6 +155,16 @@ describe('getCliVersion', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('returns null when no git directory exists', () => {
|
||||
withTempDir((dir) => {
|
||||
const entry = path.join(dir, 'nested', 'entry.ts');
|
||||
fs.mkdirSync(path.dirname(entry), { recursive: true });
|
||||
fs.writeFileSync(entry, '// noop');
|
||||
|
||||
expect(resolveGitSha(pathToFileURL(entry).href)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('formats version line with version + sha when both available', () => {
|
||||
withTempDir((dir) => {
|
||||
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ version: '3.3.3' }));
|
||||
@@ -126,4 +178,10 @@ describe('getCliVersion', () => {
|
||||
expect(formatVersionLine(pathToFileURL(entry).href)).toBe('3.3.3 (dddddddd)');
|
||||
});
|
||||
});
|
||||
|
||||
it('returns a CLI version string', () => {
|
||||
const value = getCliVersion();
|
||||
expect(typeof value).toBe('string');
|
||||
expect(value.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user