birdclaw 0.8.2 → 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 (247) hide show
  1. package/CHANGELOG.md +33 -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 +27 -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-moderation.ts +0 -210
  100. package/src/cli.ts +0 -2336
  101. package/src/components/AccountSwitcher.tsx +0 -186
  102. package/src/components/AppNav.tsx +0 -118
  103. package/src/components/AvatarChip.tsx +0 -58
  104. package/src/components/BrandMark.tsx +0 -67
  105. package/src/components/ConversationThread.tsx +0 -131
  106. package/src/components/DmWorkspace.tsx +0 -286
  107. package/src/components/EmbeddedTweetCard.tsx +0 -55
  108. package/src/components/FeedState.tsx +0 -147
  109. package/src/components/FloatingPreview.tsx +0 -382
  110. package/src/components/InboxCard.tsx +0 -152
  111. package/src/components/LinkPreviewCard.tsx +0 -292
  112. package/src/components/MarkdownViewer.tsx +0 -777
  113. package/src/components/ProfileAnalysisStream.tsx +0 -428
  114. package/src/components/ProfilePreview.tsx +0 -129
  115. package/src/components/SavedTimelineView.tsx +0 -155
  116. package/src/components/SmartTimestamp.tsx +0 -72
  117. package/src/components/SyncNowButton.tsx +0 -140
  118. package/src/components/ThemeSlider.tsx +0 -80
  119. package/src/components/TimelineCard.tsx +0 -533
  120. package/src/components/TimelineRouteFrame.tsx +0 -186
  121. package/src/components/TweetArticleCard.tsx +0 -66
  122. package/src/components/TweetMediaGrid.tsx +0 -185
  123. package/src/components/TweetRichText.tsx +0 -159
  124. package/src/components/account-selection.ts +0 -64
  125. package/src/components/useTimelineRouteData.ts +0 -323
  126. package/src/lib/account-sync-job.ts +0 -666
  127. package/src/lib/actions-transport.ts +0 -300
  128. package/src/lib/api-client.ts +0 -419
  129. package/src/lib/archive-finder.ts +0 -185
  130. package/src/lib/archive-import.ts +0 -2764
  131. package/src/lib/authored-live.ts +0 -1072
  132. package/src/lib/avatar-cache.ts +0 -349
  133. package/src/lib/backup.ts +0 -2741
  134. package/src/lib/bird-actions.ts +0 -294
  135. package/src/lib/bird-command.ts +0 -130
  136. package/src/lib/bird.ts +0 -1140
  137. package/src/lib/blocklist.ts +0 -136
  138. package/src/lib/blocks-write.ts +0 -167
  139. package/src/lib/blocks.ts +0 -389
  140. package/src/lib/bookmark-sync-job.ts +0 -536
  141. package/src/lib/client-cache.ts +0 -109
  142. package/src/lib/config.ts +0 -224
  143. package/src/lib/conversation-surface.ts +0 -205
  144. package/src/lib/data-sources.ts +0 -219
  145. package/src/lib/db.ts +0 -1135
  146. package/src/lib/dms-live.ts +0 -933
  147. package/src/lib/effect-runtime.ts +0 -45
  148. package/src/lib/follow-graph.ts +0 -1097
  149. package/src/lib/geocoding.ts +0 -296
  150. package/src/lib/http-effect.ts +0 -222
  151. package/src/lib/identity-search-index.ts +0 -369
  152. package/src/lib/inbox.ts +0 -241
  153. package/src/lib/link-index.ts +0 -641
  154. package/src/lib/link-insights.ts +0 -860
  155. package/src/lib/link-preview-metadata.ts +0 -754
  156. package/src/lib/location.ts +0 -137
  157. package/src/lib/media-fetch.ts +0 -860
  158. package/src/lib/media-includes.ts +0 -165
  159. package/src/lib/mention-threads-live.ts +0 -917
  160. package/src/lib/mentions-export.ts +0 -147
  161. package/src/lib/mentions-live.ts +0 -1238
  162. package/src/lib/moderation-target.ts +0 -216
  163. package/src/lib/moderation-write.ts +0 -131
  164. package/src/lib/mutes-write.ts +0 -167
  165. package/src/lib/mutes.ts +0 -84
  166. package/src/lib/ndjson-stream.ts +0 -106
  167. package/src/lib/network-map.ts +0 -382
  168. package/src/lib/openai.ts +0 -117
  169. package/src/lib/period-digest.ts +0 -1552
  170. package/src/lib/present.ts +0 -118
  171. package/src/lib/profile-affiliation-hydration.ts +0 -228
  172. package/src/lib/profile-affiliations.ts +0 -262
  173. package/src/lib/profile-analysis.ts +0 -1272
  174. package/src/lib/profile-bio-entities.ts +0 -318
  175. package/src/lib/profile-history.ts +0 -164
  176. package/src/lib/profile-hydration.ts +0 -180
  177. package/src/lib/profile-replies.ts +0 -77
  178. package/src/lib/profile-resolver.ts +0 -650
  179. package/src/lib/queries.ts +0 -2381
  180. package/src/lib/research.ts +0 -652
  181. package/src/lib/search-discussion.ts +0 -1016
  182. package/src/lib/seed.ts +0 -613
  183. package/src/lib/sqlite.ts +0 -147
  184. package/src/lib/sync-cache.ts +0 -65
  185. package/src/lib/theme-transition.ts +0 -113
  186. package/src/lib/theme.tsx +0 -165
  187. package/src/lib/timeline-collections-live.ts +0 -581
  188. package/src/lib/timeline-live.ts +0 -452
  189. package/src/lib/tweet-account-edges.ts +0 -48
  190. package/src/lib/tweet-lookup.ts +0 -46
  191. package/src/lib/tweet-render.ts +0 -430
  192. package/src/lib/tweet-search-live.ts +0 -566
  193. package/src/lib/types.ts +0 -723
  194. package/src/lib/ui.ts +0 -529
  195. package/src/lib/url-expansion-store.ts +0 -110
  196. package/src/lib/url-expansion.ts +0 -343
  197. package/src/lib/url-safety.ts +0 -220
  198. package/src/lib/web-sync.ts +0 -516
  199. package/src/lib/whois.ts +0 -1079
  200. package/src/lib/x-profile.ts +0 -365
  201. package/src/lib/x-web.ts +0 -199
  202. package/src/lib/xurl-rate-limits.ts +0 -267
  203. package/src/lib/xurl.ts +0 -1677
  204. package/src/routeTree.gen.ts +0 -723
  205. package/src/router.tsx +0 -20
  206. package/src/routes/__root.tsx +0 -79
  207. package/src/routes/api/action.tsx +0 -147
  208. package/src/routes/api/avatar.tsx +0 -50
  209. package/src/routes/api/blocks.tsx +0 -35
  210. package/src/routes/api/conversation.tsx +0 -45
  211. package/src/routes/api/data-sources.tsx +0 -24
  212. package/src/routes/api/inbox.tsx +0 -43
  213. package/src/routes/api/link-insights.tsx +0 -85
  214. package/src/routes/api/link-preview.tsx +0 -47
  215. package/src/routes/api/network-map.tsx +0 -55
  216. package/src/routes/api/period-digest.tsx +0 -101
  217. package/src/routes/api/profile-analysis.tsx +0 -97
  218. package/src/routes/api/profile-hydrate.tsx +0 -54
  219. package/src/routes/api/query.tsx +0 -115
  220. package/src/routes/api/search-discussion.tsx +0 -113
  221. package/src/routes/api/status.tsx +0 -28
  222. package/src/routes/api/sync.tsx +0 -105
  223. package/src/routes/api/xurl-rate-limits.tsx +0 -24
  224. package/src/routes/blocks.tsx +0 -377
  225. package/src/routes/bookmarks.tsx +0 -18
  226. package/src/routes/data-sources.tsx +0 -257
  227. package/src/routes/discuss.tsx +0 -419
  228. package/src/routes/dms.tsx +0 -432
  229. package/src/routes/inbox.tsx +0 -226
  230. package/src/routes/index.tsx +0 -32
  231. package/src/routes/likes.tsx +0 -18
  232. package/src/routes/links.tsx +0 -994
  233. package/src/routes/mentions.tsx +0 -32
  234. package/src/routes/network-map.tsx +0 -1035
  235. package/src/routes/profile-analyze.tsx +0 -112
  236. package/src/routes/profiles.$handle.tsx +0 -228
  237. package/src/routes/rate-limits.tsx +0 -309
  238. package/src/routes/today.tsx +0 -511
  239. package/src/styles.css +0 -257
  240. package/tsconfig.json +0 -29
  241. package/vite.config.ts +0 -29
  242. /package/{public → dist/client}/birdclaw-mark.png +0 -0
  243. /package/{public → dist/client}/favicon.ico +0 -0
  244. /package/{public → dist/client}/logo192.png +0 -0
  245. /package/{public → dist/client}/logo512.png +0 -0
  246. /package/{public → dist/client}/manifest.json +0 -0
  247. /package/{public → dist/client}/robots.txt +0 -0
