Initial commit: twitter-cli for posting tweets via GraphQL API
Features: - Post tweets and replies via Twitter GraphQL API - Cookie extraction from Chrome (macOS) - Env var and CLI argument authentication - 19 passing tests with vitest - Biome for linting
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('CLI utilities', () => {
|
||||
describe('extractTweetId', () => {
|
||||
// Testing the URL extraction logic inline since it's a simple function
|
||||
function extractTweetId(input: string): string {
|
||||
const urlMatch = input.match(/(?:twitter\.com|x\.com)\/\w+\/status\/(\d+)/);
|
||||
if (urlMatch) {
|
||||
return urlMatch[1];
|
||||
}
|
||||
return input;
|
||||
}
|
||||
|
||||
it('should extract ID from x.com URL', () => {
|
||||
const url = 'https://x.com/steipete/status/1234567890123456789';
|
||||
expect(extractTweetId(url)).toBe('1234567890123456789');
|
||||
});
|
||||
|
||||
it('should extract ID from twitter.com URL', () => {
|
||||
const url = 'https://twitter.com/steipete/status/1234567890123456789';
|
||||
expect(extractTweetId(url)).toBe('1234567890123456789');
|
||||
});
|
||||
|
||||
it('should extract ID from URL with query params', () => {
|
||||
const url = 'https://x.com/steipete/status/1234567890123456789?s=20';
|
||||
expect(extractTweetId(url)).toBe('1234567890123456789');
|
||||
});
|
||||
|
||||
it('should return ID as-is if already an ID', () => {
|
||||
const id = '1234567890123456789';
|
||||
expect(extractTweetId(id)).toBe('1234567890123456789');
|
||||
});
|
||||
|
||||
it('should handle URLs with www prefix', () => {
|
||||
// Note: our regex handles this because \w+ matches any word chars after the domain
|
||||
const url = 'https://x.com/user_name/status/1234567890123456789';
|
||||
expect(extractTweetId(url)).toBe('1234567890123456789');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
// Mock child_process.execSync to prevent actual shell commands
|
||||
vi.mock('node:child_process', () => ({
|
||||
execSync: vi.fn(() => ''),
|
||||
}));
|
||||
|
||||
// Mock fs to prevent actual file operations
|
||||
vi.mock('node:fs', () => ({
|
||||
existsSync: vi.fn(() => false),
|
||||
copyFileSync: vi.fn(),
|
||||
mkdtempSync: vi.fn(() => '/tmp/test-dir'),
|
||||
rmSync: vi.fn(),
|
||||
}));
|
||||
|
||||
describe('cookies', () => {
|
||||
const originalEnv = process.env;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
process.env = { ...originalEnv };
|
||||
// Clear Twitter-related env vars
|
||||
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('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.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({});
|
||||
|
||||
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({});
|
||||
|
||||
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({});
|
||||
|
||||
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({});
|
||||
|
||||
expect(result.warnings).toContain(
|
||||
'Missing auth_token - provide via --auth-token, AUTH_TOKEN env var, or login to x.com in Chrome',
|
||||
);
|
||||
expect(result.warnings).toContain('Missing ct0 - provide via --ct0, CT0 env var, or login to x.com in Chrome');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TwitterClient } from '../src/lib/twitter-client.js';
|
||||
|
||||
describe('TwitterClient', () => {
|
||||
const validCookies = {
|
||||
authToken: 'test_auth_token',
|
||||
ct0: 'test_ct0_token',
|
||||
source: 'test',
|
||||
};
|
||||
|
||||
describe('constructor', () => {
|
||||
it('should throw if authToken is missing', () => {
|
||||
expect(
|
||||
() =>
|
||||
new TwitterClient({
|
||||
cookies: { authToken: null, ct0: 'test', source: null },
|
||||
}),
|
||||
).toThrow('Both authToken and ct0 cookies are required');
|
||||
});
|
||||
|
||||
it('should throw if ct0 is missing', () => {
|
||||
expect(
|
||||
() =>
|
||||
new TwitterClient({
|
||||
cookies: { authToken: 'test', ct0: 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);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tweet', () => {
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch = vi.fn();
|
||||
global.fetch = mockFetch;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should post a tweet successfully', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: {
|
||||
create_tweet: {
|
||||
tweet_results: {
|
||||
result: {
|
||||
rest_id: '1234567890',
|
||||
legacy: {
|
||||
full_text: 'Hello world!',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.tweet('Hello world!');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.tweetId).toBe('1234567890');
|
||||
expect(mockFetch).toHaveBeenCalledTimes(1);
|
||||
|
||||
const [url, options] = mockFetch.mock.calls[0];
|
||||
expect(url).toContain('CreateTweet');
|
||||
expect(options.method).toBe('POST');
|
||||
|
||||
const body = JSON.parse(options.body);
|
||||
expect(body.variables.tweet_text).toBe('Hello world!');
|
||||
});
|
||||
|
||||
it('should handle API errors', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
errors: [{ message: 'Rate limit exceeded', code: 88 }],
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.tweet('Test');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('Rate limit exceeded');
|
||||
});
|
||||
|
||||
it('should handle HTTP errors', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: false,
|
||||
status: 403,
|
||||
text: async () => 'Forbidden',
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.tweet('Test');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toContain('HTTP 403');
|
||||
});
|
||||
|
||||
it('should handle network errors', async () => {
|
||||
mockFetch.mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.tweet('Test');
|
||||
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.error).toBe('Network error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('reply', () => {
|
||||
let mockFetch: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFetch = vi.fn();
|
||||
global.fetch = mockFetch;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('should post a reply with correct reply_to_tweet_id', async () => {
|
||||
mockFetch.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
data: {
|
||||
create_tweet: {
|
||||
tweet_results: {
|
||||
result: {
|
||||
rest_id: '9876543210',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const client = new TwitterClient({ cookies: validCookies });
|
||||
const result = await client.reply('This is a reply', '1234567890');
|
||||
|
||||
expect(result.success).toBe(true);
|
||||
expect(result.tweetId).toBe('9876543210');
|
||||
|
||||
const [, options] = mockFetch.mock.calls[0];
|
||||
const body = JSON.parse(options.body);
|
||||
expect(body.variables.reply.in_reply_to_tweet_id).toBe('1234567890');
|
||||
expect(body.variables.tweet_text).toBe('This is a reply');
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user