mirror of
https://github.com/jackwener/OpenCLI.git
synced 2026-09-14 18:25:42 +08:00
4fe9a73ebc
* refactor: migrate adapter imports to package exports Replace all relative imports (../../src/registry.js, ../../browser/cdp.js, etc.) with package exports (@jackwener/opencli/registry, @jackwener/opencli/errors, etc.) across all 484 adapter files. This decouples adapter import resolution from directory structure: - User CLIs in ~/.opencli/clis/ resolve via node_modules symlink - Internal adapters resolve via Node.js self-referencing - No more shim files needed for import resolution Changes: - package.json: add sub-path exports for all public modules - clis/**: replace relative imports with @jackwener/opencli/... - discovery.ts: simplify ensureUserCliCompatShims to symlink-only - registry-api.ts: export CommandArgs type - Remove root-level shim directories (browser/, download/, pipeline/) - Remove shim entries from tsconfig.json include and package.json files * test: add regression tests for package exports Prevents regressions like #788/#791 by: 1. Scanning all adapter files for forbidden relative imports (../../src/, ../../browser/, etc.) — fails if any remain 2. Verifying every package.json export maps to an existing source file 18 new test cases. * fix: use junction on Windows + broaden test patterns - discovery.ts: use 'junction' symlink type on Windows (no admin required) - package-exports.test.ts: generalize forbidden patterns to catch any depth of ../ traversal (not just ../../ and ../../../) * fix: update stale vi.mock/importActual paths in adapter tests Test files still used old relative paths for vi.mock() and vi.importActual() calls. Updated 5 test files to use package exports. Also broadened regression test patterns to catch mock/importActual paths. * fix: use rm instead of unlink for symlink cleanup, add warn on failure Addresses review feedback from Astro-Han: - rm() handles both symlinks and stale directories (unlink fails on dirs) - Log a warning when symlink creation fails instead of silent catch * docs: update import examples to use package exports Update all documentation, contributing guides, and skills to use @jackwener/opencli/registry instead of ../../src/registry.js. Without this, users following the docs would write adapters with broken imports since the old shim files are no longer created.
137 lines
5.7 KiB
TypeScript
137 lines
5.7 KiB
TypeScript
import { CommandExecutionError } from '@jackwener/opencli/errors';
|
|
import { cli, Strategy } from '@jackwener/opencli/registry';
|
|
|
|
cli({
|
|
site: 'twitter',
|
|
name: 'notifications',
|
|
description: 'Get Twitter/X notifications',
|
|
domain: 'x.com',
|
|
strategy: Strategy.INTERCEPT,
|
|
browser: true,
|
|
args: [
|
|
{ name: 'limit', type: 'int', default: 20 },
|
|
],
|
|
columns: ['id', 'action', 'author', 'text', 'url'],
|
|
func: async (page, kwargs) => {
|
|
// 1. Navigate to home first (we need a loaded Twitter page for SPA navigation)
|
|
await page.goto('https://x.com/home');
|
|
await page.wait(3);
|
|
|
|
// 2. Install interceptor BEFORE SPA navigation
|
|
await page.installInterceptor('NotificationsTimeline');
|
|
|
|
// 3. SPA navigate to notifications via history API
|
|
await page.evaluate(`() => {
|
|
window.history.pushState({}, '', '/notifications');
|
|
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
|
|
}`);
|
|
await page.waitForCapture(5);
|
|
|
|
// Verify SPA navigation succeeded
|
|
const currentUrl = await page.evaluate('() => window.location.pathname');
|
|
if (currentUrl !== '/notifications') {
|
|
throw new CommandExecutionError('SPA navigation to notifications failed. Twitter may have changed its routing.');
|
|
}
|
|
|
|
// 4. Scroll to trigger pagination
|
|
await page.autoScroll({ times: 2, delayMs: 2000 });
|
|
|
|
// 5. Retrieve data
|
|
const requests = await page.getInterceptedRequests();
|
|
if (!requests || requests.length === 0) return [];
|
|
|
|
let results: any[] = [];
|
|
const seen = new Set<string>();
|
|
for (const req of requests) {
|
|
try {
|
|
// GraphQL response: { data: { viewer: ... } } (one level of .data)
|
|
let instructions: any[] = [];
|
|
if (req.data?.viewer?.timeline_response?.timeline?.instructions) {
|
|
instructions = req.data.viewer.timeline_response.timeline.instructions;
|
|
} else if (req.data?.viewer_v2?.user_results?.result?.notification_timeline?.timeline?.instructions) {
|
|
instructions = req.data.viewer_v2.user_results.result.notification_timeline.timeline.instructions;
|
|
} else if (req.data?.timeline?.instructions) {
|
|
instructions = req.data.timeline.instructions;
|
|
}
|
|
|
|
let addEntries = instructions.find((i: any) => i.type === 'TimelineAddEntries');
|
|
if (!addEntries) {
|
|
addEntries = instructions.find((i: any) => i.entries && Array.isArray(i.entries));
|
|
}
|
|
if (!addEntries) continue;
|
|
|
|
for (const entry of addEntries.entries) {
|
|
if (!entry.entryId.startsWith('notification-')) {
|
|
if (entry.content?.items) {
|
|
for (const subItem of entry.content.items) {
|
|
processNotificationItem(subItem.item?.itemContent, subItem.entryId);
|
|
}
|
|
}
|
|
continue;
|
|
}
|
|
|
|
processNotificationItem(entry.content?.itemContent, entry.entryId);
|
|
}
|
|
|
|
function processNotificationItem(itemContent: any, entryId: string) {
|
|
if (!itemContent) return;
|
|
|
|
let item = itemContent?.notification_results?.result || itemContent?.tweet_results?.result || itemContent;
|
|
|
|
let actionText = 'Notification';
|
|
let author = 'unknown';
|
|
let text = '';
|
|
let urlStr = '';
|
|
|
|
if (item.__typename === 'TimelineNotification') {
|
|
text = item.rich_message?.text || item.message?.text || '';
|
|
const fromUser = item.template?.from_users?.[0]?.user_results?.result;
|
|
// Twitter moved screen_name from legacy to core
|
|
author = fromUser?.core?.screen_name || fromUser?.legacy?.screen_name || 'unknown';
|
|
urlStr = item.notification_url?.url || '';
|
|
actionText = item.notification_icon || 'Activity';
|
|
|
|
const targetTweet = item.template?.target_objects?.[0]?.tweet_results?.result;
|
|
if (targetTweet) {
|
|
const targetText = targetTweet.note_tweet?.note_tweet_results?.result?.text || targetTweet.legacy?.full_text || '';
|
|
text += text && targetText ? ' | ' + targetText : targetText;
|
|
if (!urlStr) {
|
|
urlStr = `https://x.com/i/status/${targetTweet.rest_id}`;
|
|
}
|
|
}
|
|
} else if (item.__typename === 'TweetNotification') {
|
|
const tweet = item.tweet_result?.result;
|
|
const tweetUser = tweet?.core?.user_results?.result;
|
|
author = tweetUser?.core?.screen_name || tweetUser?.legacy?.screen_name || 'unknown';
|
|
text = tweet?.note_tweet?.note_tweet_results?.result?.text || tweet?.legacy?.full_text || item.message?.text || '';
|
|
actionText = 'Mention/Reply';
|
|
urlStr = `https://x.com/i/status/${tweet?.rest_id}`;
|
|
} else if (item.__typename === 'Tweet') {
|
|
const tweetUser = item.core?.user_results?.result;
|
|
author = tweetUser?.core?.screen_name || tweetUser?.legacy?.screen_name || 'unknown';
|
|
text = item.note_tweet?.note_tweet_results?.result?.text || item.legacy?.full_text || '';
|
|
actionText = 'Mention';
|
|
urlStr = `https://x.com/i/status/${item.rest_id}`;
|
|
}
|
|
|
|
const id = item.id || item.rest_id || entryId;
|
|
if (seen.has(id)) return;
|
|
seen.add(id);
|
|
|
|
results.push({
|
|
id,
|
|
action: actionText,
|
|
author: author,
|
|
text: text,
|
|
url: urlStr || `https://x.com/notifications`
|
|
});
|
|
}
|
|
} catch (e) {
|
|
// ignore parsing errors for individual payloads
|
|
}
|
|
}
|
|
|
|
return results.slice(0, kwargs.limit);
|
|
}
|
|
});
|