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,77 +0,0 @@
1
- import { Effect } from "effect";
2
-
3
- import { runEffectPromise, tryPromise } from "./effect-runtime";
4
- import { resolveProfile } from "./moderation-target";
5
- import type { ProfileRepliesResponse, XurlReferencedTweet } from "./types";
6
- import { listUserTweets } from "./xurl";
7
-
8
- function getReplyTargetId(references?: XurlReferencedTweet[]) {
9
- return references?.find((item) => item.type === "replied_to")?.id;
10
- }
11
-
12
- function getScanSize(limit: number) {
13
- return Math.min(Math.max(limit * 3, 20), 100);
14
- }
15
-
16
- export function inspectProfileReplies(
17
- query: string,
18
- { limit = 12 }: { limit?: number } = {},
19
- ): Promise<ProfileRepliesResponse> {
20
- return runEffectPromise(inspectProfileRepliesEffect(query, { limit }));
21
- }
22
-
23
- export function inspectProfileRepliesEffect(
24
- query: string,
25
- { limit = 12 }: { limit?: number } = {},
26
- ): Effect.Effect<ProfileRepliesResponse, unknown> {
27
- return Effect.gen(function* () {
28
- const resolved = yield* tryPromise(() => resolveProfile(query));
29
- const externalUserId = resolved.externalUserId;
30
- if (!externalUserId) {
31
- return yield* Effect.fail(
32
- new Error(`Profile has no external Twitter user id: ${query}`),
33
- );
34
- }
35
-
36
- const timeline = yield* tryPromise(() =>
37
- listUserTweets(externalUserId, {
38
- maxResults: getScanSize(limit),
39
- excludeRetweets: true,
40
- }),
41
- );
42
- const items = timeline.items
43
- .map((tweet) => {
44
- const replyToTweetId = getReplyTargetId(tweet.referenced_tweets);
45
- if (!replyToTweetId) {
46
- return null;
47
- }
48
-
49
- return {
50
- id: tweet.id,
51
- text: tweet.text,
52
- createdAt: tweet.created_at,
53
- conversationId: tweet.conversation_id,
54
- replyToTweetId,
55
- likeCount: Number(tweet.public_metrics?.like_count ?? 0),
56
- replyCount: Number(tweet.public_metrics?.reply_count ?? 0),
57
- retweetCount: Number(tweet.public_metrics?.retweet_count ?? 0),
58
- quoteCount: Number(tweet.public_metrics?.quote_count ?? 0),
59
- bookmarkCount: Number(tweet.public_metrics?.bookmark_count ?? 0),
60
- impressionCount: Number(tweet.public_metrics?.impression_count ?? 0),
61
- };
62
- })
63
- .filter((item): item is NonNullable<typeof item> => item !== null)
64
- .slice(0, limit);
65
-
66
- return {
67
- profile: resolved.profile,
68
- externalUserId,
69
- items,
70
- meta: {
71
- scannedCount: timeline.items.length,
72
- returnedCount: items.length,
73
- nextToken: timeline.nextToken,
74
- },
75
- };
76
- });
77
- }
@@ -1,650 +0,0 @@
1
- import { Effect } from "effect";
2
-
3
- import { getNativeDb } from "./db";
4
- import {
5
- lookupProfileViaBirdEffect,
6
- lookupProfilesViaBirdEffect,
7
- } from "./bird";
8
- import { runEffectPromise, tryPromise } from "./effect-runtime";
9
- import { readSyncCache, writeSyncCache } from "./sync-cache";
10
- import {
11
- hydrateProfileAffiliationOrganizationsEffect,
12
- type ProfileAffiliationHydrationResult,
13
- } from "./profile-affiliation-hydration";
14
- import type { ProfileRecord, XurlMentionUser } from "./types";
15
- import { getExternalUserId, upsertProfileFromXUser } from "./x-profile";
16
- import { lookupUsersByHandles, lookupUsersByIds } from "./xurl";
17
-
18
- const PROFILE_CACHE_TTL_MS = 30 * 24 * 60 * 60 * 1000;
19
- const PROFILE_NEGATIVE_CACHE_TTL_MS = 24 * 60 * 60 * 1000;
20
-
21
- type ProfileLookupStatus = "hit" | "miss" | "error";
22
- type ProfileLookupSource = "local" | "cache" | "bird" | "xurl";
23
-
24
- interface CachedProfileLookup {
25
- status: ProfileLookupStatus;
26
- source: Exclude<ProfileLookupSource, "local" | "cache">;
27
- user?: XurlMentionUser;
28
- error?: string;
29
- }
30
-
31
- function toError(error: unknown) {
32
- return error instanceof Error ? error : new Error(String(error));
33
- }
34
-
35
- function trySync<T>(try_: () => T) {
36
- return Effect.try({
37
- try: try_,
38
- catch: toError,
39
- });
40
- }
41
-
42
- export interface ResolveProfilesOptions {
43
- refresh?: boolean;
44
- maxAgeMs?: number;
45
- negativeMaxAgeMs?: number;
46
- xurlFallback?: boolean;
47
- }
48
-
49
- export interface ProfileResolveResult {
50
- profileId: string;
51
- externalUserId: string | null;
52
- status: ProfileLookupStatus;
53
- source: ProfileLookupSource | "negative-cache";
54
- profile?: ProfileRecord;
55
- affiliationHydration?: ProfileAffiliationHydrationResult;
56
- error?: string;
57
- }
58
-
59
- export interface HandleProfileResolveResult {
60
- handle: string;
61
- status: ProfileLookupStatus;
62
- source: Exclude<ProfileLookupSource, "local">;
63
- profile?: ProfileRecord;
64
- error?: string;
65
- }
66
-
67
- function toProfile(row: Record<string, unknown>): ProfileRecord {
68
- const followingCount = Number(row.following_count ?? 0);
69
- let entities: Record<string, unknown> | undefined;
70
- if (typeof row.entities_json === "string" && row.entities_json.length > 0) {
71
- try {
72
- const parsed = JSON.parse(row.entities_json) as unknown;
73
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
74
- entities = parsed as Record<string, unknown>;
75
- }
76
- } catch {
77
- entities = undefined;
78
- }
79
- }
80
- return {
81
- id: String(row.id),
82
- handle: String(row.handle),
83
- displayName: String(row.display_name),
84
- bio: String(row.bio),
85
- followersCount: Number(row.followers_count),
86
- ...(Number.isFinite(followingCount) ? { followingCount } : {}),
87
- avatarHue: Number(row.avatar_hue),
88
- avatarUrl:
89
- typeof row.avatar_url === "string" ? String(row.avatar_url) : undefined,
90
- ...(typeof row.location === "string" && row.location.length > 0
91
- ? { location: row.location }
92
- : {}),
93
- ...(typeof row.url === "string" && row.url.length > 0
94
- ? { url: row.url }
95
- : {}),
96
- ...(typeof row.verified_type === "string" && row.verified_type.length > 0
97
- ? { verifiedType: row.verified_type }
98
- : {}),
99
- ...(entities ? { entities } : {}),
100
- createdAt: String(row.created_at),
101
- };
102
- }
103
-
104
- function getProfile(profileId: string) {
105
- const row = getNativeDb()
106
- .prepare(
107
- `
108
- select id, handle, display_name, bio, followers_count, following_count,
109
- avatar_hue, avatar_url, location, url, verified_type, entities_json, created_at
110
- from profiles
111
- where id = ?
112
- `,
113
- )
114
- .get(profileId) as Record<string, unknown> | undefined;
115
-
116
- return row ? toProfile(row) : null;
117
- }
118
-
119
- function isPlaceholderProfile(profile: ProfileRecord) {
120
- const externalUserId = getExternalUserId(profile.id);
121
- if (!externalUserId) {
122
- return false;
123
- }
124
- return (
125
- profile.handle === `id${externalUserId}` ||
126
- profile.handle === `user_${externalUserId}` ||
127
- profile.displayName === `id${externalUserId}` ||
128
- profile.displayName === `user_${externalUserId}` ||
129
- profile.bio === `Imported from archive user ${externalUserId}` ||
130
- (profile.followersCount === 0 &&
131
- profile.bio.startsWith("Imported from archive user "))
132
- );
133
- }
134
-
135
- function isFresh(updatedAt: string, maxAgeMs: number) {
136
- return Date.now() - new Date(updatedAt).getTime() <= maxAgeMs;
137
- }
138
-
139
- function cacheKeyForUserId(externalUserId: string) {
140
- return `profile:lookup:user-id:${externalUserId}`;
141
- }
142
-
143
- function writeProfileLookupCache(
144
- externalUserId: string,
145
- value: CachedProfileLookup,
146
- ) {
147
- writeSyncCache(cacheKeyForUserId(externalUserId), value);
148
- }
149
-
150
- function updateConversationTitles(profile: ProfileRecord, db = getNativeDb()) {
151
- db.prepare(
152
- `
153
- update dm_conversations
154
- set title = ?
155
- where participant_profile_id = ?
156
- `,
157
- ).run(profile.displayName || profile.handle, profile.id);
158
- }
159
-
160
- function lookupViaXurlEffect(externalUserId: string) {
161
- return Effect.gen(function* () {
162
- const [user] = yield* tryPromise(() => lookupUsersByIds([externalUserId]));
163
- return user ?? null;
164
- });
165
- }
166
-
167
- function normalizeHandle(value: string) {
168
- return value.trim().replace(/^@/, "").toLowerCase();
169
- }
170
-
171
- function fetchProfileUserEffect(
172
- externalUserId: string,
173
- xurlFallback: boolean,
174
- ): Effect.Effect<CachedProfileLookup, never> {
175
- return Effect.gen(function* () {
176
- const birdResult = yield* lookupProfileViaBirdEffect(externalUserId).pipe(
177
- Effect.map((user) => ({ ok: true as const, user })),
178
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
179
- );
180
- if (birdResult.ok) {
181
- const birdUser = birdResult.user;
182
- if (birdUser) {
183
- return { status: "hit", source: "bird", user: birdUser };
184
- }
185
- } else if (!xurlFallback) {
186
- return {
187
- status: "error",
188
- source: "bird",
189
- error:
190
- birdResult.error instanceof Error
191
- ? birdResult.error.message
192
- : String(birdResult.error),
193
- };
194
- }
195
-
196
- if (!xurlFallback) {
197
- return { status: "miss", source: "bird" };
198
- }
199
-
200
- const xurlResult = yield* lookupViaXurlEffect(externalUserId).pipe(
201
- Effect.map((user) => ({ ok: true as const, user })),
202
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
203
- );
204
- if (xurlResult.ok) {
205
- const xurlUser = xurlResult.user;
206
- return xurlUser
207
- ? { status: "hit", source: "xurl", user: xurlUser }
208
- : { status: "miss", source: "xurl" };
209
- }
210
- return {
211
- status: "error",
212
- source: "xurl",
213
- error:
214
- xurlResult.error instanceof Error
215
- ? xurlResult.error.message
216
- : String(xurlResult.error),
217
- };
218
- });
219
- }
220
-
221
- function fetchProfileUsersEffect(
222
- externalUserIds: string[],
223
- xurlFallback: boolean,
224
- ) {
225
- return Effect.gen(function* () {
226
- const uniqueIds = Array.from(new Set(externalUserIds));
227
- const results = new Map<string, CachedProfileLookup>();
228
- let unresolved = uniqueIds;
229
-
230
- const birdResult = yield* lookupProfilesViaBirdEffect(uniqueIds).pipe(
231
- Effect.map((items) => ({ ok: true as const, items })),
232
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
233
- );
234
- if (birdResult.ok) {
235
- const birdResults = birdResult.items;
236
- for (const result of birdResults) {
237
- const externalUserId = result.target;
238
- if (result.user) {
239
- results.set(externalUserId, {
240
- status: "hit",
241
- source: "bird",
242
- user: result.user,
243
- });
244
- } else if (result.error && !xurlFallback) {
245
- results.set(externalUserId, {
246
- status: "error",
247
- source: "bird",
248
- error: result.error,
249
- });
250
- }
251
- }
252
- unresolved = uniqueIds.filter((id) => !results.has(id));
253
- } else if (!xurlFallback) {
254
- for (const externalUserId of uniqueIds) {
255
- results.set(externalUserId, {
256
- status: "error",
257
- source: "bird",
258
- error:
259
- birdResult.error instanceof Error
260
- ? birdResult.error.message
261
- : String(birdResult.error),
262
- });
263
- }
264
- return results;
265
- }
266
-
267
- if (unresolved.length === 0) {
268
- return results;
269
- }
270
- if (!xurlFallback) {
271
- for (const externalUserId of unresolved) {
272
- results.set(externalUserId, { status: "miss", source: "bird" });
273
- }
274
- return results;
275
- }
276
-
277
- const xurlResult = yield* tryPromise(() =>
278
- lookupUsersByIds(unresolved),
279
- ).pipe(
280
- Effect.map((users) => ({ ok: true as const, users })),
281
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
282
- );
283
- if (xurlResult.ok) {
284
- const xurlUsers = xurlResult.users;
285
- const usersById = new Map(
286
- xurlUsers.map((user) => [String(user.id), user]),
287
- );
288
- for (const externalUserId of unresolved) {
289
- const user = usersById.get(externalUserId);
290
- results.set(
291
- externalUserId,
292
- user
293
- ? { status: "hit", source: "xurl", user }
294
- : { status: "miss", source: "xurl" },
295
- );
296
- }
297
- } else {
298
- for (const externalUserId of unresolved) {
299
- results.set(externalUserId, {
300
- status: "error",
301
- source: "xurl",
302
- error:
303
- xurlResult.error instanceof Error
304
- ? xurlResult.error.message
305
- : String(xurlResult.error),
306
- });
307
- }
308
- }
309
-
310
- return results;
311
- });
312
- }
313
-
314
- export function resolveProfilesForIdsEffect(
315
- profileIds: string[],
316
- options: ResolveProfilesOptions = {},
317
- ): Effect.Effect<ProfileResolveResult[], unknown> {
318
- return Effect.gen(function* () {
319
- const db = yield* trySync(() => getNativeDb());
320
- const maxAgeMs = options.maxAgeMs ?? PROFILE_CACHE_TTL_MS;
321
- const negativeMaxAgeMs =
322
- options.negativeMaxAgeMs ?? PROFILE_NEGATIVE_CACHE_TTL_MS;
323
- const xurlFallback = options.xurlFallback ?? true;
324
- const ordered: Array<
325
- | { kind: "ready"; result: ProfileResolveResult }
326
- | { kind: "pending"; profileId: string; externalUserId: string }
327
- > = [];
328
-
329
- for (const profileId of Array.from(new Set(profileIds))) {
330
- const externalUserId = getExternalUserId(profileId);
331
- if (!externalUserId) {
332
- ordered.push({
333
- kind: "ready",
334
- result: {
335
- profileId,
336
- externalUserId: null,
337
- status: "miss",
338
- source: "local",
339
- },
340
- });
341
- continue;
342
- }
343
-
344
- const localProfile = yield* trySync(() => getProfile(profileId));
345
- if (
346
- localProfile &&
347
- !options.refresh &&
348
- !isPlaceholderProfile(localProfile)
349
- ) {
350
- ordered.push({
351
- kind: "ready",
352
- result: {
353
- profileId,
354
- externalUserId,
355
- status: "hit",
356
- source: "local",
357
- profile: localProfile,
358
- },
359
- });
360
- continue;
361
- }
362
-
363
- const cached = yield* trySync(() =>
364
- readSyncCache<CachedProfileLookup>(cacheKeyForUserId(externalUserId)),
365
- );
366
- if (cached && !options.refresh) {
367
- const maxAge =
368
- cached.value.status === "hit" ? maxAgeMs : negativeMaxAgeMs;
369
- if (isFresh(cached.updatedAt, maxAge)) {
370
- if (cached.value.status === "hit" && cached.value.user) {
371
- const resolved = yield* trySync(() => {
372
- const resolved = upsertProfileFromXUser(db, cached.value.user!);
373
- updateConversationTitles(resolved.profile, db);
374
- return resolved;
375
- });
376
- ordered.push({
377
- kind: "ready",
378
- result: {
379
- profileId: resolved.profile.id,
380
- externalUserId,
381
- status: "hit",
382
- source: "cache",
383
- profile: resolved.profile,
384
- },
385
- });
386
- continue;
387
- }
388
- ordered.push({
389
- kind: "ready",
390
- result: {
391
- profileId,
392
- externalUserId,
393
- status: cached.value.status,
394
- source: "negative-cache",
395
- error: cached.value.error,
396
- },
397
- });
398
- continue;
399
- }
400
- }
401
-
402
- ordered.push({ kind: "pending", profileId, externalUserId });
403
- }
404
-
405
- const pendingExternalIds = ordered.flatMap((item) =>
406
- item.kind === "pending" ? [item.externalUserId] : [],
407
- );
408
- const fetchedByExternalId =
409
- pendingExternalIds.length > 1
410
- ? yield* fetchProfileUsersEffect(pendingExternalIds, xurlFallback)
411
- : new Map<string, CachedProfileLookup>();
412
-
413
- const results: ProfileResolveResult[] = [];
414
- for (const item of ordered) {
415
- if (item.kind === "ready") {
416
- results.push(item.result);
417
- continue;
418
- }
419
- const fetched =
420
- fetchedByExternalId.get(item.externalUserId) ??
421
- (yield* fetchProfileUserEffect(item.externalUserId, xurlFallback));
422
- yield* trySync(() =>
423
- writeProfileLookupCache(item.externalUserId, fetched),
424
- );
425
- if (fetched.status === "hit" && fetched.user) {
426
- const resolved = yield* trySync(() =>
427
- upsertProfileFromXUser(db, fetched.user!),
428
- );
429
- const affiliationHydration =
430
- yield* hydrateProfileAffiliationOrganizationsEffect(
431
- db,
432
- resolved.profile.id,
433
- );
434
- yield* trySync(() => updateConversationTitles(resolved.profile, db));
435
- results.push({
436
- profileId: resolved.profile.id,
437
- externalUserId: item.externalUserId,
438
- status: "hit",
439
- source: fetched.source,
440
- profile: resolved.profile,
441
- ...(affiliationHydration.checked > 0 ? { affiliationHydration } : {}),
442
- });
443
- continue;
444
- }
445
- results.push({
446
- profileId: item.profileId,
447
- externalUserId: item.externalUserId,
448
- status: fetched.status,
449
- source: fetched.source,
450
- error: fetched.error,
451
- });
452
- }
453
-
454
- return results;
455
- });
456
- }
457
-
458
- export function resolveProfilesForIds(
459
- profileIds: string[],
460
- options: ResolveProfilesOptions = {},
461
- ): Promise<ProfileResolveResult[]> {
462
- return runEffectPromise(resolveProfilesForIdsEffect(profileIds, options));
463
- }
464
-
465
- export function resolveProfilesForHandlesEffect(
466
- handles: string[],
467
- options: Pick<ResolveProfilesOptions, "xurlFallback"> = {},
468
- ): Effect.Effect<HandleProfileResolveResult[], unknown> {
469
- return Effect.gen(function* () {
470
- const db = yield* trySync(() => getNativeDb());
471
- const xurlFallback = options.xurlFallback ?? true;
472
- const targets = Array.from(
473
- new Set(
474
- handles.map(normalizeHandle).filter((handle) => handle.length > 0),
475
- ),
476
- );
477
- if (targets.length === 0) {
478
- return [];
479
- }
480
-
481
- const results = new Map<string, HandleProfileResolveResult>();
482
- let unresolved = targets;
483
-
484
- const birdResult = yield* lookupProfilesViaBirdEffect(targets).pipe(
485
- Effect.map((items) => ({ ok: true as const, items })),
486
- Effect.catchAll((error) => Effect.succeed({ ok: false as const, error })),
487
- );
488
- if (birdResult.ok) {
489
- const birdResults = birdResult.items;
490
- for (const item of birdResults) {
491
- const handle = normalizeHandle(item.target);
492
- if (item.user) {
493
- const resolved = yield* trySync(() => {
494
- const resolved = upsertProfileFromXUser(db, item.user!);
495
- updateConversationTitles(resolved.profile, db);
496
- return resolved;
497
- });
498
- results.set(handle, {
499
- handle,
500
- status: "hit",
501
- source: "bird",
502
- profile: resolved.profile,
503
- });
504
- } else if (item.error && !xurlFallback) {
505
- results.set(handle, {
506
- handle,
507
- status: "error",
508
- source: "bird",
509
- error: item.error,
510
- });
511
- }
512
- }
513
- unresolved = targets.filter((handle) => !results.has(handle));
514
- } else if (!xurlFallback) {
515
- for (const handle of targets) {
516
- results.set(handle, {
517
- handle,
518
- status: "error",
519
- source: "bird",
520
- error:
521
- birdResult.error instanceof Error
522
- ? birdResult.error.message
523
- : String(birdResult.error),
524
- });
525
- }
526
- unresolved = [];
527
- }
528
-
529
- if (unresolved.length > 0 && xurlFallback) {
530
- const xurlResult = yield* tryPromise(() =>
531
- lookupUsersByHandles(unresolved),
532
- ).pipe(
533
- Effect.map((users) => ({ ok: true as const, users })),
534
- Effect.catchAll((error) =>
535
- Effect.succeed({ ok: false as const, error }),
536
- ),
537
- );
538
- if (xurlResult.ok) {
539
- const users = xurlResult.users;
540
- const usersByHandle = new Map(
541
- users.map((user) => [
542
- normalizeHandle(String(user.username ?? "")),
543
- user,
544
- ]),
545
- );
546
- for (const handle of unresolved) {
547
- const user = usersByHandle.get(handle);
548
- if (user) {
549
- const resolved = yield* trySync(() => {
550
- const resolved = upsertProfileFromXUser(db, user);
551
- updateConversationTitles(resolved.profile, db);
552
- return resolved;
553
- });
554
- results.set(handle, {
555
- handle,
556
- status: "hit",
557
- source: "xurl",
558
- profile: resolved.profile,
559
- });
560
- } else {
561
- results.set(handle, {
562
- handle,
563
- status: "miss",
564
- source: "xurl",
565
- });
566
- }
567
- }
568
- } else {
569
- for (const handle of unresolved) {
570
- results.set(handle, {
571
- handle,
572
- status: "error",
573
- source: "xurl",
574
- error:
575
- xurlResult.error instanceof Error
576
- ? xurlResult.error.message
577
- : String(xurlResult.error),
578
- });
579
- }
580
- }
581
- }
582
-
583
- return targets.map(
584
- (handle) =>
585
- results.get(handle) ?? {
586
- handle,
587
- status: "miss",
588
- source: "bird",
589
- },
590
- );
591
- });
592
- }
593
-
594
- export function resolveProfilesForHandles(
595
- handles: string[],
596
- options: Pick<ResolveProfilesOptions, "xurlFallback"> = {},
597
- ): Promise<HandleProfileResolveResult[]> {
598
- return runEffectPromise(resolveProfilesForHandlesEffect(handles, options));
599
- }
600
-
601
- export function resolvePlaceholderProfilesEffect(
602
- options: ResolveProfilesOptions & { limit?: number } = {},
603
- ) {
604
- return Effect.gen(function* () {
605
- const db = yield* trySync(() => getNativeDb());
606
- const rows = yield* trySync(
607
- () =>
608
- db
609
- .prepare(
610
- `
611
- select id
612
- from profiles
613
- where id like 'profile_user_%'
614
- and (
615
- followers_count = 0
616
- or bio like 'Imported from archive user %'
617
- or handle like 'id%'
618
- or handle like 'user_%'
619
- )
620
- order by id asc
621
- limit ?
622
- `,
623
- )
624
- .all(options.limit ?? 500) as Array<{ id: string }>,
625
- );
626
-
627
- const results = yield* resolveProfilesForIdsEffect(
628
- rows.map((row) => row.id),
629
- options,
630
- );
631
- return {
632
- ok: true,
633
- requestedProfiles: rows.length,
634
- hydratedProfiles: results.filter((result) => result.status === "hit")
635
- .length,
636
- results,
637
- };
638
- });
639
- }
640
-
641
- export function resolvePlaceholderProfiles(
642
- options: ResolveProfilesOptions & { limit?: number } = {},
643
- ) {
644
- return runEffectPromise(resolvePlaceholderProfilesEffect(options));
645
- }
646
-
647
- export const __test__ = {
648
- isPlaceholderProfile,
649
- cacheKeyForUserId,
650
- };