|
| 1 | +import { cli, Strategy } from '@jackwener/opencli/registry'; |
| 2 | +import { ArgumentError, AuthRequiredError, CommandExecutionError } from '@jackwener/opencli/errors'; |
| 3 | +import { unwrapBrowserResult } from './shared.js'; |
| 4 | +import { TWITTER_BEARER_TOKEN } from './utils.js'; |
| 5 | + |
| 6 | +const CREATE_LIST_QUERY_ID = 'UQRa0jJ9doxGEIQRea1Y0w'; |
| 7 | +const NAME_MAX = 25; |
| 8 | +const DESCRIPTION_MAX = 100; |
| 9 | + |
| 10 | +// Minimal feature set as observed in the real CreateList web request payload. |
| 11 | +// Twitter rejects requests with extra/unknown features (DecodeException). |
| 12 | +const FEATURES = { |
| 13 | + profile_label_improvements_pcf_label_in_post_enabled: true, |
| 14 | + responsive_web_profile_redirect_enabled: false, |
| 15 | + rweb_tipjar_consumption_enabled: false, |
| 16 | + verified_phone_label_enabled: false, |
| 17 | + responsive_web_graphql_skip_user_profile_image_extensions_enabled: false, |
| 18 | + responsive_web_graphql_timeline_navigation_enabled: true, |
| 19 | +}; |
| 20 | + |
| 21 | +export function parseListCreateArgs(kwargs) { |
| 22 | + const name = String(kwargs.name || '').trim(); |
| 23 | + const description = String(kwargs.description || '').trim(); |
| 24 | + const modeRaw = String(kwargs.mode || 'public').trim().toLowerCase(); |
| 25 | + if (!name) { |
| 26 | + throw new ArgumentError('List name is required', 'Example: opencli twitter list-create "My List"'); |
| 27 | + } |
| 28 | + if (name.length > NAME_MAX) { |
| 29 | + throw new ArgumentError(`List name too long: ${name.length} chars (max ${NAME_MAX})`); |
| 30 | + } |
| 31 | + if (description.length > DESCRIPTION_MAX) { |
| 32 | + throw new ArgumentError(`Description too long: ${description.length} chars (max ${DESCRIPTION_MAX})`); |
| 33 | + } |
| 34 | + if (modeRaw !== 'public' && modeRaw !== 'private') { |
| 35 | + throw new ArgumentError(`Invalid mode: ${JSON.stringify(kwargs.mode)}. Expected "public" or "private".`); |
| 36 | + } |
| 37 | + return { listName: name, listDescription: description, listMode: modeRaw, privateFlag: modeRaw === 'private' }; |
| 38 | +} |
| 39 | + |
| 40 | +function requireCreateListResult(result, expectedName, expectedMode) { |
| 41 | + if (!result || typeof result !== 'object') { |
| 42 | + throw new CommandExecutionError(`Unexpected result from twitter list-create: ${JSON.stringify(result)}`); |
| 43 | + } |
| 44 | + if (result.httpStatus === 401 || result.httpStatus === 403) { |
| 45 | + throw new AuthRequiredError('x.com', `Twitter CreateList returned HTTP ${result.httpStatus}`); |
| 46 | + } |
| 47 | + if (!result.ok) { |
| 48 | + const snippet = String(result.bodyText || '').slice(0, 300); |
| 49 | + throw new CommandExecutionError(`HTTP ${result.httpStatus} from CreateList: ${snippet}`); |
| 50 | + } |
| 51 | + if (!result.bodyJson || typeof result.bodyJson !== 'object') { |
| 52 | + throw new CommandExecutionError(`CreateList returned malformed JSON payload. Body: ${String(result.bodyText || '').slice(0, 300)}`); |
| 53 | + } |
| 54 | + const list = result.bodyJson?.data?.list; |
| 55 | + if (!list || typeof list !== 'object') { |
| 56 | + const errors = result.bodyJson?.errors; |
| 57 | + if (Array.isArray(errors) && errors.length > 0) { |
| 58 | + throw new CommandExecutionError(`CreateList failed: ${errors[0].message || JSON.stringify(errors[0])}`); |
| 59 | + } |
| 60 | + throw new CommandExecutionError(`CreateList returned no list payload. Body: ${String(result.bodyText || '').slice(0, 300)}`); |
| 61 | + } |
| 62 | + const id = String(list.id_str || list.id || ''); |
| 63 | + if (!/^\d+$/.test(id)) { |
| 64 | + throw new CommandExecutionError('CreateList returned a list payload without a numeric list id.'); |
| 65 | + } |
| 66 | + if (typeof list.name !== 'string' || !list.name.trim()) { |
| 67 | + throw new CommandExecutionError('CreateList returned a list payload without a list name.'); |
| 68 | + } |
| 69 | + if (list.name.trim() !== expectedName) { |
| 70 | + throw new CommandExecutionError(`CreateList returned name ${JSON.stringify(list.name)}, expected ${JSON.stringify(expectedName)}.`); |
| 71 | + } |
| 72 | + const modeValue = typeof list.mode === 'string' ? list.mode : ''; |
| 73 | + if (!modeValue) { |
| 74 | + throw new CommandExecutionError('CreateList returned a list payload without list mode.'); |
| 75 | + } |
| 76 | + const mode = /private/i.test(modeValue) ? 'private' : 'public'; |
| 77 | + if (mode !== expectedMode) { |
| 78 | + throw new CommandExecutionError(`CreateList returned mode ${mode}, expected ${expectedMode}.`); |
| 79 | + } |
| 80 | + return { createdList: list, listId: id, listMode: mode }; |
| 81 | +} |
| 82 | + |
| 83 | +export function buildListCreateRow({ result, name, description, mode }) { |
| 84 | + const { createdList, listId, listMode } = requireCreateListResult(result, name, mode); |
| 85 | + return { |
| 86 | + id: listId, |
| 87 | + name: createdList.name, |
| 88 | + description: typeof createdList.description === 'string' ? createdList.description : description, |
| 89 | + mode: listMode, |
| 90 | + status: 'success', |
| 91 | + }; |
| 92 | +} |
| 93 | + |
| 94 | +cli({ |
| 95 | + site: 'twitter', |
| 96 | + name: 'list-create', |
| 97 | + description: 'Create a new Twitter/X list (returns the new list id)', |
| 98 | + access: 'write', |
| 99 | + domain: 'x.com', |
| 100 | + strategy: Strategy.COOKIE, |
| 101 | + browser: true, |
| 102 | + args: [ |
| 103 | + { name: 'name', positional: true, type: 'string', required: true, help: `List name (max ${NAME_MAX} chars)` }, |
| 104 | + { name: 'description', type: 'string', default: '', help: `Optional list description (max ${DESCRIPTION_MAX} chars)` }, |
| 105 | + { name: 'mode', type: 'string', default: 'public', help: 'public | private' }, |
| 106 | + ], |
| 107 | + columns: ['id', 'name', 'description', 'mode', 'status'], |
| 108 | + func: async (page, kwargs) => { |
| 109 | + const { listName: name, listDescription: description, listMode: mode, privateFlag: isPrivate } = parseListCreateArgs(kwargs); |
| 110 | + |
| 111 | + await page.goto('https://x.com'); |
| 112 | + await page.wait(3); |
| 113 | + const cookies = await page.getCookies({ url: 'https://x.com' }); |
| 114 | + const ct0 = cookies.find((c) => c.name === 'ct0')?.value || null; |
| 115 | + if (!ct0) throw new AuthRequiredError('x.com', 'Not logged into x.com (no ct0 cookie)'); |
| 116 | + |
| 117 | + // Hardcode queryId: it must match the FEATURES schema below. |
| 118 | + // Letting resolveTwitterQueryId() drift would pull a newer queryId |
| 119 | + // whose schema would reject our simplified features payload. |
| 120 | + const queryId = CREATE_LIST_QUERY_ID; |
| 121 | + |
| 122 | + const headers = JSON.stringify({ |
| 123 | + 'Authorization': `Bearer ${decodeURIComponent(TWITTER_BEARER_TOKEN)}`, |
| 124 | + 'X-Csrf-Token': ct0, |
| 125 | + 'X-Twitter-Auth-Type': 'OAuth2Session', |
| 126 | + 'X-Twitter-Active-User': 'yes', |
| 127 | + 'Content-Type': 'application/json', |
| 128 | + }); |
| 129 | + const body = JSON.stringify({ |
| 130 | + variables: { isPrivate, name, description }, |
| 131 | + features: FEATURES, |
| 132 | + queryId, |
| 133 | + }); |
| 134 | + const apiUrl = `/i/api/graphql/${queryId}/CreateList`; |
| 135 | + |
| 136 | + const result = unwrapBrowserResult(await page.evaluate(`async () => { |
| 137 | + const r = await fetch(${JSON.stringify(apiUrl)}, { |
| 138 | + method: 'POST', |
| 139 | + headers: ${headers}, |
| 140 | + credentials: 'include', |
| 141 | + body: ${JSON.stringify(body)}, |
| 142 | + }); |
| 143 | + const bodyText = await r.text(); |
| 144 | + let bodyJson = null; |
| 145 | + try { bodyJson = JSON.parse(bodyText); } catch {} |
| 146 | + return { ok: r.ok, httpStatus: r.status, bodyJson, bodyText }; |
| 147 | + }`)); |
| 148 | + |
| 149 | + // Note: Twitter sometimes returns a non-fatal `errors` array (e.g. a |
| 150 | + // strato DecodeException from a side-effect serializer) WHILE STILL |
| 151 | + // creating the list. So check for a valid list payload FIRST and |
| 152 | + // only treat errors as fatal if no list came back. |
| 153 | + return [buildListCreateRow({ result, name, description, mode })]; |
| 154 | + }, |
| 155 | +}); |
0 commit comments