birdclaw 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +10 -8
  3. package/bin/birdclaw.mjs +4 -66
  4. package/dist/cli/birdclaw.js +28165 -0
  5. package/dist/client/assets/AvatarChip-DLoqM5xD.js +1 -0
  6. package/dist/client/assets/ProfilePreview-BejAuYsJ.js +1 -0
  7. package/dist/client/assets/SavedTimelineView-BIS7HKpp.js +1 -0
  8. package/dist/client/assets/SmartTimestamp-BR0-9se2.js +1 -0
  9. package/dist/client/assets/TimelineRouteFrame-CyGPj0eM.js +1 -0
  10. package/dist/client/assets/blocks-7UDKQp8H.js +1 -0
  11. package/dist/client/assets/bookmarks-CbBkMvXk.js +1 -0
  12. package/dist/client/assets/chunk-C0phanGV.js +1 -0
  13. package/dist/client/assets/circle-check-C_Vq3ElD.js +1 -0
  14. package/dist/client/assets/client-stream-contracts-ys3XhWG4.js +5 -0
  15. package/dist/client/assets/createLucideIcon-JV8isFFR.js +1 -0
  16. package/dist/client/assets/data-sources-Cm2bpNvg.js +1 -0
  17. package/dist/client/assets/discuss-DTjaOugw.js +1 -0
  18. package/dist/client/assets/dms-CGd6Eogq.js +1 -0
  19. package/dist/client/assets/inbox-BHlGuOy2.js +1 -0
  20. package/dist/client/assets/index-CEIG7S6s.js +31 -0
  21. package/dist/client/assets/index-bpFrQ5yG.css +1 -0
  22. package/dist/client/assets/likes-cLrcAQem.js +1 -0
  23. package/dist/client/assets/links-CM9QO1LC.js +1 -0
  24. package/dist/client/assets/mapbox-BxTlqXt9.js +2 -0
  25. package/dist/client/assets/mapbox-gl-dgf_hX3a.js +3215 -0
  26. package/dist/client/assets/mentions-CxKCgzIf.js +1 -0
  27. package/dist/client/assets/network-map-B5a3whqj.js +2 -0
  28. package/dist/client/assets/profile-analyze-CRtNEwlb.js +1 -0
  29. package/dist/client/assets/profile-hydration-client-YEtJsNTv.js +1 -0
  30. package/dist/client/assets/profiles._handle-C82_HoKX.js +1 -0
  31. package/dist/client/assets/query-client-fYu2rzRC.js +17 -0
  32. package/dist/client/assets/rate-limits-ScaEwdVK.js +1 -0
  33. package/dist/client/assets/react-dom-DHl6Ug7F.js +1 -0
  34. package/dist/client/assets/react-nBylq1U5.js +1 -0
  35. package/dist/client/assets/repeat-2-xCwHM9hD.js +1 -0
  36. package/dist/client/assets/routes-q7ZaW4En.js +1 -0
  37. package/dist/client/assets/schemas-I9r6F6ya.js +64 -0
  38. package/dist/client/assets/search-Dq5kYsxA.js +1 -0
  39. package/dist/client/assets/sparkles-CQVlvHsZ.js +1 -0
  40. package/dist/client/assets/styles-B8s3tt3r.css +2 -0
  41. package/dist/client/assets/today-CeG1O7Py.js +1 -0
  42. package/dist/client/assets/triangle-alert-CBL7s2pf.js +1 -0
  43. package/dist/client/assets/useTimelineRouteData-1HsqgvUi.js +1 -0
  44. package/dist/client/assets/users-CHbKlqUr.js +1 -0
  45. package/dist/server/assets/AvatarChip-zUDAEmjL.js +105 -0
  46. package/dist/server/assets/FeedState-ntW0Q2GB.js +214 -0
  47. package/dist/server/assets/ProfileAnalysisStream-BFvhVdhn.js +198 -0
  48. package/dist/server/assets/ProfilePreview-C6gAor_j.js +752 -0
  49. package/dist/server/assets/SavedTimelineView-BG1jnBp1.js +64 -0
  50. package/dist/server/assets/SmartTimestamp-DfwE1NGf.js +45 -0
  51. package/dist/server/assets/SyncNowButton-BOn_IBXS.js +76 -0
  52. package/dist/server/assets/TimelineRouteFrame-CU7ilM7U.js +85 -0
  53. package/dist/server/assets/TweetRichText-DhCVv1-6.js +74 -0
  54. package/dist/server/assets/_tanstack-start-manifest_v-C-ZRnG_n.js +148 -0
  55. package/dist/server/assets/account-selection-CTdFGWRk.js +44 -0
  56. package/dist/server/assets/blocks-C1mgGTB3.js +299 -0
  57. package/dist/server/assets/blocks-DSgQghqP.js +17 -0
  58. package/dist/server/assets/bookmarks-BJN8tykY.js +14 -0
  59. package/dist/server/assets/client-stream-contracts-C2xbWVjm.js +769 -0
  60. package/dist/server/assets/data-sources-BnA1Q94p.js +180 -0
  61. package/dist/server/assets/discuss-CJ1dau1j.js +15 -0
  62. package/dist/server/assets/discuss-QTo08NCN.js +338 -0
  63. package/dist/server/assets/dms-BuLj4bp8.js +368 -0
  64. package/dist/server/assets/dms-DAyQrVM2.js +240 -0
  65. package/dist/server/assets/empty-plugin-adapters-DzrEkdBF.js +5 -0
  66. package/dist/server/assets/inbox-CkGOaW1q.js +214 -0
  67. package/dist/server/assets/inbox-DpWd1EzC.js +146 -0
  68. package/dist/server/assets/likes-DBOAtsJU.js +14 -0
  69. package/dist/server/assets/links-DAhSjynu.js +240 -0
  70. package/dist/server/assets/links-DmH5lxHO.js +468 -0
  71. package/dist/server/assets/mentions-BH2MzKtB.js +26 -0
  72. package/dist/server/assets/network-map-D3CzRcC4.js +224 -0
  73. package/dist/server/assets/network-map-D5DoLOwR.js +582 -0
  74. package/dist/server/assets/profile-analyze-BP65PED0.js +90 -0
  75. package/dist/server/assets/profile-analyze-C1NoM0tV.js +9 -0
  76. package/dist/server/assets/profile-hydration-client-GJ4kwJS8.js +133 -0
  77. package/dist/server/assets/profiles._handle-DjwlN_ac.js +184 -0
  78. package/dist/server/assets/profiles._handle-DsLNj2Ca.js +12 -0
  79. package/dist/server/assets/query-client-BdauHBgd.js +923 -0
  80. package/dist/server/assets/rate-limits-VAr2qzYD.js +262 -0
  81. package/dist/server/assets/route-search-BUlQ5lGM.js +117 -0
  82. package/dist/server/assets/router-DqkwSPiM.js +17026 -0
  83. package/dist/server/assets/routes-A9c9ZhwN.js +26 -0
  84. package/dist/server/assets/start-FaDOTmto.js +4 -0
  85. package/dist/server/assets/today-B5hVM57Z.js +17 -0
  86. package/dist/server/assets/today-fvGiZ7ud.js +303 -0
  87. package/dist/server/assets/ui-qbmcMSSX.js +137 -0
  88. package/{src/components/useDebouncedValue.ts → dist/server/assets/useDebouncedValue-DOnA6Xcy.js} +4 -4
  89. package/dist/server/assets/useTimelineRouteData-27cxynxa.js +1101 -0
  90. package/dist/server/server.js +5520 -0
  91. package/package.json +26 -34
  92. package/playwright.config.ts +0 -35
  93. package/scripts/browser-perf.mjs +0 -427
  94. package/scripts/build-docs-site.mjs +0 -967
  95. package/scripts/docs-site-assets.mjs +0 -311
  96. package/scripts/run-vitest.mjs +0 -21
  97. package/scripts/sanitize-node-options.mjs +0 -23
  98. package/scripts/start-test-server.mjs +0 -42
  99. package/src/cli/command-context.ts +0 -17
  100. package/src/cli/register-analysis.ts +0 -500
  101. package/src/cli/register-compose.ts +0 -40
  102. package/src/cli/register-graph.ts +0 -132
  103. package/src/cli/register-inbox.ts +0 -41
  104. package/src/cli/register-storage.ts +0 -106
  105. package/src/cli-moderation.ts +0 -210
  106. package/src/cli.ts +0 -1616
  107. package/src/components/AccountSwitcher.tsx +0 -178
  108. package/src/components/AppNav.tsx +0 -118
  109. package/src/components/AvatarChip.tsx +0 -58
  110. package/src/components/AvatarPreload.ts +0 -149
  111. package/src/components/BrandMark.tsx +0 -67
  112. package/src/components/ConversationThread.tsx +0 -131
  113. package/src/components/DmWorkspace.tsx +0 -286
  114. package/src/components/EmbeddedTweetCard.tsx +0 -55
  115. package/src/components/FeedState.tsx +0 -147
  116. package/src/components/FloatingPreview.tsx +0 -382
  117. package/src/components/InboxCard.tsx +0 -152
  118. package/src/components/LinkPreviewCard.tsx +0 -292
  119. package/src/components/MarkdownCitations.tsx +0 -680
  120. package/src/components/MarkdownViewer.tsx +0 -111
  121. package/src/components/ProfileAnalysisClient.ts +0 -191
  122. package/src/components/ProfileAnalysisStream.tsx +0 -259
  123. package/src/components/ProfilePreview.tsx +0 -131
  124. package/src/components/SavedTimelineView.tsx +0 -155
  125. package/src/components/SmartTimestamp.tsx +0 -72
  126. package/src/components/SyncNowButton.tsx +0 -140
  127. package/src/components/ThemeSlider.tsx +0 -80
  128. package/src/components/TimelineCard.tsx +0 -533
  129. package/src/components/TimelineRouteFrame.tsx +0 -186
  130. package/src/components/TweetArticleCard.tsx +0 -66
  131. package/src/components/TweetMediaGrid.tsx +0 -185
  132. package/src/components/TweetRichText.tsx +0 -159
  133. package/src/components/account-selection.ts +0 -64
  134. package/src/components/links-controller.ts +0 -162
  135. package/src/components/links-model.ts +0 -198
  136. package/src/components/network-map-controller.ts +0 -84
  137. package/src/components/network-map-model.ts +0 -255
  138. package/src/components/useTimelineRouteData.ts +0 -193
  139. package/src/lib/account-sync-job.ts +0 -666
  140. package/src/lib/actions-transport.ts +0 -300
  141. package/src/lib/analysis-runtime.ts +0 -238
  142. package/src/lib/api-client.ts +0 -220
  143. package/src/lib/api-contracts.ts +0 -328
  144. package/src/lib/archive-finder.ts +0 -185
  145. package/src/lib/archive-import-plan.ts +0 -102
  146. package/src/lib/archive-import.ts +0 -2695
  147. package/src/lib/authored-live.ts +0 -1027
  148. package/src/lib/avatar-cache.ts +0 -349
  149. package/src/lib/backup.ts +0 -2652
  150. package/src/lib/bird-actions.ts +0 -294
  151. package/src/lib/bird-command.ts +0 -130
  152. package/src/lib/bird.ts +0 -1140
  153. package/src/lib/blocklist.ts +0 -136
  154. package/src/lib/blocks-write.ts +0 -171
  155. package/src/lib/blocks.ts +0 -387
  156. package/src/lib/bookmark-sync-job.ts +0 -536
  157. package/src/lib/config.ts +0 -224
  158. package/src/lib/conversation-surface.ts +0 -205
  159. package/src/lib/data-sources.ts +0 -219
  160. package/src/lib/database-metrics.ts +0 -88
  161. package/src/lib/database-migrations.ts +0 -34
  162. package/src/lib/database-schema.ts +0 -312
  163. package/src/lib/database-writer.ts +0 -69
  164. package/src/lib/db.ts +0 -889
  165. package/src/lib/dm-read-model.ts +0 -533
  166. package/src/lib/dms-live.ts +0 -870
  167. package/src/lib/effect-runtime.ts +0 -45
  168. package/src/lib/follow-graph.ts +0 -1087
  169. package/src/lib/geocoding.ts +0 -296
  170. package/src/lib/http-effect.ts +0 -222
  171. package/src/lib/identity-search-index.ts +0 -369
  172. package/src/lib/import-repository.ts +0 -138
  173. package/src/lib/inbox.ts +0 -242
  174. package/src/lib/link-index.ts +0 -641
  175. package/src/lib/link-insights.ts +0 -860
  176. package/src/lib/link-preview-metadata.ts +0 -754
  177. package/src/lib/live-sync-engine.ts +0 -209
  178. package/src/lib/live-transport-gateway.ts +0 -128
  179. package/src/lib/location.ts +0 -137
  180. package/src/lib/media-fetch.ts +0 -860
  181. package/src/lib/media-includes.ts +0 -165
  182. package/src/lib/mention-threads-live.ts +0 -830
  183. package/src/lib/mentions-export.ts +0 -147
  184. package/src/lib/mentions-live.ts +0 -1114
  185. package/src/lib/moderation-target.ts +0 -227
  186. package/src/lib/moderation-write.ts +0 -131
  187. package/src/lib/mutes-write.ts +0 -171
  188. package/src/lib/mutes.ts +0 -84
  189. package/src/lib/ndjson-stream.ts +0 -106
  190. package/src/lib/network-map.ts +0 -382
  191. package/src/lib/openai-response-runtime.ts +0 -251
  192. package/src/lib/openai.ts +0 -117
  193. package/src/lib/paginated-sync.ts +0 -93
  194. package/src/lib/period-digest.ts +0 -1364
  195. package/src/lib/present.ts +0 -118
  196. package/src/lib/profile-affiliation-hydration.ts +0 -228
  197. package/src/lib/profile-affiliations.ts +0 -262
  198. package/src/lib/profile-analysis.ts +0 -1198
  199. package/src/lib/profile-bio-entities.ts +0 -318
  200. package/src/lib/profile-history.ts +0 -164
  201. package/src/lib/profile-hydration.ts +0 -180
  202. package/src/lib/profile-replies.ts +0 -77
  203. package/src/lib/profile-resolver.ts +0 -650
  204. package/src/lib/queries.ts +0 -6
  205. package/src/lib/query-actions.ts +0 -437
  206. package/src/lib/query-client.tsx +0 -47
  207. package/src/lib/query-read-model-shared.ts +0 -52
  208. package/src/lib/query-read-models.ts +0 -5
  209. package/src/lib/query-resource.ts +0 -41
  210. package/src/lib/query-status.ts +0 -164
  211. package/src/lib/research.ts +0 -652
  212. package/src/lib/runtime-services.ts +0 -20
  213. package/src/lib/search-discussion.ts +0 -812
  214. package/src/lib/seed.ts +0 -613
  215. package/src/lib/server-runtime-services.ts +0 -30
  216. package/src/lib/sqlite.ts +0 -183
  217. package/src/lib/streaming-ingestion.ts +0 -240
  218. package/src/lib/sync-cache.ts +0 -70
  219. package/src/lib/sync-plan.ts +0 -175
  220. package/src/lib/theme-transition.ts +0 -113
  221. package/src/lib/theme.tsx +0 -165
  222. package/src/lib/timeline-collections-live.ts +0 -407
  223. package/src/lib/timeline-live.ts +0 -302
  224. package/src/lib/timeline-read-model.ts +0 -1191
  225. package/src/lib/tweet-account-edges.ts +0 -48
  226. package/src/lib/tweet-lookup.ts +0 -46
  227. package/src/lib/tweet-render.ts +0 -430
  228. package/src/lib/tweet-repository.ts +0 -156
  229. package/src/lib/tweet-search-live.ts +0 -462
  230. package/src/lib/types.ts +0 -723
  231. package/src/lib/ui.ts +0 -529
  232. package/src/lib/url-expansion-store.ts +0 -110
  233. package/src/lib/url-expansion.ts +0 -343
  234. package/src/lib/url-safety.ts +0 -220
  235. package/src/lib/web-sync.ts +0 -533
  236. package/src/lib/whois.ts +0 -1080
  237. package/src/lib/x-profile.ts +0 -365
  238. package/src/lib/x-web.ts +0 -199
  239. package/src/lib/xurl-rate-limits.ts +0 -267
  240. package/src/lib/xurl.ts +0 -1677
  241. package/src/routeTree.gen.ts +0 -723
  242. package/src/router.tsx +0 -20
  243. package/src/routes/__root.tsx +0 -82
  244. package/src/routes/api/action.tsx +0 -147
  245. package/src/routes/api/avatar.tsx +0 -50
  246. package/src/routes/api/blocks.tsx +0 -35
  247. package/src/routes/api/conversation.tsx +0 -45
  248. package/src/routes/api/data-sources.tsx +0 -24
  249. package/src/routes/api/inbox.tsx +0 -43
  250. package/src/routes/api/link-insights.tsx +0 -85
  251. package/src/routes/api/link-preview.tsx +0 -47
  252. package/src/routes/api/network-map.tsx +0 -55
  253. package/src/routes/api/period-digest.tsx +0 -101
  254. package/src/routes/api/profile-analysis.tsx +0 -97
  255. package/src/routes/api/profile-hydrate.tsx +0 -54
  256. package/src/routes/api/query.tsx +0 -121
  257. package/src/routes/api/search-discussion.tsx +0 -113
  258. package/src/routes/api/status.tsx +0 -30
  259. package/src/routes/api/sync.tsx +0 -108
  260. package/src/routes/api/xurl-rate-limits.tsx +0 -24
  261. package/src/routes/blocks.tsx +0 -343
  262. package/src/routes/bookmarks.tsx +0 -18
  263. package/src/routes/data-sources.tsx +0 -249
  264. package/src/routes/discuss.tsx +0 -419
  265. package/src/routes/dms.tsx +0 -415
  266. package/src/routes/inbox.tsx +0 -232
  267. package/src/routes/index.tsx +0 -32
  268. package/src/routes/likes.tsx +0 -18
  269. package/src/routes/links.tsx +0 -631
  270. package/src/routes/mentions.tsx +0 -32
  271. package/src/routes/network-map.tsx +0 -732
  272. package/src/routes/profile-analyze.tsx +0 -112
  273. package/src/routes/profiles.$handle.tsx +0 -228
  274. package/src/routes/rate-limits.tsx +0 -305
  275. package/src/routes/today.tsx +0 -511
  276. package/src/styles.css +0 -257
  277. package/tsconfig.json +0 -29
  278. package/vite.config.ts +0 -29
  279. /package/{public → dist/client}/birdclaw-mark.png +0 -0
  280. /package/{public → dist/client}/favicon.ico +0 -0
  281. /package/{public → dist/client}/logo192.png +0 -0
  282. /package/{public → dist/client}/logo512.png +0 -0
  283. /package/{public → dist/client}/manifest.json +0 -0
  284. /package/{public → dist/client}/robots.txt +0 -0