@@ -1,917 +0,0 @@
1
- import type { Database } from "./sqlite";
2
- import { Effect } from "effect";
3
- import { listThreadViaBirdEffect } from "./bird";
4
- import { getNativeDb } from "./db";
5
- import { runEffectPromise } from "./effect-runtime";
6
- import { buildMediaJsonFromIncludes, countTweetMedia } from "./media-includes";
7
- import { tweetEntitiesFromXurl } from "./tweet-render";
8
- import type {
9
- XurlMentionData,
10
- XurlMentionsResponse,
11
- XurlMentionUser,
12
- XurlMediaItem,
13
- XurlTweetsResponse,
14
- } from "./types";
15
- import { upsertTweetAccountEdge } from "./tweet-account-edges";
16
- import { ensureStubProfileForXUser, upsertProfileFromXUser } from "./x-profile";
17
- import { getTweetByIdEffect, searchRecentByConversationIdEffect } from "./xurl";
18
-
19
- const DEFAULT_LIMIT = 30;
20
- const DEFAULT_DELAY_MS = 1500;
21
- const DEFAULT_TIMEOUT_MS = 15_000;
22
- const DEFAULT_MODE = "bird";
23
- const DEFAULT_FALLBACK_DEPTH = 12;
24
- const MAX_XURL_SEARCH_RESULTS = 100;
25
-
26
- export type MentionThreadsMode = "bird" | "xurl";
27
- export interface MentionThreadsProgress {
28
- source: MentionThreadsMode;
29
- processed: number;
30
- total: number;
31
- fetched: number;
32
- done: boolean;
33
- }
34
- export interface SyncMentionThreadsOptions {
35
- account?: string;
36
- mode?: string;
37
- limit?: number;
38
- tweetIds?: string[];
39
- delayMs?: number;
40
- timeoutMs?: number;
41
- all?: boolean;
42
- maxPages?: number;
43
- onProgress?: (progress: MentionThreadsProgress) => void;
44
- }
45
-
46
- interface LocalMention {
47
- id: string;
48
- replyToId?: string;
49
- conversationId?: string;
50
- rawTweet?: XurlMentionData;
51
- }
52
- interface ThreadFetchResult {
53
- strategy: string;
54
- payload: XurlMentionsResponse;
55
- pages?: number;
56
- fallbackDepth?: number;
57
- generalReadTweets: number;
58
- truncated?: boolean;
59
- warnings: string[];
60
- }
61
-
62
- function assertPositiveInteger(value: number, name: string) {
63
- if (!Number.isFinite(value) || value < 1) {
64
- throw new Error(`${name} must be at least 1`);
65
- }
66
- return Math.floor(value);
67
- }
68
-
69
- function parseNonNegativeInteger(value: number | undefined, name: string) {
70
- if (value === undefined) {
71
- return undefined;
72
- }
73
- if (!Number.isFinite(value) || value < 0) {
74
- throw new Error(`${name} must be non-negative`);
75
- }
76
- return Math.floor(value);
77
- }
78
-
79
- function parseMode(value: string | undefined): MentionThreadsMode {
80
- const mode = value ?? DEFAULT_MODE;
81
- if (mode !== "bird" && mode !== "xurl") {
82
- throw new Error("--mode must be bird or xurl");
83
- }
84
- return mode;
85
- }
86
-
87
- function toError(error: unknown) {
88
- return error instanceof Error ? error : new Error(String(error));
89
- }
90
-
91
- function trySync<T>(try_: () => T) {
92
- return Effect.try({
93
- try: try_,
94
- catch: toError,
95
- });
96
- }
97
-
98
- function getRemainingThreadTimeoutMs(
99
- deadlineMs: number,
100
- originalTimeoutMs: number,
101
- ) {
102
- const remainingMs = deadlineMs - Date.now();
103
- if (remainingMs <= 0) {
104
- throw new Error(
105
- `xurl thread timed out after ${String(originalTimeoutMs)}ms`,
106
- );
107
- }
108
- return remainingMs;
109
- }
110
- function replaceTweetFts(db: Database, tweetId: string, text: string) {
111
- db.prepare("delete from tweets_fts where tweet_id = ?").run(tweetId);
112
- db.prepare("insert into tweets_fts (tweet_id, text) values (?, ?)").run(
113
- tweetId,
114
- text,
115
- );
116
- }
117
-
118
- function resolveAccount(db: Database, accountId?: string) {
119
- const row = accountId
120
- ? (db
121
- .prepare("select id, handle from accounts where id = ?")
122
- .get(accountId) as { id: string; handle: string } | undefined)
123
- : (db
124
- .prepare(
125
- `
126
- select id, handle
127
- from accounts
128
- order by is_default desc, created_at asc
129
- limit 1
130
- `,
131
- )
132
- .get() as { id: string; handle: string } | undefined);
133
-
134
- if (!row) {
135
- throw new Error(`Unknown account: ${accountId ?? "default"}`);
136
- }
137
-
138
- return {
139
- accountId: row.id,
140
- handle: row.handle.replace(/^@/, "").toLowerCase(),
141
- };
142
- }
143
-
144
- function getReplyToId(tweet: XurlMentionData) {
145
- return tweet.referenced_tweets?.find((entry) => entry.type === "replied_to")
146
- ?.id;
147
- }
148
-
149
- function mergePayloads(pages: XurlTweetsResponse[]): XurlMentionsResponse {
150
- const tweets: XurlMentionData[] = [];
151
- const seenTweetIds = new Set<string>();
152
- const users: XurlMentionUser[] = [];
153
- const seenUserIds = new Set<string>();
154
- const media: XurlMediaItem[] = [];
155
- const seenMediaKeys = new Set<string>();
156
-
157
- for (const page of pages) {
158
- for (const tweet of page.data) {
159
- if (seenTweetIds.has(tweet.id)) {
160
- continue;
161
- }
162
- seenTweetIds.add(tweet.id);
163
- tweets.push(tweet);
164
- }
165
-
166
- for (const user of page.includes?.users ?? []) {
167
- if (seenUserIds.has(user.id)) {
168
- continue;
169
- }
170
- seenUserIds.add(user.id);
171
- users.push(user);
172
- }
173
-
174
- for (const item of page.includes?.media ?? []) {
175
- if (seenMediaKeys.has(item.media_key)) {
176
- continue;
177
- }
178
- seenMediaKeys.add(item.media_key);
179
- media.push(item);
180
- }
181
- }
182
-
183
- const lastMeta = pages.at(-1)?.meta;
184
- return {
185
- data: tweets,
186
- includes:
187
- users.length > 0 || media.length > 0
188
- ? {
189
- ...(users.length > 0 ? { users } : {}),
190
- ...(media.length > 0 ? { media } : {}),
191
- }
192
- : undefined,
193
- meta: {
194
- ...lastMeta,
195
- result_count: tweets.length,
196
- page_count: pages.length,
197
- next_token:
198
- typeof lastMeta?.next_token === "string" ? lastMeta.next_token : null,
199
- },
200
- };
201
- }
202
-
203
- function parseRawTweet(value: string | null | undefined) {
204
- if (!value || value === "{}" || value === "null") {
205
- return undefined;
206
- }
207
-
208
- try {
209
- const parsed = JSON.parse(value) as unknown;
210
- if (parsed && typeof parsed === "object") {
211
- return parsed as XurlMentionData;
212
- }
213
- } catch {
214
- return undefined;
215
- }
216
-
217
- return undefined;
218
- }
219
-
220
- function listRecentMentions(
221
- db: Database,
222
- accountId: string,
223
- limit: number,
224
- ): LocalMention[] {
225
- const rows = db
226
- .prepare(
227
- `
228
- with local_mentions as (
229
- select
230
- t.id,
231
- t.created_at as createdAt,
232
- t.reply_to_id as replyToId,
233
- edge.raw_json as rawJson
234
- from tweet_account_edges edge
235
- join tweets t on t.id = edge.tweet_id
236
- where edge.kind = 'mention' and edge.account_id = ?
237
- union all
238
- select
239
- t.id,
240
- t.created_at as createdAt,
241
- t.reply_to_id as replyToId,
242
- '{}' as rawJson
243
- from tweets t
244
- where t.kind = 'mention' and t.account_id = ?
245
- and not exists (
246
- select 1
247
- from tweet_account_edges edge
248
- where edge.account_id = t.account_id
249
- and edge.tweet_id = t.id
250
- and edge.kind = 'mention'
251
- )
252
- )
253
- select id, createdAt, replyToId, rawJson
254
- from local_mentions
255
- order by createdAt desc
256
- limit ?
257
- `,
258
- )
259
- .all(accountId, accountId, limit) as Array<{
260
- id: string;
261
- createdAt: string;
262
- replyToId: string | null;
263
- rawJson: string | null;
264
- }>;
265
-
266
- return rows.map((row) => {
267
- const rawTweet = parseRawTweet(row.rawJson);
268
- return {
269
- id: row.id,
270
- replyToId:
271
- row.replyToId ?? (rawTweet ? getReplyToId(rawTweet) : undefined),
272
- conversationId:
273
- typeof rawTweet?.conversation_id === "string"
274
- ? rawTweet.conversation_id
275
- : undefined,
276
- rawTweet,
277
- };
278
- });
279
- }
280
-
281
- function listMentionsByIds(
282
- db: Database,
283
- accountId: string,
284
- tweetIds: string[],
285
- limit: number,
286
- ): LocalMention[] {
287
- const ids = [...new Set(tweetIds.filter((id) => id.trim().length > 0))].slice(
288
- 0,
289
- limit,
290
- );
291
- if (ids.length === 0) return [];
292
- const placeholders = ids.map(() => "?").join(", ");
293
- const rows = db
294
- .prepare(
295
- `
296
- select
297
- t.id,
298
- t.created_at as createdAt,
299
- t.reply_to_id as replyToId,
300
- coalesce(edge.raw_json, '{}') as rawJson
301
- from tweets t
302
- left join tweet_account_edges edge
303
- on edge.tweet_id = t.id
304
- and edge.account_id = ?
305
- and edge.kind = 'mention'
306
- where t.id in (${placeholders})
307
- and (
308
- edge.tweet_id is not null
309
- or (t.kind = 'mention' and t.account_id = ?)
310
- )
311
- order by t.created_at desc
312
- limit ?
313
- `,
314
- )
315
- .all(accountId, ...ids, accountId, limit) as Array<{
316
- id: string;
317
- createdAt: string;
318
- replyToId: string | null;
319
- rawJson: string | null;
320
- }>;
321
-
322
- return rows.map((row) => {
323
- const rawTweet = parseRawTweet(row.rawJson);
324
- return {
325
- id: row.id,
326
- replyToId:
327
- row.replyToId ?? (rawTweet ? getReplyToId(rawTweet) : undefined),
328
- conversationId:
329
- typeof rawTweet?.conversation_id === "string"
330
- ? rawTweet.conversation_id
331
- : undefined,
332
- rawTweet,
333
- };
334
- });
335
- }
336
-
337
- function mergeMentionThreadIntoLocalStore({
338
- db,
339
- accountId,
340
- accountHandle,
341
- mentionIds,
342
- payload,
343
- source = "bird",
344
- writeThreadContextEdges = false,
345
- }: {
346
- db: Database;
347
- accountId: string;
348
- accountHandle: string;
349
- mentionIds: Set<string>;
350
- payload: XurlMentionsResponse;
351
- source?: "bird" | "xurl";
352
- writeThreadContextEdges?: boolean;
353
- }) {
354
- const usersById = new Map(
355
- (payload.includes?.users ?? []).map((user) => [user.id, user]),
356
- );
357
- const upsertTweet = db.prepare(
358
- `
359
- insert into tweets (
360
- id, account_id, author_profile_id, kind, text, created_at,
361
- is_replied, reply_to_id, like_count, media_count, bookmarked, liked,
362
- entities_json, media_json, quoted_tweet_id
363
- ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, 0, ?, ?, null)
364
- on conflict(id) do update set
365
- account_id = excluded.account_id,
366
- author_profile_id = excluded.author_profile_id,
367
- kind = case
368
- when tweets.kind in ('authored', 'home', 'mention') then tweets.kind
369
- when excluded.kind in ('authored', 'home', 'mention') then excluded.kind
370
- else coalesce(nullif(tweets.kind, ''), excluded.kind)
371
- end,
372
- text = excluded.text,
373
- created_at = excluded.created_at,
374
- is_replied = max(tweets.is_replied, excluded.is_replied),
375
- reply_to_id = coalesce(excluded.reply_to_id, tweets.reply_to_id),
376
- like_count = excluded.like_count,
377
- media_count = max(tweets.media_count, excluded.media_count),
378
- entities_json = excluded.entities_json,
379
- media_json = case
380
- when excluded.media_json not in ('', '[]', 'null') then excluded.media_json
381
- else tweets.media_json
382
- end,
383
- bookmarked = tweets.bookmarked,
384
- liked = tweets.liked
385
- `,
386
- );
387
-
388
- db.transaction(() => {
389
- const seenAt = new Date().toISOString();
390
- for (const tweet of payload.data) {
391
- const author =
392
- usersById.get(tweet.author_id) ??
393
- ({
394
- id: tweet.author_id,
395
- username: `user_${tweet.author_id}`,
396
- name: `user_${tweet.author_id}`,
397
- } as const);
398
- const profile = usersById.has(tweet.author_id)
399
- ? upsertProfileFromXUser(db, author)
400
- : ensureStubProfileForXUser(db, tweet.author_id);
401
- const handle = author.username.toLowerCase();
402
- const kind = mentionIds.has(tweet.id)
403
- ? "mention"
404
- : handle === accountHandle
405
- ? "home"
406
- : "thread";
407
- const replyToId = getReplyToId(tweet);
408
- upsertTweet.run(
409
- tweet.id,
410
- accountId,
411
- profile.profile.id,
412
- kind,
413
- tweet.text,
414
- tweet.created_at,
415
- replyToId ? 1 : 0,
416
- replyToId ?? null,
417
- Number(tweet.public_metrics?.like_count ?? 0),
418
- countTweetMedia(tweet),
419
- JSON.stringify(tweetEntitiesFromXurl(tweet.entities)),
420
- buildMediaJsonFromIncludes(tweet, payload.includes?.media),
421
- );
422
- if (writeThreadContextEdges) {
423
- upsertTweetAccountEdge(db, {
424
- accountId,
425
- tweetId: tweet.id,
426
- kind: "thread_context",
427
- source,
428
- seenAt,
429
- rawJson: JSON.stringify(tweet),
430
- });
431
- }
432
- replaceTweetFts(db, tweet.id, tweet.text);
433
- }
434
- })();
435
- }
436
-
437
- function fetchConversationViaRecentSearchEffect({
438
- conversationId,
439
- all,
440
- maxPages,
441
- timeoutMs,
442
- deadlineMs,
443
- }: {
444
- conversationId: string;
445
- all: boolean;
446
- maxPages?: number;
447
- timeoutMs: number;
448
- deadlineMs: number;
449
- }) {
450
- return Effect.gen(function* () {
451
- const pages: XurlTweetsResponse[] = [];
452
- let nextToken: string | undefined;
453
- let pageCount = 0;
454
-
455
- do {
456
- const payload = yield* searchRecentByConversationIdEffect(
457
- conversationId,
458
- {
459
- maxResults: MAX_XURL_SEARCH_RESULTS,
460
- paginationToken: nextToken,
461
- timeoutMs: yield* trySync(() =>
462
- getRemainingThreadTimeoutMs(deadlineMs, timeoutMs),
463
- ),
464
- },
465
- );
466
- pages.push(payload);
467
- nextToken =
468
- typeof payload.meta?.next_token === "string"
469
- ? payload.meta.next_token
470
- : undefined;
471
- pageCount += 1;
472
- } while (
473
- (all || maxPages !== undefined) &&
474
- nextToken &&
475
- (maxPages === undefined || pageCount < maxPages)
476
- );
477
-
478
- const payload = mergePayloads(pages);
479
- const paginationRequested = all || maxPages !== undefined;
480
- return {
481
- payload,
482
- pages: pageCount,
483
- truncated: paginationRequested && Boolean(nextToken),
484
- generalReadTweets: payload.data.length,
485
- };
486
- });
487
- }
488
-
489
- function fetchParentChainViaXurlEffect({
490
- mention,
491
- maxDepth,
492
- timeoutMs,
493
- deadlineMs,
494
- }: {
495
- mention: LocalMention;
496
- maxDepth: number;
497
- timeoutMs: number;
498
- deadlineMs: number;
499
- }) {
500
- return Effect.gen(function* () {
501
- const pages: XurlTweetsResponse[] = [];
502
- const warnings: string[] = [];
503
- const seenTweetIds = new Set([mention.id]);
504
- let nextParentId = mention.replyToId;
505
- let fallbackDepth = 0;
506
- let generalReadTweets = 0;
507
-
508
- const rawAnchorPayload =
509
- mention.rawTweet && mention.rawTweet.id === mention.id
510
- ? ({ data: [mention.rawTweet] } satisfies XurlTweetsResponse)
511
- : undefined;
512
- let shouldUseRawAnchor = Boolean(rawAnchorPayload);
513
-
514
- if (!nextParentId) {
515
- const anchorPayload = yield* getTweetByIdEffect(mention.id, {
516
- timeoutMs: yield* trySync(() =>
517
- getRemainingThreadTimeoutMs(deadlineMs, timeoutMs),
518
- ),
519
- });
520
- pages.push(anchorPayload);
521
- generalReadTweets += anchorPayload.data.length;
522
- const anchorTweet = anchorPayload.data[0];
523
- if (anchorTweet) {
524
- shouldUseRawAnchor = false;
525
- seenTweetIds.add(anchorTweet.id);
526
- nextParentId = anchorTweet.in_reply_to_user_id
527
- ? getReplyToId(anchorTweet)
528
- : undefined;
529
- }
530
- }
531
-
532
- if (shouldUseRawAnchor && rawAnchorPayload) {
533
- pages.unshift(rawAnchorPayload);
534
- }
535
-
536
- while (nextParentId) {
537
- if (fallbackDepth >= maxDepth) {
538
- warnings.push(
539
- `fallback parent-chain depth cap reached for ${mention.id} after ${maxDepth} hops`,
540
- );
541
- break;
542
- }
543
- if (seenTweetIds.has(nextParentId)) {
544
- warnings.push(
545
- `fallback parent-chain cycle detected for ${mention.id} at ${nextParentId}`,
546
- );
547
- break;
548
- }
549
-
550
- fallbackDepth += 1;
551
- const parentPayload = yield* getTweetByIdEffect(nextParentId, {
552
- timeoutMs: yield* trySync(() =>
553
- getRemainingThreadTimeoutMs(deadlineMs, timeoutMs),
554
- ),
555
- });
556
- pages.push(parentPayload);
557
- generalReadTweets += parentPayload.data.length;
558
- const parentTweet = parentPayload.data[0];
559
- if (!parentTweet) {
560
- break;
561
- }
562
- seenTweetIds.add(parentTweet.id);
563
- nextParentId = parentTweet.in_reply_to_user_id
564
- ? getReplyToId(parentTweet)
565
- : undefined;
566
- }
567
-
568
- const payload = mergePayloads(pages);
569
- return {
570
- payload,
571
- fallbackDepth,
572
- warnings,
573
- generalReadTweets,
574
- };
575
- });
576
- }
577
-
578
- function findMissingAncestorId(
579
- mention: LocalMention,
580
- payload: XurlMentionsResponse,
581
- ) {
582
- const tweetsById = new Map(payload.data.map((tweet) => [tweet.id, tweet]));
583
- const seenTweetIds = new Set<string>([mention.id]);
584
- const anchorTweet = tweetsById.get(mention.id) ?? mention.rawTweet;
585
- let nextParentId = anchorTweet
586
- ? getReplyToId(anchorTweet)
587
- : mention.replyToId;
588
-
589
- while (nextParentId) {
590
- if (seenTweetIds.has(nextParentId)) {
591
- return undefined;
592
- }
593
- const parentTweet = tweetsById.get(nextParentId);
594
- if (!parentTweet) {
595
- return nextParentId;
596
- }
597
- seenTweetIds.add(parentTweet.id);
598
- nextParentId = parentTweet.in_reply_to_user_id
599
- ? getReplyToId(parentTweet)
600
- : undefined;
601
- }
602
-
603
- if (
604
- mention.conversationId &&
605
- mention.conversationId !== mention.id &&
606
- !tweetsById.has(mention.conversationId)
607
- ) {
608
- return mention.conversationId;
609
- }
610
-
611
- return undefined;
612
- }
613
-
614
- function fetchThreadContextViaXurlEffect({
615
- mention,
616
- all,
617
- maxPages,
618
- maxFallbackDepth,
619
- timeoutMs,
620
- }: {
621
- mention: LocalMention;
622
- all: boolean;
623
- maxPages?: number;
624
- maxFallbackDepth: number;
625
- timeoutMs: number;
626
- }) {
627
- return Effect.gen(function* () {
628
- const deadlineMs = Date.now() + timeoutMs;
629
- if (!mention.conversationId) {
630
- if (mention.replyToId) {
631
- const fallback = yield* fetchParentChainViaXurlEffect({
632
- mention,
633
- maxDepth: maxFallbackDepth,
634
- timeoutMs,
635
- deadlineMs,
636
- });
637
- return {
638
- strategy: "parent_walk" as const,
639
- pages: 0,
640
- truncated: false,
641
- payload: fallback.payload,
642
- fallbackDepth: fallback.fallbackDepth,
643
- generalReadTweets: fallback.generalReadTweets,
644
- warnings: [
645
- `missing conversation_id for ${mention.id}; used parent walk`,
646
- ...fallback.warnings,
647
- ],
648
- };
649
- }
650
- return {
651
- strategy: "skipped:no_conversation_id" as const,
652
- payload: { data: [] } satisfies XurlMentionsResponse,
653
- pages: 0,
654
- fallbackDepth: 0,
655
- generalReadTweets: 0,
656
- warnings: [`skipped ${mention.id}: missing conversation_id`],
657
- truncated: false,
658
- };
659
- }
660
-
661
- const search = yield* fetchConversationViaRecentSearchEffect({
662
- conversationId: mention.conversationId,
663
- all,
664
- maxPages,
665
- timeoutMs,
666
- deadlineMs,
667
- });
668
- if (search.payload.data.length > 0) {
669
- const missingAncestorId = findMissingAncestorId(mention, search.payload);
670
- if (missingAncestorId) {
671
- const fallback = yield* fetchParentChainViaXurlEffect({
672
- mention,
673
- maxDepth: maxFallbackDepth,
674
- timeoutMs,
675
- deadlineMs,
676
- });
677
- return {
678
- strategy: "conversation_search+parent_walk" as const,
679
- pages: search.pages,
680
- truncated: search.truncated,
681
- payload: mergePayloads([search.payload, fallback.payload]),
682
- fallbackDepth: fallback.fallbackDepth,
683
- generalReadTweets:
684
- search.generalReadTweets + fallback.generalReadTweets,
685
- warnings: [
686
- `recent search missed ancestor ${missingAncestorId} for conversation ${mention.conversationId}; used parent walk`,
687
- ...fallback.warnings,
688
- ],
689
- };
690
- }
691
- return {
692
- strategy: "conversation_search" as const,
693
- fallbackDepth: 0,
694
- warnings: [] as string[],
695
- ...search,
696
- };
697
- }
698
-
699
- const fallback = yield* fetchParentChainViaXurlEffect({
700
- mention,
701
- maxDepth: maxFallbackDepth,
702
- timeoutMs,
703
- deadlineMs,
704
- });
705
- return {
706
- strategy: "parent_walk" as const,
707
- pages: search.pages,
708
- truncated: search.truncated,
709
- payload: fallback.payload,
710
- fallbackDepth: fallback.fallbackDepth,
711
- generalReadTweets: search.generalReadTweets + fallback.generalReadTweets,
712
- warnings: [
713
- `recent search returned no tweets for conversation ${mention.conversationId}; used parent walk`,
714
- ...fallback.warnings,
715
- ],
716
- };
717
- });
718
- }
719
-
720
- export function syncMentionThreadsEffect({
721
- account,
722
- mode = DEFAULT_MODE,
723
- limit = DEFAULT_LIMIT,
724
- tweetIds,
725
- delayMs = DEFAULT_DELAY_MS,
726
- timeoutMs = DEFAULT_TIMEOUT_MS,
727
- all = false,
728
- maxPages,
729
- onProgress,
730
- }: SyncMentionThreadsOptions) {
731
- return Effect.gen(function* () {
732
- const parsedMode = yield* trySync(() => parseMode(mode));
733
- const parsedLimit = yield* trySync(() =>
734
- assertPositiveInteger(limit, "--limit"),
735
- );
736
- const parsedDelayMs =
737
- (yield* trySync(() => parseNonNegativeInteger(delayMs, "--delay-ms"))) ??
738
- 0;
739
- const parsedTimeoutMs = yield* trySync(() =>
740
- assertPositiveInteger(timeoutMs, "--timeout-ms"),
741
- );
742
- const parsedMaxPages = yield* trySync(() =>
743
- parseNonNegativeInteger(maxPages, "--max-pages"),
744
- );
745
- const db = yield* trySync(() => getNativeDb());
746
- const resolvedAccount = yield* trySync(() => resolveAccount(db, account));
747
- const mentions = yield* trySync(() =>
748
- tweetIds
749
- ? listMentionsByIds(
750
- db,
751
- resolvedAccount.accountId,
752
- tweetIds,
753
- parsedLimit,
754
- )
755
- : listRecentMentions(db, resolvedAccount.accountId, parsedLimit),
756
- );
757
- const mentionIds = mentions.map((mention) => mention.id);
758
- const mentionIdSet = new Set(mentionIds);
759
- const results: Array<{
760
- tweetId: string;
761
- conversationId?: string | null;
762
- ok: boolean;
763
- count: number;
764
- strategy?: string;
765
- pages?: number;
766
- fallbackDepth?: number;
767
- truncated?: boolean;
768
- warnings?: string[];
769
- error?: string;
770
- }> = [];
771
- let mergedTweets = 0;
772
- let generalReadTweets = 0;
773
- const uniqueTweetIds = new Set<string>();
774
- const warnings: string[] = [];
775
-
776
- for (const [index, mention] of mentions.entries()) {
777
- if (index > 0 && parsedDelayMs > 0) {
778
- yield* Effect.sleep(parsedDelayMs);
779
- }
780
- const fetchEffect: Effect.Effect<ThreadFetchResult, unknown, never> =
781
- parsedMode === "bird"
782
- ? listThreadViaBirdEffect({
783
- tweetId: mention.id,
784
- all,
785
- maxPages: parsedMaxPages,
786
- timeoutMs: parsedTimeoutMs,
787
- }).pipe(
788
- Effect.map((payload) => ({
789
- strategy: "bird" as const,
790
- payload,
791
- pages: undefined,
792
- fallbackDepth: undefined,
793
- generalReadTweets: 0,
794
- truncated: undefined,
795
- warnings: [] as string[],
796
- })),
797
- )
798
- : fetchThreadContextViaXurlEffect({
799
- mention,
800
- all,
801
- maxPages: parsedMaxPages,
802
- maxFallbackDepth: DEFAULT_FALLBACK_DEPTH,
803
- timeoutMs: parsedTimeoutMs,
804
- });
805
- const fetched = yield* fetchEffect.pipe(
806
- Effect.flatMap((fetchResult) =>
807
- trySync(() =>
808
- mergeMentionThreadIntoLocalStore({
809
- db,
810
- accountId: resolvedAccount.accountId,
811
- accountHandle: resolvedAccount.handle,
812
- mentionIds: mentionIdSet,
813
- payload: fetchResult.payload,
814
- source: parsedMode,
815
- writeThreadContextEdges: parsedMode === "xurl",
816
- }),
817
- ).pipe(Effect.as(fetchResult)),
818
- ),
819
- Effect.map((fetchResult) => ({ ok: true as const, fetchResult })),
820
- Effect.catchAll((error) =>
821
- Effect.succeed({ ok: false as const, error }),
822
- ),
823
- );
824
-
825
- if (!fetched.ok) {
826
- results.push({
827
- tweetId: mention.id,
828
- conversationId: mention.conversationId ?? null,
829
- ok: false,
830
- count: 0,
831
- strategy: parsedMode,
832
- error:
833
- fetched.error instanceof Error
834
- ? fetched.error.message
835
- : String(fetched.error),
836
- });
837
- yield* Effect.sync(() =>
838
- onProgress?.({
839
- source: parsedMode,
840
- processed: index + 1,
841
- total: mentions.length,
842
- fetched: uniqueTweetIds.size,
843
- done: index + 1 === mentions.length,
844
- }),
845
- );
846
- continue;
847
- }
848
-
849
- const { fetchResult } = fetched;
850
- const { payload } = fetchResult;
851
- for (const tweet of payload.data) {
852
- uniqueTweetIds.add(tweet.id);
853
- }
854
- mergedTweets += payload.data.length;
855
- generalReadTweets += fetchResult.generalReadTweets;
856
- warnings.push(...fetchResult.warnings);
857
- results.push({
858
- tweetId: mention.id,
859
- conversationId: mention.conversationId ?? null,
860
- ok: true,
861
- count: payload.data.length,
862
- strategy: fetchResult.strategy,
863
- pages: fetchResult.pages,
864
- fallbackDepth: fetchResult.fallbackDepth,
865
- truncated: fetchResult.truncated,
866
- warnings:
867
- fetchResult.warnings.length > 0 ? fetchResult.warnings : undefined,
868
- });
869
- yield* Effect.sync(() =>
870
- onProgress?.({
871
- source: parsedMode,
872
- processed: index + 1,
873
- total: mentions.length,
874
- fetched: uniqueTweetIds.size,
875
- done: index + 1 === mentions.length,
876
- }),
877
- );
878
- }
879
-
880
- const failures = results.filter((item) => !item.ok);
881
- const skipped = results.filter((item) =>
882
- item.strategy?.startsWith("skipped:"),
883
- );
884
- const partial = results.some((item) => item.truncated === true);
885
- return {
886
- ok: true,
887
- source: parsedMode,
888
- accountId: resolvedAccount.accountId,
889
- mentions: mentionIds.length,
890
- threads: results.length,
891
- succeeded: results.length - failures.length - skipped.length,
892
- skipped: skipped.length,
893
- failed: failures.length,
894
- mergedTweets,
895
- uniqueTweets: uniqueTweetIds.size,
896
- generalReadTweets: parsedMode === "xurl" ? generalReadTweets : 0,
897
- partial,
898
- options: {
899
- mode: parsedMode,
900
- limit: parsedLimit,
901
- delayMs: parsedDelayMs,
902
- timeoutMs: parsedTimeoutMs,
903
- all,
904
- maxPages: parsedMaxPages ?? null,
905
- maxFallbackDepth: DEFAULT_FALLBACK_DEPTH,
906
- tweetIds: tweetIds ?? null,
907
- },
908
- results,
909
- failures,
910
- warnings,
911
- };
912
- });
913
- }
914
-
915
- export function syncMentionThreads(options: SyncMentionThreadsOptions) {
916
- return runEffectPromise(syncMentionThreadsEffect(options));
917
- }