package/src/lib/xurl.ts DELETED
@@ -1,1677 +0,0 @@
1
- import { execFile } from "node:child_process";
2
- import { promisify } from "node:util";
3
- import { Effect } from "effect";
4
- import { runEffectPromise } from "./effect-runtime";
5
- import type {
6
- FollowDirection,
7
- LiveDataSourceAccount,
8
- TransportStatus,
9
- XurlDmEventsResponse,
10
- XurlFollowUsersResponse,
11
- XurlMentionsResponse,
12
- XurlMentionUser,
13
- XurlTweetsResponse,
14
- XurlUserTweet,
15
- XurlUserTweetsResponse,
16
- } from "./types";
17
-
18
- const execFileAsync = promisify(execFile);
19
- const TRANSPORT_STATUS_TTL_MS = 5 * 60_000;
20
- const AUTHENTICATED_USER_TTL_MS = 60_000;
21
- const JSON_RETRY_LIMIT = 6;
22
- const MEDIA_EXPANSION = "attachments.media_keys";
23
- const AUTHOR_MEDIA_EXPANSIONS = `author_id,${MEDIA_EXPANSION}`;
24
- const MEDIA_FIELDS =
25
- "variants,preview_image_url,url,duration_ms,alt_text,type,width,height,public_metrics";
26
- const RICH_USER_FIELDS =
27
- "description,entities,location,public_metrics,profile_image_url,url,created_at,verified,verified_type";
28
- const DM_EVENT_FIELDS =
29
- "attachments,created_at,dm_conversation_id,entities,event_type,id,participant_ids,referenced_tweets,sender_id,text";
30
- const THREAD_TWEET_FIELDS =
31
- "created_at,conversation_id,entities,public_metrics,referenced_tweets,in_reply_to_user_id,attachments";
32
- // X bookmarks pagination truncates above 90 until this bug is fixed:
33
- // https://devcommunity.x.com/t/bookmarks-api-v2-stops-paginating-after-3-pages-no-next-token-returned/257339
34
- const BOOKMARKS_MAX_RESULTS_CAP = 90;
35
-
36
- type TimelineCollectionEndpoint = "liked_tweets" | "bookmarks";
37
- type JsonCommandOptions = {
38
- timeoutMs?: number;
39
- deadlineMs?: number;
40
- signal?: AbortSignal;
41
- onAttempt?: (attempt: XurlJsonCommandAttempt) => void;
42
- };
43
- export interface XurlJsonCommandAttempt {
44
- args: readonly string[];
45
- attempt: number;
46
- status: "ok" | "rate_limited" | "error";
47
- error?: Error;
48
- }
49
- type OAuth2UsernameCandidate = {
50
- app?: string;
51
- username?: string;
52
- };
53
-
54
- let transportStatusCache:
55
- | {
56
- expiresAt: number;
57
- pending?: Promise<TransportStatus>;
58
- value?: TransportStatus;
59
- }
60
- | undefined;
61
- let authenticatedUserCache:
62
- | {
63
- expiresAt: number;
64
- pending?: Promise<Record<string, unknown> | null>;
65
- value?: Record<string, unknown> | null;
66
- }
67
- | undefined;
68
- const oauth2CandidateCache = new Map<
69
- string,
70
- { expiresAt: number; value: OAuth2UsernameCandidate }
71
- >();
72
-
73
- function liveWritesDisabled() {
74
- return process.env.BIRDCLAW_DISABLE_LIVE_WRITES === "1";
75
- }
76
-
77
- function e2eFakeLiveWritesEnabled() {
78
- return (
79
- process.env.BIRDCLAW_E2E === "1" &&
80
- process.env.BIRDCLAW_E2E_FAKE_LIVE_WRITES === "1"
81
- );
82
- }
83
-
84
- function getJsonRetryBaseDelayMs() {
85
- const value = Number(process.env.BIRDCLAW_XURL_RETRY_BASE_MS ?? "2000");
86
- return Number.isFinite(value) && value >= 0 ? value : 2000;
87
- }
88
-
89
- function stripAnsi(value: string) {
90
- // ANSI escape parsing needs a constructor to avoid literal control characters.
91
- return value.replace(new RegExp("\\u001b\\[[0-9;]*m", "g"), "");
92
- }
93
-
94
- function formatExecError(error: unknown, fallback: string) {
95
- if (!(error instanceof Error)) {
96
- return fallback;
97
- }
98
-
99
- const parts = [error.message];
100
- if (
101
- "stdout" in error &&
102
- typeof error.stdout === "string" &&
103
- error.stdout.trim().length > 0
104
- ) {
105
- parts.push(stripAnsi(error.stdout).trim());
106
- }
107
- if (
108
- "stderr" in error &&
109
- typeof error.stderr === "string" &&
110
- error.stderr.trim().length > 0
111
- ) {
112
- parts.push(stripAnsi(error.stderr).trim());
113
- }
114
-
115
- return parts.join("\n");
116
- }
117
-
118
- function formatXurlCommandError(error: unknown, args: string[]) {
119
- return new Error(formatExecError(error, `xurl ${args.join(" ")} failed`));
120
- }
121
-
122
- function normalizeError(error: unknown) {
123
- return error instanceof Error ? error : new Error(String(error));
124
- }
125
-
126
- function parseErrorPayload(error: unknown) {
127
- const stdout =
128
- typeof error === "object" &&
129
- error !== null &&
130
- "stdout" in error &&
131
- typeof error.stdout === "string"
132
- ? stripAnsi(error.stdout)
133
- : "";
134
-
135
- const start = stdout.indexOf("{");
136
- const end = stdout.lastIndexOf("}");
137
- if (start < 0 || end <= start) {
138
- return null;
139
- }
140
-
141
- try {
142
- return JSON.parse(stdout.slice(start, end + 1)) as Record<string, unknown>;
143
- } catch {
144
- return null;
145
- }
146
- }
147
-
148
- function getRetryDelayMs(error: unknown, attempt: number) {
149
- const payload = parseErrorPayload(error);
150
- const status = Number(payload?.status ?? 0);
151
- if (status !== 429) {
152
- return null;
153
- }
154
-
155
- const baseDelay = getJsonRetryBaseDelayMs();
156
- return Math.min(baseDelay * 2 ** attempt, 30_000);
157
- }
158
-
159
- function emitJsonCommandAttempt(
160
- options: JsonCommandOptions,
161
- attempt: XurlJsonCommandAttempt,
162
- ) {
163
- try {
164
- options.onAttempt?.(attempt);
165
- } catch {
166
- // Telemetry observers must not affect xurl command behavior.
167
- }
168
- }
169
-
170
- function capTimelineCollectionMaxResults(
171
- collection: TimelineCollectionEndpoint,
172
- maxResults: number,
173
- isPaginatedWalk: boolean,
174
- ) {
175
- return collection === "bookmarks" && isPaginatedWalk
176
- ? Math.min(maxResults, BOOKMARKS_MAX_RESULTS_CAP)
177
- : maxResults;
178
- }
179
-
180
- export function resetTransportStatusCache() {
181
- transportStatusCache = undefined;
182
- }
183
-
184
- export function resetAuthenticatedUserCache() {
185
- authenticatedUserCache = undefined;
186
- oauth2CandidateCache.clear();
187
- }
188
-
189
- function hasXurlEffect() {
190
- return Effect.tryPromise({
191
- try: () => execFileAsync("xurl", ["version"]),
192
- catch: normalizeError,
193
- }).pipe(
194
- Effect.as(true),
195
- Effect.catchAll(() => Effect.succeed(false)),
196
- );
197
- }
198
-
199
- function isUnauthenticatedXurlStatus(status: string) {
200
- return /no apps registered|no authenticated user|not authenticated|not logged in/i.test(
201
- status,
202
- );
203
- }
204
-
205
- function readTransportStatusEffect(): Effect.Effect<TransportStatus, never> {
206
- return Effect.gen(function* () {
207
- const installed = yield* hasXurlEffect();
208
- if (!installed) {
209
- return {
210
- installed: false,
211
- availableTransport: "local" as const,
212
- statusText: "xurl not installed. local mode active.",
213
- };
214
- }
215
-
216
- return yield* Effect.tryPromise({
217
- try: () => execFileAsync("xurl", ["auth", "status"]),
218
- catch: (cause) => cause,
219
- }).pipe(
220
- Effect.map(({ stdout }) => {
221
- const rawStatus = stdout.trim();
222
-
223
- if (isUnauthenticatedXurlStatus(rawStatus)) {
224
- return {
225
- installed: true,
226
- availableTransport: "local" as const,
227
- statusText:
228
- "xurl installed but not authenticated. local (bird) mode active.",
229
- rawStatus,
230
- };
231
- }
232
-
233
- return {
234
- installed: true,
235
- availableTransport: "xurl" as const,
236
- statusText: "xurl available",
237
- rawStatus,
238
- };
239
- }),
240
- Effect.catchAll((error) =>
241
- Effect.succeed({
242
- installed: true,
243
- availableTransport: "local" as const,
244
- statusText: `xurl detected but auth unavailable: ${
245
- error instanceof Error ? error.message : "unknown error"
246
- }`,
247
- }),
248
- ),
249
- );
250
- });
251
- }
252
-
253
- export function getTransportStatusEffect() {
254
- return Effect.gen(function* () {
255
- const now = Date.now();
256
- if (transportStatusCache?.value && transportStatusCache.expiresAt > now) {
257
- return transportStatusCache.value;
258
- }
259
-
260
- if (transportStatusCache?.pending) {
261
- const status = yield* Effect.tryPromise({
262
- try: () => transportStatusCache?.pending ?? Promise.resolve(undefined),
263
- catch: normalizeError,
264
- });
265
- if (status) return status;
266
- }
267
-
268
- const pending = runEffectPromise(readTransportStatusEffect());
269
-
270
- transportStatusCache = {
271
- expiresAt: 0,
272
- pending,
273
- };
274
-
275
- const status = yield* Effect.tryPromise({
276
- try: () => pending,
277
- catch: normalizeError,
278
- }).pipe(
279
- Effect.catchAll((error) =>
280
- Effect.sync(() => {
281
- transportStatusCache = undefined;
282
- }).pipe(Effect.flatMap(() => Effect.fail(error))),
283
- ),
284
- );
285
- transportStatusCache = {
286
- expiresAt: Date.now() + TRANSPORT_STATUS_TTL_MS,
287
- value: status,
288
- };
289
- return status;
290
- });
291
- }
292
-
293
- export function getTransportStatus(): Promise<TransportStatus> {
294
- return runEffectPromise(getTransportStatusEffect());
295
- }
296
-
297
- function runShortcutEffect(args: string[]) {
298
- return Effect.gen(function* () {
299
- if (liveWritesDisabled()) {
300
- if (e2eFakeLiveWritesEnabled()) {
301
- return { ok: true, output: "e2e fake live write" };
302
- }
303
- return { ok: false, output: "live writes disabled" };
304
- }
305
-
306
- return yield* Effect.tryPromise({
307
- try: () => execFileAsync("xurl", args),
308
- catch: normalizeError,
309
- }).pipe(
310
- Effect.map(({ stdout, stderr }) => ({
311
- ok: true,
312
- output: stdout || stderr,
313
- })),
314
- Effect.catchAll((error) =>
315
- Effect.succeed({
316
- ok: false,
317
- output: formatExecError(error, "xurl execution failed"),
318
- }),
319
- ),
320
- );
321
- });
322
- }
323
-
324
- function execXurlJsonEffect(
325
- args: string[],
326
- timeoutMs?: number,
327
- signal?: AbortSignal,
328
- ): Effect.Effect<{ stdout: string; stderr: string }, Error> {
329
- return Effect.tryPromise({
330
- try: () => {
331
- const controller =
332
- (typeof timeoutMs === "number" &&
333
- Number.isFinite(timeoutMs) &&
334
- timeoutMs > 0) ||
335
- signal
336
- ? new AbortController()
337
- : undefined;
338
- if (
339
- typeof timeoutMs === "number" &&
340
- Number.isFinite(timeoutMs) &&
341
- timeoutMs <= 0
342
- ) {
343
- throw new Error("xurl command timed out");
344
- }
345
- if (signal?.aborted) {
346
- throw new Error("xurl command aborted");
347
- }
348
- const onAbort = () => controller?.abort();
349
- signal?.addEventListener("abort", onAbort, { once: true });
350
- const timeout =
351
- controller &&
352
- typeof timeoutMs === "number" &&
353
- Number.isFinite(timeoutMs) &&
354
- timeoutMs > 0
355
- ? setTimeout(() => controller.abort(), timeoutMs)
356
- : undefined;
357
- const result = controller
358
- ? execFileAsync("xurl", args, { signal: controller.signal })
359
- : execFileAsync("xurl", args);
360
- return result.finally(() => {
361
- signal?.removeEventListener("abort", onAbort);
362
- if (timeout) {
363
- clearTimeout(timeout);
364
- }
365
- });
366
- },
367
- catch: normalizeError,
368
- });
369
- }
370
-
371
- function getRemainingTimeoutMs(deadlineMs?: number) {
372
- if (deadlineMs === undefined) return undefined;
373
- const timeoutMs = Math.max(0, deadlineMs - Date.now());
374
- if (timeoutMs <= 0) {
375
- throw new Error("xurl OAuth2 fallback timed out");
376
- }
377
- return timeoutMs;
378
- }
379
-
380
- function execXurlTextEffect(
381
- args: string[],
382
- deadlineMs?: number,
383
- ): Effect.Effect<{ stdout: string; stderr: string }, Error> {
384
- return Effect.tryPromise({
385
- try: () => {
386
- const timeoutMs = getRemainingTimeoutMs(deadlineMs);
387
- const controller =
388
- typeof timeoutMs === "number" &&
389
- Number.isFinite(timeoutMs) &&
390
- timeoutMs > 0
391
- ? new AbortController()
392
- : undefined;
393
- const timeout = controller
394
- ? setTimeout(() => controller.abort(), timeoutMs)
395
- : undefined;
396
- const result = controller
397
- ? execFileAsync("xurl", args, { signal: controller.signal })
398
- : execFileAsync("xurl", args);
399
- return result.finally(() => {
400
- if (timeout) {
401
- clearTimeout(timeout);
402
- }
403
- });
404
- },
405
- catch: normalizeError,
406
- });
407
- }
408
-
409
- function parseJsonPayloadEffect(
410
- stdout: string,
411
- args: string[],
412
- ): Effect.Effect<Record<string, unknown>, Error> {
413
- return Effect.try({
414
- try: () => JSON.parse(stdout) as Record<string, unknown>,
415
- catch: (error) => formatXurlCommandError(error, args),
416
- });
417
- }
418
-
419
- function runJsonCommandEffect(
420
- args: string[],
421
- options: JsonCommandOptions = {},
422
- attempt = 0,
423
- ): Effect.Effect<Record<string, unknown>, Error> {
424
- return Effect.gen(function* () {
425
- const deadlineMs =
426
- options.deadlineMs ??
427
- (typeof options.timeoutMs === "number" &&
428
- Number.isFinite(options.timeoutMs) &&
429
- options.timeoutMs > 0
430
- ? Date.now() + options.timeoutMs
431
- : undefined);
432
- const timeoutMs = deadlineMs
433
- ? Math.max(0, deadlineMs - Date.now())
434
- : undefined;
435
- return yield* execXurlJsonEffect(args, timeoutMs, options.signal).pipe(
436
- Effect.flatMap(({ stdout }) => parseJsonPayloadEffect(stdout, args)),
437
- Effect.tap(() =>
438
- Effect.sync(() =>
439
- emitJsonCommandAttempt(options, { args, attempt, status: "ok" }),
440
- ),
441
- ),
442
- Effect.catchAll((error) => {
443
- const retryDelayMs = getRetryDelayMs(error, attempt);
444
- emitJsonCommandAttempt(options, {
445
- args,
446
- attempt,
447
- status: retryDelayMs === null ? "error" : "rate_limited",
448
- error,
449
- });
450
- if (retryDelayMs === null || attempt >= JSON_RETRY_LIMIT - 1) {
451
- return Effect.fail(formatXurlCommandError(error, args));
452
- }
453
- if (options.signal?.aborted) {
454
- return Effect.fail(formatXurlCommandError(error, args));
455
- }
456
- const remainingMs = deadlineMs
457
- ? Math.max(0, deadlineMs - Date.now())
458
- : undefined;
459
- if (remainingMs !== undefined && retryDelayMs >= remainingMs) {
460
- return Effect.fail(formatXurlCommandError(error, args));
461
- }
462
-
463
- return Effect.sleep(retryDelayMs).pipe(
464
- Effect.flatMap(() =>
465
- runJsonCommandEffect(args, { ...options, deadlineMs }, attempt + 1),
466
- ),
467
- );
468
- }),
469
- );
470
- });
471
- }
472
-
473
- function cleanXurlUsernameLabel(username?: string) {
474
- const label = username?.trim().replace(/^@/, "");
475
- return label &&
476
- label !== "-" &&
477
- label !== "–" &&
478
- label !== "(none)" &&
479
- label.toLowerCase() !== "none" &&
480
- label.toLowerCase() !== "unknown" &&
481
- /^[^\s]{1,128}$/.test(label)
482
- ? label
483
- : undefined;
484
- }
485
-
486
- function comparableXurlUsername(username?: string) {
487
- return cleanXurlUsernameLabel(username)?.toLowerCase();
488
- }
489
-
490
- function cleanXurlAppLabel(app?: string) {
491
- const label = app?.trim();
492
- return label && /^[^\s]{1,128}$/.test(label) ? label : undefined;
493
- }
494
-
495
- function parseOAuth2UsernamesFromStatus(rawStatus: string) {
496
- const seen = new Set<string>();
497
- const usernames: OAuth2UsernameCandidate[] = [];
498
- let currentApp: string | undefined;
499
- for (const line of rawStatus.split(/\r?\n/)) {
500
- const appMatch = line.match(/^\s*(?:▸\s*)?([^\s]+)\s+\[client_id:/);
501
- if (appMatch) {
502
- currentApp = cleanXurlAppLabel(appMatch[1]);
503
- continue;
504
- }
505
- const oauthMatch = line.match(/\boauth2:\s*([^\s]+)/);
506
- if (oauthMatch) {
507
- const username = cleanXurlUsernameLabel(oauthMatch[1]);
508
- const key = username
509
- ? `${currentApp ?? "default"}:${username}`
510
- : undefined;
511
- if (username && key && !seen.has(key)) {
512
- seen.add(key);
513
- usernames.push({ app: currentApp, username });
514
- }
515
- }
516
- }
517
- return usernames;
518
- }
519
-
520
- function readOAuth2UsernameCandidatesEffect(
521
- deadlineMs?: number,
522
- ): Effect.Effect<OAuth2UsernameCandidate[], never> {
523
- return execXurlTextEffect(["auth", "status"], deadlineMs).pipe(
524
- Effect.map(({ stdout }) => parseOAuth2UsernamesFromStatus(stdout)),
525
- Effect.catchAll(() => Effect.succeed([])),
526
- );
527
- }
528
-
529
- export function readXurlOAuth2AccountsEffect(): Effect.Effect<
530
- LiveDataSourceAccount[],
531
- never
532
- > {
533
- return readOAuth2UsernameCandidatesEffect().pipe(
534
- Effect.map((candidates) =>
535
- candidates.map((candidate) => ({
536
- ...(candidate.app ? { app: candidate.app } : {}),
537
- ...(candidate.username ? { username: candidate.username } : {}),
538
- })),
539
- ),
540
- );
541
- }
542
-
543
- export function readXurlOAuth2Accounts(): Promise<LiveDataSourceAccount[]> {
544
- return runEffectPromise(readXurlOAuth2AccountsEffect());
545
- }
546
-
547
- function lookupOAuth2UsernameForAccountEffect(
548
- expectedUsername: string,
549
- attemptedUsernames: Set<string>,
550
- deadlineMs?: number,
551
- knownCandidates?: OAuth2UsernameCandidate[],
552
- ) {
553
- return Effect.gen(function* () {
554
- const expected = comparableXurlUsername(expectedUsername);
555
- if (!expected) return undefined;
556
-
557
- const candidates =
558
- knownCandidates ??
559
- (yield* readOAuth2UsernameCandidatesEffect(deadlineMs));
560
- for (const candidate of candidates) {
561
- const candidateKey = `${candidate.app ?? "default"}:${candidate.username}`;
562
- if (attemptedUsernames.has(candidateKey)) continue;
563
- const payload = yield* runJsonCommandEffect(
564
- oauth2ArgsForCandidate(candidate, ["/2/users/me"]),
565
- { deadlineMs },
566
- ).pipe(Effect.catchAll(() => Effect.succeed(null)));
567
- const user = payload ? authenticatedUserFromPayload(payload) : null;
568
- const actual = comparableXurlUsername(String(user?.username ?? ""));
569
- if (actual === expected) {
570
- return candidate;
571
- }
572
- }
573
-
574
- return undefined;
575
- });
576
- }
577
-
578
- function oauth2ArgsForCandidate(
579
- candidate: OAuth2UsernameCandidate | undefined,
580
- args: string[],
581
- ) {
582
- return [
583
- ...(candidate?.app ? ["--app", candidate.app] : []),
584
- "--auth",
585
- "oauth2",
586
- ...(candidate?.username ? ["--username", candidate.username] : []),
587
- ...args,
588
- ];
589
- }
590
-
591
- function configuredOAuth2Candidate(primaryUsername: string | undefined) {
592
- const app = cleanXurlAppLabel(process.env.BIRDCLAW_XURL_OAUTH2_APP);
593
- const username = cleanXurlUsernameLabel(
594
- process.env.BIRDCLAW_XURL_OAUTH2_USERNAME,
595
- );
596
- if (!app && !username) return undefined;
597
- const effectiveUsername = username ?? primaryUsername;
598
- if (!app && !effectiveUsername) return undefined;
599
- return {
600
- ...(app ? { app } : {}),
601
- ...(effectiveUsername ? { username: effectiveUsername } : {}),
602
- };
603
- }
604
-
605
- function runOAuth2JsonCommandEffect({
606
- args,
607
- username,
608
- options,
609
- useConfiguredCandidate = true,
610
- }: {
611
- args: string[];
612
- username?: string;
613
- options?: JsonCommandOptions;
614
- useConfiguredCandidate?: boolean;
615
- }) {
616
- const primaryUsername = cleanXurlUsernameLabel(username);
617
- return Effect.gen(function* () {
618
- const deadlineMs =
619
- options?.deadlineMs ??
620
- (typeof options?.timeoutMs === "number" &&
621
- Number.isFinite(options.timeoutMs) &&
622
- options.timeoutMs > 0
623
- ? Date.now() + options.timeoutMs
624
- : undefined);
625
- const scopedOptions = { ...options, deadlineMs };
626
- let authCandidate: OAuth2UsernameCandidate | undefined = primaryUsername
627
- ? { username: primaryUsername }
628
- : undefined;
629
- const configuredCandidate = useConfiguredCandidate
630
- ? configuredOAuth2Candidate(primaryUsername)
631
- : undefined;
632
- if (configuredCandidate) {
633
- authCandidate = configuredCandidate;
634
- } else if (primaryUsername) {
635
- const cacheKey = primaryUsername.toLowerCase();
636
- const cachedCandidate = oauth2CandidateCache.get(cacheKey);
637
- if (cachedCandidate && cachedCandidate.expiresAt > Date.now()) {
638
- authCandidate = cachedCandidate.value;
639
- } else {
640
- const candidates =
641
- yield* readOAuth2UsernameCandidatesEffect(deadlineMs);
642
- const primaryCandidates = candidates.filter(
643
- (candidate) => candidate.username === primaryUsername,
644
- );
645
- if (primaryCandidates.length === 1) {
646
- authCandidate = primaryCandidates[0];
647
- } else if (primaryCandidates.length > 1) {
648
- const verifiedUsername = yield* lookupOAuth2UsernameForAccountEffect(
649
- primaryUsername,
650
- new Set(),
651
- deadlineMs,
652
- candidates,
653
- );
654
- authCandidate = verifiedUsername ??
655
- primaryCandidates[0] ?? { username: primaryUsername };
656
- } else {
657
- const fallbackUsername = yield* lookupOAuth2UsernameForAccountEffect(
658
- primaryUsername,
659
- new Set(),
660
- deadlineMs,
661
- candidates,
662
- );
663
- if (fallbackUsername) {
664
- authCandidate = fallbackUsername;
665
- }
666
- }
667
- if (authCandidate) {
668
- oauth2CandidateCache.set(cacheKey, {
669
- expiresAt: Date.now() + AUTHENTICATED_USER_TTL_MS,
670
- value: authCandidate,
671
- });
672
- }
673
- }
674
- }
675
-
676
- if (deadlineMs !== undefined && Date.now() >= deadlineMs) {
677
- return yield* Effect.fail(new Error("xurl OAuth2 fallback timed out"));
678
- }
679
-
680
- return yield* runJsonCommandEffect(
681
- oauth2ArgsForCandidate(authCandidate, args),
682
- scopedOptions,
683
- ).pipe(
684
- Effect.catchAll((error) => {
685
- if (!primaryUsername) {
686
- return Effect.fail(error);
687
- }
688
- oauth2CandidateCache.delete(primaryUsername.toLowerCase());
689
- const attempted = new Set([
690
- authCandidate
691
- ? `${authCandidate.app ?? "default"}:${authCandidate.username}`
692
- : `default:${primaryUsername}`,
693
- ]);
694
- if (authCandidate?.username !== primaryUsername) {
695
- attempted.add(`default:${primaryUsername}`);
696
- }
697
- return lookupOAuth2UsernameForAccountEffect(
698
- primaryUsername,
699
- attempted,
700
- deadlineMs,
701
- ).pipe(
702
- Effect.flatMap((fallbackUsername) => {
703
- if (!fallbackUsername) {
704
- return Effect.fail(error);
705
- }
706
- oauth2CandidateCache.set(primaryUsername.toLowerCase(), {
707
- expiresAt: Date.now() + AUTHENTICATED_USER_TTL_MS,
708
- value: fallbackUsername,
709
- });
710
- return runJsonCommandEffect(
711
- oauth2ArgsForCandidate(fallbackUsername, args),
712
- scopedOptions,
713
- );
714
- }),
715
- Effect.catchAll(() => Effect.fail(error)),
716
- );
717
- }),
718
- );
719
- });
720
- }
721
-
722
- function runMutationCommandEffect(args: string[]) {
723
- return Effect.gen(function* () {
724
- if (liveWritesDisabled()) {
725
- if (e2eFakeLiveWritesEnabled()) {
726
- return { ok: true, output: "e2e fake live write" };
727
- }
728
- return { ok: false, output: "live writes disabled" };
729
- }
730
-
731
- return yield* Effect.tryPromise({
732
- try: () => execFileAsync("xurl", args),
733
- catch: normalizeError,
734
- }).pipe(
735
- Effect.map(({ stdout, stderr }) => ({
736
- ok: true,
737
- output: stdout || stderr || "ok",
738
- })),
739
- Effect.catchAll((error) =>
740
- Effect.succeed({
741
- ok: false,
742
- output: formatExecError(error, "xurl execution failed"),
743
- }),
744
- ),
745
- );
746
- });
747
- }
748
-
749
- export function lookupUsersByIdsEffect(ids: string[]) {
750
- if (ids.length === 0) {
751
- return Effect.succeed([]);
752
- }
753
-
754
- const query = new URLSearchParams({
755
- ids: ids.join(","),
756
- "user.fields":
757
- "description,entities,location,public_metrics,profile_image_url,url,created_at,verified,verified_type",
758
- });
759
- return runJsonCommandEffect([`/2/users?${query.toString()}`]).pipe(
760
- Effect.map((payload) =>
761
- Array.isArray(payload.data) ? (payload.data as XurlMentionUser[]) : [],
762
- ),
763
- );
764
- }
765
-
766
- export function lookupUsersByIds(ids: string[]) {
767
- return runEffectPromise(lookupUsersByIdsEffect(ids));
768
- }
769
-
770
- export function lookupUsersByHandlesEffect(
771
- handles: string[],
772
- options: {
773
- auth?: "oauth2";
774
- username?: string;
775
- signal?: AbortSignal;
776
- useConfiguredCandidate?: boolean;
777
- } = {},
778
- ) {
779
- if (handles.length === 0) {
780
- return Effect.succeed([]);
781
- }
782
-
783
- const query = new URLSearchParams({
784
- usernames: handles.map((item) => item.replace(/^@/, "")).join(","),
785
- "user.fields":
786
- "description,entities,location,public_metrics,profile_image_url,url,created_at,verified,verified_type",
787
- });
788
- const args = [`/2/users/by?${query.toString()}`];
789
- const command =
790
- options.auth === "oauth2"
791
- ? runOAuth2JsonCommandEffect({
792
- args,
793
- username: options.username,
794
- options: { signal: options.signal },
795
- useConfiguredCandidate: options.useConfiguredCandidate,
796
- })
797
- : runJsonCommandEffect(args, { signal: options.signal });
798
- return command.pipe(
799
- Effect.map((payload) =>
800
- Array.isArray(payload.data) ? (payload.data as XurlMentionUser[]) : [],
801
- ),
802
- );
803
- }
804
-
805
- export function lookupUsersByHandles(
806
- handles: string[],
807
- options: {
808
- auth?: "oauth2";
809
- username?: string;
810
- signal?: AbortSignal;
811
- useConfiguredCandidate?: boolean;
812
- } = {},
813
- ) {
814
- return runEffectPromise(lookupUsersByHandlesEffect(handles, options));
815
- }
816
-
817
- function authenticatedUserFromPayload(payload: Record<string, unknown>) {
818
- const data = payload.data;
819
- return data && typeof data === "object"
820
- ? (data as Record<string, unknown>)
821
- : null;
822
- }
823
-
824
- export function lookupAuthenticatedUserFreshEffect() {
825
- return runJsonCommandEffect(["whoami"]).pipe(
826
- Effect.map(authenticatedUserFromPayload),
827
- );
828
- }
829
-
830
- export function lookupAuthenticatedOAuth2UserEffect(username?: string) {
831
- return runOAuth2JsonCommandEffect({
832
- args: ["whoami"],
833
- username,
834
- }).pipe(Effect.map(authenticatedUserFromPayload));
835
- }
836
-
837
- export function lookupAuthenticatedUserEffect() {
838
- return Effect.gen(function* () {
839
- const now = Date.now();
840
- if (
841
- authenticatedUserCache &&
842
- "value" in authenticatedUserCache &&
843
- authenticatedUserCache.expiresAt > now
844
- ) {
845
- return authenticatedUserCache.value ?? null;
846
- }
847
-
848
- if (authenticatedUserCache?.pending) {
849
- return yield* Effect.tryPromise({
850
- try: () => authenticatedUserCache?.pending ?? Promise.resolve(null),
851
- catch: normalizeError,
852
- });
853
- }
854
-
855
- const pending = runEffectPromise(lookupAuthenticatedUserFreshEffect());
856
-
857
- authenticatedUserCache = {
858
- expiresAt: 0,
859
- pending,
860
- };
861
-
862
- const value = yield* Effect.tryPromise({
863
- try: () => pending,
864
- catch: normalizeError,
865
- }).pipe(
866
- Effect.catchAll((error) =>
867
- Effect.sync(() => {
868
- authenticatedUserCache = undefined;
869
- }).pipe(Effect.flatMap(() => Effect.fail(error))),
870
- ),
871
- );
872
- authenticatedUserCache = {
873
- expiresAt: Date.now() + AUTHENTICATED_USER_TTL_MS,
874
- value,
875
- };
876
- return value;
877
- });
878
- }
879
-
880
- export function lookupAuthenticatedUser() {
881
- return runEffectPromise(lookupAuthenticatedUserEffect());
882
- }
883
-
884
- export function lookupAuthenticatedUserFresh() {
885
- return runEffectPromise(lookupAuthenticatedUserFreshEffect());
886
- }
887
-
888
- function resolveUserIdEffect({
889
- username,
890
- userId,
891
- }: {
892
- username?: string;
893
- userId?: string;
894
- }) {
895
- return Effect.gen(function* () {
896
- if (userId) return userId;
897
- if (username) {
898
- const [user] = yield* lookupUsersByHandlesEffect([username]);
899
- if (!user?.id) {
900
- return yield* Effect.fail(
901
- new Error(`Could not resolve Twitter user id for @${username}`),
902
- );
903
- }
904
- return String(user.id);
905
- }
906
- const user = yield* lookupAuthenticatedUserEffect();
907
- if (!user?.id) {
908
- return yield* Effect.fail(
909
- new Error("Could not resolve authenticated Twitter user id"),
910
- );
911
- }
912
- return String(user.id);
913
- });
914
- }
915
-
916
- export function listMentionsViaXurlEffect({
917
- maxResults,
918
- username,
919
- userId,
920
- paginationToken,
921
- sinceId,
922
- startTime,
923
- }: {
924
- maxResults: number;
925
- username?: string;
926
- userId?: string;
927
- paginationToken?: string;
928
- sinceId?: string;
929
- startTime?: string;
930
- }): Effect.Effect<XurlMentionsResponse, Error> {
931
- return Effect.gen(function* () {
932
- const resolvedUserId = yield* resolveUserIdEffect({ username, userId });
933
- const query = new URLSearchParams({
934
- max_results: String(maxResults),
935
- expansions: AUTHOR_MEDIA_EXPANSIONS,
936
- "tweet.fields": "created_at,conversation_id,entities,public_metrics",
937
- "media.fields": MEDIA_FIELDS,
938
- "user.fields":
939
- "description,entities,location,public_metrics,profile_image_url,url,created_at,verified,verified_type",
940
- });
941
- if (paginationToken) {
942
- query.set("pagination_token", paginationToken);
943
- }
944
- if (sinceId) {
945
- query.set("since_id", sinceId);
946
- }
947
- if (startTime) {
948
- query.set("start_time", startTime);
949
- }
950
-
951
- const payload = yield* runOAuth2JsonCommandEffect({
952
- args: [`/2/users/${resolvedUserId}/mentions?${query.toString()}`],
953
- username,
954
- });
955
- return toXurlMentionsResponse(payload);
956
- });
957
- }
958
-
959
- export function listMentionsViaXurl(options: {
960
- maxResults: number;
961
- username?: string;
962
- userId?: string;
963
- paginationToken?: string;
964
- sinceId?: string;
965
- startTime?: string;
966
- }): Promise<XurlMentionsResponse> {
967
- return runEffectPromise(listMentionsViaXurlEffect(options));
968
- }
969
-
970
- export function listHomeTimelineViaXurlEffect({
971
- maxResults,
972
- username,
973
- userId,
974
- paginationToken,
975
- timeoutMs,
976
- }: {
977
- maxResults: number;
978
- username?: string;
979
- userId?: string;
980
- paginationToken?: string;
981
- timeoutMs?: number;
982
- }): Effect.Effect<XurlMentionsResponse, Error> {
983
- return Effect.gen(function* () {
984
- const resolvedUserId = yield* resolveUserIdEffect({ username, userId });
985
- const query = new URLSearchParams({
986
- max_results: String(maxResults),
987
- expansions: AUTHOR_MEDIA_EXPANSIONS,
988
- "tweet.fields":
989
- "created_at,conversation_id,entities,public_metrics,referenced_tweets",
990
- "media.fields": MEDIA_FIELDS,
991
- "user.fields": RICH_USER_FIELDS,
992
- });
993
- if (paginationToken) {
994
- query.set("pagination_token", paginationToken);
995
- }
996
-
997
- const payload = yield* runOAuth2JsonCommandEffect({
998
- args: [
999
- `/2/users/${resolvedUserId}/timelines/reverse_chronological?${query.toString()}`,
1000
- ],
1001
- username,
1002
- options: { timeoutMs },
1003
- });
1004
- return toXurlMentionsResponse(payload);
1005
- });
1006
- }
1007
-
1008
- export function listHomeTimelineViaXurl(options: {
1009
- maxResults: number;
1010
- username?: string;
1011
- userId?: string;
1012
- paginationToken?: string;
1013
- timeoutMs?: number;
1014
- }): Promise<XurlMentionsResponse> {
1015
- return runEffectPromise(listHomeTimelineViaXurlEffect(options));
1016
- }
1017
-
1018
- function toXurlMentionsResponse(
1019
- payload: Record<string, unknown>,
1020
- ): XurlMentionsResponse {
1021
- return {
1022
- data: Array.isArray(payload.data)
1023
- ? (payload.data as XurlMentionsResponse["data"])
1024
- : [],
1025
- includes:
1026
- payload.includes && typeof payload.includes === "object"
1027
- ? (payload.includes as XurlMentionsResponse["includes"])
1028
- : undefined,
1029
- meta:
1030
- payload.meta && typeof payload.meta === "object"
1031
- ? (payload.meta as XurlMentionsResponse["meta"])
1032
- : undefined,
1033
- };
1034
- }
1035
-
1036
- function listTimelineCollectionViaXurlEffect({
1037
- collection,
1038
- maxResults,
1039
- username,
1040
- userId,
1041
- isPaginatedWalk = false,
1042
- paginationToken,
1043
- }: {
1044
- collection: TimelineCollectionEndpoint;
1045
- maxResults: number;
1046
- username?: string;
1047
- userId?: string;
1048
- isPaginatedWalk?: boolean;
1049
- paginationToken?: string;
1050
- }): Effect.Effect<XurlMentionsResponse, Error> {
1051
- return Effect.gen(function* () {
1052
- const resolvedUserId = yield* resolveUserIdEffect({ username, userId });
1053
- const requestMaxResults = capTimelineCollectionMaxResults(
1054
- collection,
1055
- maxResults,
1056
- isPaginatedWalk,
1057
- );
1058
- const query = new URLSearchParams({
1059
- max_results: String(requestMaxResults),
1060
- expansions: AUTHOR_MEDIA_EXPANSIONS,
1061
- "tweet.fields":
1062
- "created_at,conversation_id,entities,public_metrics,referenced_tweets",
1063
- "media.fields": MEDIA_FIELDS,
1064
- "user.fields":
1065
- "description,entities,location,public_metrics,profile_image_url,url,created_at,verified,verified_type",
1066
- });
1067
- if (paginationToken) {
1068
- query.set("pagination_token", paginationToken);
1069
- }
1070
-
1071
- const payload = yield* runOAuth2JsonCommandEffect({
1072
- args: [`/2/users/${resolvedUserId}/${collection}?${query.toString()}`],
1073
- username,
1074
- });
1075
- return toXurlMentionsResponse(payload);
1076
- });
1077
- }
1078
-
1079
- export function listLikedTweetsViaXurlEffect(options: {
1080
- maxResults: number;
1081
- username?: string;
1082
- userId?: string;
1083
- paginationToken?: string;
1084
- }) {
1085
- return listTimelineCollectionViaXurlEffect({
1086
- ...options,
1087
- collection: "liked_tweets",
1088
- });
1089
- }
1090
-
1091
- export function listLikedTweetsViaXurl(options: {
1092
- maxResults: number;
1093
- username?: string;
1094
- userId?: string;
1095
- paginationToken?: string;
1096
- }): Promise<XurlMentionsResponse> {
1097
- return runEffectPromise(listLikedTweetsViaXurlEffect(options));
1098
- }
1099
-
1100
- export function listBookmarkedTweetsViaXurlEffect(options: {
1101
- maxResults: number;
1102
- username?: string;
1103
- userId?: string;
1104
- isPaginatedWalk?: boolean;
1105
- paginationToken?: string;
1106
- }) {
1107
- return listTimelineCollectionViaXurlEffect({
1108
- ...options,
1109
- collection: "bookmarks",
1110
- });
1111
- }
1112
-
1113
- export function listBookmarkedTweetsViaXurl(options: {
1114
- maxResults: number;
1115
- username?: string;
1116
- userId?: string;
1117
- isPaginatedWalk?: boolean;
1118
- paginationToken?: string;
1119
- }): Promise<XurlMentionsResponse> {
1120
- return runEffectPromise(listBookmarkedTweetsViaXurlEffect(options));
1121
- }
1122
-
1123
- export function listDirectMessageEventsViaXurlEffect({
1124
- maxResults,
1125
- username,
1126
- paginationToken,
1127
- }: {
1128
- maxResults: number;
1129
- username?: string;
1130
- paginationToken?: string;
1131
- }): Effect.Effect<XurlDmEventsResponse, Error> {
1132
- const query = new URLSearchParams({
1133
- max_results: String(maxResults),
1134
- event_types: "MessageCreate",
1135
- "dm_event.fields": DM_EVENT_FIELDS,
1136
- expansions: "sender_id,participant_ids",
1137
- "user.fields": RICH_USER_FIELDS,
1138
- });
1139
- if (paginationToken) {
1140
- query.set("pagination_token", paginationToken);
1141
- }
1142
-
1143
- return runOAuth2JsonCommandEffect({
1144
- args: [`/2/dm_events?${query.toString()}`],
1145
- username,
1146
- }).pipe(
1147
- Effect.map((payload) => ({
1148
- data: Array.isArray(payload.data)
1149
- ? (payload.data as XurlDmEventsResponse["data"])
1150
- : [],
1151
- includes:
1152
- payload.includes && typeof payload.includes === "object"
1153
- ? (payload.includes as XurlDmEventsResponse["includes"])
1154
- : undefined,
1155
- meta:
1156
- payload.meta && typeof payload.meta === "object"
1157
- ? (payload.meta as Record<string, unknown>)
1158
- : undefined,
1159
- })),
1160
- );
1161
- }
1162
-
1163
- export function listDirectMessageEventsViaXurl(options: {
1164
- maxResults: number;
1165
- username?: string;
1166
- paginationToken?: string;
1167
- }): Promise<XurlDmEventsResponse> {
1168
- return runEffectPromise(listDirectMessageEventsViaXurlEffect(options));
1169
- }
1170
-
1171
- export function listFollowUsersViaXurlEffect({
1172
- direction,
1173
- maxResults,
1174
- username,
1175
- userId,
1176
- paginationToken,
1177
- }: {
1178
- direction: FollowDirection;
1179
- maxResults: number;
1180
- username?: string;
1181
- userId?: string;
1182
- paginationToken?: string;
1183
- }): Effect.Effect<XurlFollowUsersResponse, Error> {
1184
- return Effect.gen(function* () {
1185
- const resolvedUserId = yield* resolveUserIdEffect({ username, userId });
1186
- const query = new URLSearchParams({
1187
- max_results: String(maxResults),
1188
- "user.fields":
1189
- "id,username,name,description,verified,protected,public_metrics,profile_image_url,created_at",
1190
- });
1191
- if (paginationToken) {
1192
- query.set("pagination_token", paginationToken);
1193
- }
1194
-
1195
- const payload = yield* runOAuth2JsonCommandEffect({
1196
- args: [`/2/users/${resolvedUserId}/${direction}?${query.toString()}`],
1197
- username,
1198
- });
1199
- return {
1200
- data: Array.isArray(payload.data)
1201
- ? (payload.data as XurlMentionUser[])
1202
- : [],
1203
- meta:
1204
- payload.meta && typeof payload.meta === "object"
1205
- ? (payload.meta as Record<string, unknown>)
1206
- : undefined,
1207
- };
1208
- });
1209
- }
1210
-
1211
- export function listFollowUsersViaXurl(options: {
1212
- direction: FollowDirection;
1213
- maxResults: number;
1214
- username?: string;
1215
- userId?: string;
1216
- paginationToken?: string;
1217
- }): Promise<XurlFollowUsersResponse> {
1218
- return runEffectPromise(listFollowUsersViaXurlEffect(options));
1219
- }
1220
-
1221
- export function listBlockedUsersEffect(
1222
- userId: string,
1223
- paginationToken?: string,
1224
- ) {
1225
- const query = new URLSearchParams({
1226
- max_results: "100",
1227
- "user.fields":
1228
- "description,entities,location,public_metrics,profile_image_url,url,created_at,verified,verified_type",
1229
- });
1230
- if (paginationToken) {
1231
- query.set("pagination_token", paginationToken);
1232
- }
1233
-
1234
- return runJsonCommandEffect([`/2/users/${userId}/blocking?${query}`]).pipe(
1235
- Effect.map((payload) => {
1236
- const data = Array.isArray(payload.data)
1237
- ? (payload.data as XurlMentionUser[])
1238
- : [];
1239
- const meta =
1240
- payload.meta && typeof payload.meta === "object"
1241
- ? (payload.meta as Record<string, unknown>)
1242
- : null;
1243
-
1244
- return {
1245
- items: data,
1246
- nextToken:
1247
- typeof meta?.next_token === "string" ? String(meta.next_token) : null,
1248
- };
1249
- }),
1250
- );
1251
- }
1252
-
1253
- export function listBlockedUsers(userId: string, paginationToken?: string) {
1254
- return runEffectPromise(listBlockedUsersEffect(userId, paginationToken));
1255
- }
1256
-
1257
- export function listUserTweetsEffect(
1258
- userId: string,
1259
- {
1260
- maxResults,
1261
- paginationToken,
1262
- excludeRetweets = true,
1263
- sinceId,
1264
- untilId,
1265
- tweetFields,
1266
- expansions,
1267
- userFields,
1268
- mediaFields,
1269
- auth,
1270
- username,
1271
- signal,
1272
- onAttempt,
1273
- useConfiguredCandidate,
1274
- }: {
1275
- maxResults: number;
1276
- paginationToken?: string;
1277
- excludeRetweets?: boolean;
1278
- sinceId?: string;
1279
- untilId?: string;
1280
- tweetFields?: string[];
1281
- expansions?: string[];
1282
- userFields?: string[];
1283
- mediaFields?: string[];
1284
- auth?: "oauth2";
1285
- username?: string;
1286
- signal?: AbortSignal;
1287
- onAttempt?: JsonCommandOptions["onAttempt"];
1288
- useConfiguredCandidate?: boolean;
1289
- },
1290
- ): Effect.Effect<XurlUserTweetsResponse, Error> {
1291
- const query = new URLSearchParams({
1292
- max_results: String(maxResults),
1293
- expansions: MEDIA_EXPANSION,
1294
- "tweet.fields":
1295
- tweetFields?.join(",") ??
1296
- "created_at,conversation_id,public_metrics,referenced_tweets",
1297
- "media.fields": MEDIA_FIELDS,
1298
- });
1299
- if (expansions && expansions.length > 0) {
1300
- query.set("expansions", expansions.join(","));
1301
- }
1302
- if (userFields && userFields.length > 0) {
1303
- query.set("user.fields", userFields.join(","));
1304
- }
1305
- if (mediaFields && mediaFields.length > 0) {
1306
- query.set("media.fields", mediaFields.join(","));
1307
- }
1308
- if (sinceId) {
1309
- query.set("since_id", sinceId);
1310
- }
1311
- if (untilId) {
1312
- query.set("until_id", untilId);
1313
- }
1314
- if (excludeRetweets) {
1315
- query.set("exclude", "retweets");
1316
- }
1317
- if (paginationToken) {
1318
- query.set("pagination_token", paginationToken);
1319
- }
1320
-
1321
- const endpoint = `/2/users/${userId}/tweets?${query}`;
1322
- const command =
1323
- auth === "oauth2"
1324
- ? runOAuth2JsonCommandEffect({
1325
- args: [endpoint],
1326
- username,
1327
- options: { signal, onAttempt },
1328
- useConfiguredCandidate,
1329
- })
1330
- : runJsonCommandEffect([endpoint], { signal, onAttempt });
1331
- return command.pipe(
1332
- Effect.map((payload) => {
1333
- const data = Array.isArray(payload.data)
1334
- ? (payload.data as XurlUserTweet[])
1335
- : [];
1336
- const meta =
1337
- payload.meta && typeof payload.meta === "object"
1338
- ? (payload.meta as Record<string, unknown>)
1339
- : null;
1340
- const includes =
1341
- payload.includes && typeof payload.includes === "object"
1342
- ? (payload.includes as XurlUserTweetsResponse["includes"])
1343
- : undefined;
1344
-
1345
- return {
1346
- items: data,
1347
- nextToken:
1348
- typeof meta?.next_token === "string" ? String(meta.next_token) : null,
1349
- ...(includes ? { includes } : {}),
1350
- };
1351
- }),
1352
- );
1353
- }
1354
-
1355
- export function listUserTweets(
1356
- userId: string,
1357
- options: {
1358
- maxResults: number;
1359
- paginationToken?: string;
1360
- excludeRetweets?: boolean;
1361
- sinceId?: string;
1362
- untilId?: string;
1363
- tweetFields?: string[];
1364
- expansions?: string[];
1365
- userFields?: string[];
1366
- mediaFields?: string[];
1367
- auth?: "oauth2";
1368
- username?: string;
1369
- signal?: AbortSignal;
1370
- onAttempt?: JsonCommandOptions["onAttempt"];
1371
- useConfiguredCandidate?: boolean;
1372
- },
1373
- ): Promise<XurlUserTweetsResponse> {
1374
- return runEffectPromise(listUserTweetsEffect(userId, options));
1375
- }
1376
-
1377
- function toXurlTweetsResponse(
1378
- payload: Record<string, unknown>,
1379
- ): XurlTweetsResponse {
1380
- return {
1381
- data: Array.isArray(payload.data)
1382
- ? (payload.data as XurlTweetsResponse["data"])
1383
- : [],
1384
- includes:
1385
- payload.includes && typeof payload.includes === "object"
1386
- ? (payload.includes as XurlTweetsResponse["includes"])
1387
- : undefined,
1388
- meta:
1389
- payload.meta && typeof payload.meta === "object"
1390
- ? (payload.meta as XurlTweetsResponse["meta"])
1391
- : undefined,
1392
- };
1393
- }
1394
-
1395
- export function lookupTweetsByIdsEffect(
1396
- ids: string[],
1397
- ): Effect.Effect<XurlTweetsResponse, Error> {
1398
- if (ids.length === 0) {
1399
- return Effect.succeed({ data: [] });
1400
- }
1401
-
1402
- const query = new URLSearchParams({
1403
- ids: ids.join(","),
1404
- expansions: AUTHOR_MEDIA_EXPANSIONS,
1405
- "tweet.fields":
1406
- "created_at,conversation_id,entities,public_metrics,referenced_tweets",
1407
- "media.fields": MEDIA_FIELDS,
1408
- "user.fields":
1409
- "description,entities,location,public_metrics,profile_image_url,url,created_at,verified,verified_type",
1410
- });
1411
-
1412
- return runJsonCommandEffect([`/2/tweets?${query.toString()}`]).pipe(
1413
- Effect.map(toXurlTweetsResponse),
1414
- );
1415
- }
1416
-
1417
- export function lookupTweetsByIds(ids: string[]): Promise<XurlTweetsResponse> {
1418
- return runEffectPromise(lookupTweetsByIdsEffect(ids));
1419
- }
1420
-
1421
- export function searchRecentByConversationIdEffect(
1422
- conversationId: string,
1423
- {
1424
- maxResults,
1425
- paginationToken,
1426
- timeoutMs,
1427
- auth,
1428
- username,
1429
- signal,
1430
- onAttempt,
1431
- }: {
1432
- maxResults: number;
1433
- paginationToken?: string;
1434
- timeoutMs?: number;
1435
- auth?: "oauth2";
1436
- username?: string;
1437
- signal?: AbortSignal;
1438
- onAttempt?: JsonCommandOptions["onAttempt"];
1439
- },
1440
- ): Effect.Effect<XurlTweetsResponse, Error> {
1441
- const query = new URLSearchParams({
1442
- query: `conversation_id:${conversationId}`,
1443
- max_results: String(maxResults),
1444
- expansions: AUTHOR_MEDIA_EXPANSIONS,
1445
- "tweet.fields": THREAD_TWEET_FIELDS,
1446
- "media.fields": MEDIA_FIELDS,
1447
- "user.fields": RICH_USER_FIELDS,
1448
- });
1449
- if (paginationToken) {
1450
- query.set("pagination_token", paginationToken);
1451
- }
1452
-
1453
- const args = [`/2/tweets/search/recent?${query.toString()}`];
1454
- const command =
1455
- auth === "oauth2"
1456
- ? runOAuth2JsonCommandEffect({
1457
- args,
1458
- username,
1459
- options: { timeoutMs, signal, onAttempt },
1460
- useConfiguredCandidate: false,
1461
- })
1462
- : runJsonCommandEffect(args, { timeoutMs, signal, onAttempt });
1463
- return command.pipe(Effect.map(toXurlTweetsResponse));
1464
- }
1465
-
1466
- export function searchRecentByConversationId(
1467
- conversationId: string,
1468
- options: {
1469
- maxResults: number;
1470
- paginationToken?: string;
1471
- timeoutMs?: number;
1472
- auth?: "oauth2";
1473
- username?: string;
1474
- signal?: AbortSignal;
1475
- onAttempt?: JsonCommandOptions["onAttempt"];
1476
- },
1477
- ): Promise<XurlTweetsResponse> {
1478
- return runEffectPromise(
1479
- searchRecentByConversationIdEffect(conversationId, options),
1480
- );
1481
- }
1482
-
1483
- export function searchRecentTweetsEffect(
1484
- searchQuery: string,
1485
- {
1486
- maxResults,
1487
- paginationToken,
1488
- startTime,
1489
- endTime,
1490
- username,
1491
- timeoutMs,
1492
- }: {
1493
- maxResults: number;
1494
- paginationToken?: string;
1495
- startTime?: string;
1496
- endTime?: string;
1497
- username?: string;
1498
- timeoutMs?: number;
1499
- },
1500
- ): Effect.Effect<XurlTweetsResponse, Error> {
1501
- const query = new URLSearchParams({
1502
- query: searchQuery,
1503
- max_results: String(maxResults),
1504
- expansions: AUTHOR_MEDIA_EXPANSIONS,
1505
- "tweet.fields": THREAD_TWEET_FIELDS,
1506
- "media.fields": MEDIA_FIELDS,
1507
- "user.fields": RICH_USER_FIELDS,
1508
- });
1509
- if (paginationToken) {
1510
- query.set("pagination_token", paginationToken);
1511
- }
1512
- if (startTime) {
1513
- query.set("start_time", startTime);
1514
- }
1515
- if (endTime) {
1516
- query.set("end_time", endTime);
1517
- }
1518
-
1519
- return runOAuth2JsonCommandEffect({
1520
- args: [`/2/tweets/search/recent?${query.toString()}`],
1521
- username,
1522
- options: { timeoutMs },
1523
- useConfiguredCandidate: false,
1524
- }).pipe(Effect.map(toXurlTweetsResponse));
1525
- }
1526
-
1527
- export function searchRecentTweets(
1528
- searchQuery: string,
1529
- options: {
1530
- maxResults: number;
1531
- paginationToken?: string;
1532
- startTime?: string;
1533
- endTime?: string;
1534
- username?: string;
1535
- timeoutMs?: number;
1536
- },
1537
- ): Promise<XurlTweetsResponse> {
1538
- return runEffectPromise(searchRecentTweetsEffect(searchQuery, options));
1539
- }
1540
-
1541
- export function getTweetByIdEffect(
1542
- id: string,
1543
- { timeoutMs }: { timeoutMs?: number } = {},
1544
- ): Effect.Effect<XurlTweetsResponse, Error> {
1545
- const query = new URLSearchParams({
1546
- expansions: AUTHOR_MEDIA_EXPANSIONS,
1547
- "tweet.fields": THREAD_TWEET_FIELDS,
1548
- "media.fields": MEDIA_FIELDS,
1549
- "user.fields": RICH_USER_FIELDS,
1550
- });
1551
-
1552
- return runJsonCommandEffect([`/2/tweets/${id}?${query.toString()}`], {
1553
- timeoutMs,
1554
- }).pipe(
1555
- Effect.map((payload) => {
1556
- const data =
1557
- payload.data &&
1558
- typeof payload.data === "object" &&
1559
- !Array.isArray(payload.data)
1560
- ? [payload.data as XurlTweetsResponse["data"][number]]
1561
- : Array.isArray(payload.data)
1562
- ? (payload.data as XurlTweetsResponse["data"])
1563
- : [];
1564
-
1565
- return {
1566
- data,
1567
- includes:
1568
- payload.includes && typeof payload.includes === "object"
1569
- ? (payload.includes as XurlTweetsResponse["includes"])
1570
- : undefined,
1571
- meta:
1572
- payload.meta && typeof payload.meta === "object"
1573
- ? (payload.meta as XurlTweetsResponse["meta"])
1574
- : undefined,
1575
- };
1576
- }),
1577
- );
1578
- }
1579
-
1580
- export function getTweetById(
1581
- id: string,
1582
- options: { timeoutMs?: number } = {},
1583
- ): Promise<XurlTweetsResponse> {
1584
- return runEffectPromise(getTweetByIdEffect(id, options));
1585
- }
1586
-
1587
- export function postViaXurlEffect(text: string) {
1588
- return runShortcutEffect(["post", text]);
1589
- }
1590
-
1591
- export function postViaXurl(text: string) {
1592
- return runEffectPromise(postViaXurlEffect(text));
1593
- }
1594
-
1595
- export function replyViaXurlEffect(tweetId: string, text: string) {
1596
- return runShortcutEffect(["reply", tweetId, text]);
1597
- }
1598
-
1599
- export function replyViaXurl(tweetId: string, text: string) {
1600
- return runEffectPromise(replyViaXurlEffect(tweetId, text));
1601
- }
1602
-
1603
- export function dmViaXurlEffect(handle: string, text: string) {
1604
- return runShortcutEffect([
1605
- "dm",
1606
- handle.startsWith("@") ? handle : `@${handle}`,
1607
- text,
1608
- ]);
1609
- }
1610
-
1611
- export function dmViaXurl(handle: string, text: string) {
1612
- return runEffectPromise(dmViaXurlEffect(handle, text));
1613
- }
1614
-
1615
- export function blockUserViaXurlEffect(
1616
- sourceUserId: string,
1617
- targetUserId: string,
1618
- ) {
1619
- return runMutationCommandEffect([
1620
- "-X",
1621
- "POST",
1622
- `/2/users/${sourceUserId}/blocking`,
1623
- "-d",
1624
- JSON.stringify({ target_user_id: targetUserId }),
1625
- ]);
1626
- }
1627
-
1628
- export function blockUserViaXurl(sourceUserId: string, targetUserId: string) {
1629
- return runEffectPromise(blockUserViaXurlEffect(sourceUserId, targetUserId));
1630
- }
1631
-
1632
- export function unblockUserViaXurlEffect(
1633
- sourceUserId: string,
1634
- targetUserId: string,
1635
- ) {
1636
- return runMutationCommandEffect([
1637
- "-X",
1638
- "DELETE",
1639
- `/2/users/${sourceUserId}/blocking/${targetUserId}`,
1640
- ]);
1641
- }
1642
-
1643
- export function unblockUserViaXurl(sourceUserId: string, targetUserId: string) {
1644
- return runEffectPromise(unblockUserViaXurlEffect(sourceUserId, targetUserId));
1645
- }
1646
-
1647
- export function muteUserViaXurlEffect(
1648
- sourceUserId: string,
1649
- targetUserId: string,
1650
- ) {
1651
- return runMutationCommandEffect([
1652
- "-X",
1653
- "POST",
1654
- `/2/users/${sourceUserId}/muting`,
1655
- "-d",
1656
- JSON.stringify({ target_user_id: targetUserId }),
1657
- ]);
1658
- }
1659
-
1660
- export function muteUserViaXurl(sourceUserId: string, targetUserId: string) {
1661
- return runEffectPromise(muteUserViaXurlEffect(sourceUserId, targetUserId));
1662
- }
1663
-
1664
- export function unmuteUserViaXurlEffect(
1665
- sourceUserId: string,
1666
- targetUserId: string,
1667
- ) {
1668
- return runMutationCommandEffect([
1669
- "-X",
1670
- "DELETE",
1671
- `/2/users/${sourceUserId}/muting/${targetUserId}`,
1672
- ]);
1673
- }
1674
-
1675
- export function unmuteUserViaXurl(sourceUserId: string, targetUserId: string) {
1676
- return runEffectPromise(unmuteUserViaXurlEffect(sourceUserId, targetUserId));
1677
- }