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,860 +0,0 @@
1
- import { getNativeDb } from "./db";
2
- import type {
3
- LinkInsightItem,
4
- LinkInsightKind,
5
- LinkInsightMention,
6
- LinkInsightQuery,
7
- LinkInsightRange,
8
- LinkInsightResponse,
9
- LinkInsightSort,
10
- ProfileRecord,
11
- TweetMediaItem,
12
- } from "./types";
13
-
14
- const DEFAULT_LIMIT = 30;
15
- const DEFAULT_COMMENTS_LIMIT = 8;
16
- const TRACKING_PARAMS = new Set([
17
- "fbclid",
18
- "gclid",
19
- "igshid",
20
- "mc_cid",
21
- "mc_eid",
22
- "ref",
23
- "ref_src",
24
- ]);
25
- const VIDEO_HOST_SUFFIXES = [
26
- "youtube.com",
27
- "youtube-nocookie.com",
28
- "youtubeeducation.com",
29
- "youtubekids.com",
30
- "vimeo.com",
31
- "twitch.tv",
32
- "tiktok.com",
33
- "loom.com",
34
- ];
35
- const VIDEO_EXACT_HOSTS = new Set([
36
- "youtu.be",
37
- "clips.twitch.tv",
38
- "vm.tiktok.com",
39
- ]);
40
- const EXCLUDED_HOST_SUFFIXES = ["x.com", "twitter.com"];
41
- const EXCLUDED_EXACT_HOSTS = new Set(["t.co"]);
42
- const URL_WHITESPACE = /\s+/g;
43
- const RAW_URL_PATTERN = /https?:\/\/[^\s<>"'`]+/g;
44
- const SQL_URL_EXPRESSION =
45
- "lower(coalesce(nullif(e.final_url, ''), nullif(e.expanded_url, ''), e.short_url))";
46
-
47
- interface LinkInsightRow {
48
- source_kind: "dm" | "tweet";
49
- source_id: string;
50
- source_position: number;
51
- short_url: string;
52
- account_id: string | null;
53
- conversation_id: string | null;
54
- direction: string | null;
55
- created_at: string;
56
- expanded_url: string;
57
- final_url: string;
58
- expanded_tweet_id: string | null;
59
- expanded_handle: string | null;
60
- title: string | null;
61
- description: string | null;
62
- source_text: string;
63
- source_media_json: string | null;
64
- account_handle: string | null;
65
- source_author_id: string | null;
66
- source_author_handle: string | null;
67
- source_author_display_name: string | null;
68
- source_author_bio: string | null;
69
- source_author_followers_count: number | null;
70
- source_author_following_count: number | null;
71
- source_author_avatar_hue: number | null;
72
- source_author_avatar_url: string | null;
73
- source_author_location: string | null;
74
- source_author_url: string | null;
75
- source_author_verified_type: string | null;
76
- source_author_entities_json: string | null;
77
- source_author_created_at: string | null;
78
- dm_sender_id: string | null;
79
- dm_sender_handle: string | null;
80
- dm_sender_display_name: string | null;
81
- dm_sender_bio: string | null;
82
- dm_sender_followers_count: number | null;
83
- dm_sender_following_count: number | null;
84
- dm_sender_avatar_hue: number | null;
85
- dm_sender_avatar_url: string | null;
86
- dm_sender_location: string | null;
87
- dm_sender_url: string | null;
88
- dm_sender_verified_type: string | null;
89
- dm_sender_entities_json: string | null;
90
- dm_sender_created_at: string | null;
91
- participant_id: string | null;
92
- participant_handle: string | null;
93
- participant_display_name: string | null;
94
- participant_bio: string | null;
95
- participant_followers_count: number | null;
96
- participant_following_count: number | null;
97
- participant_avatar_hue: number | null;
98
- participant_avatar_url: string | null;
99
- participant_location: string | null;
100
- participant_url: string | null;
101
- participant_verified_type: string | null;
102
- participant_entities_json: string | null;
103
- participant_created_at: string | null;
104
- linked_text: string | null;
105
- linked_media_json: string | null;
106
- linked_author_id: string | null;
107
- linked_author_handle: string | null;
108
- linked_author_display_name: string | null;
109
- linked_author_bio: string | null;
110
- linked_author_followers_count: number | null;
111
- linked_author_following_count: number | null;
112
- linked_author_avatar_hue: number | null;
113
- linked_author_avatar_url: string | null;
114
- linked_author_location: string | null;
115
- linked_author_url: string | null;
116
- linked_author_verified_type: string | null;
117
- linked_author_entities_json: string | null;
118
- linked_author_created_at: string | null;
119
- }
120
-
121
- interface NormalizedUrl {
122
- canonicalKey: string;
123
- displayUrl: string;
124
- host: string;
125
- url: string;
126
- }
127
-
128
- interface InsightGroup {
129
- canonicalKey: string;
130
- description: string | null;
131
- displayUrl: string;
132
- firstSeenAt: string;
133
- host: string;
134
- kind: LinkInsightKind;
135
- lastSeenAt: string;
136
- mentions: LinkInsightMention[];
137
- seenMentions: Set<string>;
138
- sharers: Set<string>;
139
- sharerProfiles: Map<string, ProfileRecord>;
140
- shareCount: number;
141
- title: string | null;
142
- topSharer: ProfileRecord | null;
143
- totalInfluence: number;
144
- url: string;
145
- }
146
-
147
- const TITLE_SEGMENT_STOPWORDS = new Set([
148
- "a",
149
- "about",
150
- "blog",
151
- "events",
152
- "forum",
153
- "news",
154
- "post",
155
- "posts",
156
- "public",
157
- "story",
158
- "watch",
159
- ]);
160
-
161
- const TITLE_WORD_OVERRIDES = new Map([
162
- ["ai", "AI"],
163
- ["api", "API"],
164
- ["codex", "Codex"],
165
- ["gpt", "GPT"],
166
- ["ios", "iOS"],
167
- ["macos", "macOS"],
168
- ["openai", "OpenAI"],
169
- ["url", "URL"],
170
- ["wwdc", "WWDC"],
171
- ]);
172
-
173
- const TITLE_SMALL_WORDS = new Set([
174
- "a",
175
- "an",
176
- "and",
177
- "as",
178
- "at",
179
- "but",
180
- "by",
181
- "for",
182
- "from",
183
- "in",
184
- "into",
185
- "nor",
186
- "of",
187
- "on",
188
- "or",
189
- "per",
190
- "the",
191
- "to",
192
- "via",
193
- "vs",
194
- ]);
195
-
196
- function parseJsonField<T>(value: unknown, fallback: T): T {
197
- if (typeof value !== "string" || value.length === 0) {
198
- return fallback;
199
- }
200
- try {
201
- return JSON.parse(value) as T;
202
- } catch {
203
- return fallback;
204
- }
205
- }
206
-
207
- function getString(value: unknown) {
208
- return typeof value === "string" && value.length > 0 ? value : undefined;
209
- }
210
-
211
- function toProfile(
212
- row: LinkInsightRow,
213
- prefix: "dm_sender_" | "linked_author_" | "participant_" | "source_author_",
214
- ): ProfileRecord | null {
215
- const id = row[`${prefix}id`];
216
- if (!id) {
217
- return null;
218
- }
219
- return {
220
- id: String(id),
221
- handle: String(row[`${prefix}handle`] ?? ""),
222
- displayName: String(row[`${prefix}display_name`] ?? ""),
223
- bio: String(row[`${prefix}bio`] ?? ""),
224
- followersCount: Number(row[`${prefix}followers_count`] ?? 0),
225
- followingCount: Number(row[`${prefix}following_count`] ?? 0),
226
- avatarHue: Number(row[`${prefix}avatar_hue`] ?? 0),
227
- avatarUrl: getString(row[`${prefix}avatar_url`]),
228
- location: getString(row[`${prefix}location`]),
229
- url: getString(row[`${prefix}url`]),
230
- verifiedType: getString(row[`${prefix}verified_type`]),
231
- entities: parseJsonField<Record<string, unknown>>(
232
- row[`${prefix}entities_json`],
233
- {},
234
- ),
235
- createdAt: String(row[`${prefix}created_at`] ?? ""),
236
- };
237
- }
238
-
239
- function isHostMatch(host: string, suffixes: string[], exact: Set<string>) {
240
- const normalized = host.toLowerCase();
241
- if (exact.has(normalized)) {
242
- return true;
243
- }
244
- return suffixes.some(
245
- (suffix) => normalized === suffix || normalized.endsWith(`.${suffix}`),
246
- );
247
- }
248
-
249
- function isVideoHost(host: string) {
250
- return isHostMatch(host, VIDEO_HOST_SUFFIXES, VIDEO_EXACT_HOSTS);
251
- }
252
-
253
- function isExcludedHost(host: string) {
254
- return isHostMatch(host, EXCLUDED_HOST_SUFFIXES, EXCLUDED_EXACT_HOSTS);
255
- }
256
-
257
- function addVideoUrlPrefilter(conditions: string[]) {
258
- const predicates: string[] = [];
259
- for (const host of VIDEO_HOST_SUFFIXES) {
260
- predicates.push(`${SQL_URL_EXPRESSION} like 'http://${host}/%'`);
261
- predicates.push(`${SQL_URL_EXPRESSION} like 'https://${host}/%'`);
262
- predicates.push(`${SQL_URL_EXPRESSION} like 'http://%.${host}/%'`);
263
- predicates.push(`${SQL_URL_EXPRESSION} like 'https://%.${host}/%'`);
264
- }
265
- for (const host of VIDEO_EXACT_HOSTS) {
266
- predicates.push(`${SQL_URL_EXPRESSION} like 'http://${host}/%'`);
267
- predicates.push(`${SQL_URL_EXPRESSION} like 'https://${host}/%'`);
268
- }
269
- conditions.push(`(${predicates.join(" or ")})`);
270
- }
271
-
272
- function normalizeUrl(rawUrl: string): NormalizedUrl | null {
273
- try {
274
- const parsed = new URL(rawUrl);
275
- const hostname = parsed.hostname.toLowerCase().replace(/^www\./, "");
276
- const host = parsed.port ? `${hostname}:${parsed.port}` : hostname;
277
- if (!hostname || isExcludedHost(hostname)) {
278
- return null;
279
- }
280
-
281
- parsed.hash = "";
282
- const searchParamKeys = new Set(parsed.searchParams.keys());
283
- for (const key of searchParamKeys) {
284
- if (key.startsWith("utm_") || TRACKING_PARAMS.has(key.toLowerCase())) {
285
- parsed.searchParams.delete(key);
286
- }
287
- }
288
- parsed.searchParams.sort();
289
-
290
- let pathname = parsed.pathname || "/";
291
- if (pathname.length > 1) {
292
- pathname = pathname.replace(/\/+$/g, "");
293
- }
294
- const search = parsed.search;
295
- const canonicalKey = `${host}${pathname}${search}`;
296
- const url = `${parsed.protocol}//${host}${pathname}${search}`;
297
- const displayUrl =
298
- pathname === "/" && !search ? host : `${host}${pathname}${search}`;
299
- return { canonicalKey, displayUrl, host, url };
300
- } catch {
301
- return null;
302
- }
303
- }
304
-
305
- function isOpaqueSlugToken(value: string) {
306
- return /^(?=.*\d)[a-z0-9]{6,}$/i.test(value) || /^[a-f0-9]{8,}$/i.test(value);
307
- }
308
-
309
- function titleCaseSlugWord(word: string, index: number) {
310
- const lower = word.toLowerCase();
311
- const override = TITLE_WORD_OVERRIDES.get(lower);
312
- if (override) {
313
- return override;
314
- }
315
- if (index > 0 && TITLE_SMALL_WORDS.has(lower)) {
316
- return lower;
317
- }
318
- return `${lower.charAt(0).toUpperCase()}${lower.slice(1)}`;
319
- }
320
-
321
- function humanizeUrlSegment(segment: string) {
322
- let decoded = segment;
323
- try {
324
- decoded = decodeURIComponent(segment);
325
- } catch {
326
- // Use the raw segment when the URL contains malformed escapes.
327
- }
328
- const withoutExtension = decoded
329
- .replace(/\.(?:html?|php|aspx?)$/i, "")
330
- .trim();
331
- const words = withoutExtension
332
- .split(/[-_+.\s]+/g)
333
- .map((word) => word.trim())
334
- .filter(Boolean);
335
- while (words.length > 3 && isOpaqueSlugToken(words[words.length - 1] ?? "")) {
336
- words.pop();
337
- }
338
- if (words.length < 2) {
339
- return null;
340
- }
341
- if (!words.some((word) => /[a-z]/i.test(word))) {
342
- return null;
343
- }
344
- return words.map(titleCaseSlugWord).join(" ");
345
- }
346
-
347
- function deriveTitleFromUrl(url: string) {
348
- try {
349
- const parsed = new URL(url);
350
- const candidates = parsed.pathname
351
- .split("/")
352
- .filter(Boolean)
353
- .filter((segment) => !TITLE_SEGMENT_STOPWORDS.has(segment.toLowerCase()))
354
- .map(humanizeUrlSegment)
355
- .filter((title): title is string => Boolean(title));
356
- if (candidates.length === 0) {
357
- return null;
358
- }
359
- return candidates.sort((left, right) => right.length - left.length)[0];
360
- } catch {
361
- return null;
362
- }
363
- }
364
-
365
- function resolveRange(
366
- range: LinkInsightRange,
367
- now: Date,
368
- since?: string,
369
- until?: string,
370
- ) {
371
- if (since || until) {
372
- return {
373
- since: since ?? null,
374
- until: until ?? null,
375
- };
376
- }
377
- if (range === "all") {
378
- return { since: null, until: null };
379
- }
380
-
381
- const start = new Date(now);
382
- if (range === "today") {
383
- // "Today" follows the user's local calendar day; toISOString below
384
- // converts that local midnight into the correct UTC storage boundary.
385
- start.setHours(0, 0, 0, 0);
386
- } else {
387
- const days = range === "week" ? 7 : range === "month" ? 30 : 365;
388
- start.setDate(start.getDate() - days);
389
- }
390
- return {
391
- since: start.toISOString(),
392
- until: now.toISOString(),
393
- };
394
- }
395
-
396
- function getInfluenceScore(profile: ProfileRecord | null) {
397
- if (!profile) {
398
- return 0;
399
- }
400
- return Math.round(Math.log10(profile.followersCount + 10) * 24);
401
- }
402
-
403
- function chooseMetadata(existing: string | null, candidate: string | null) {
404
- if (!candidate) {
405
- return existing;
406
- }
407
- if (!existing) {
408
- return candidate;
409
- }
410
- return candidate.length > existing.length ? candidate : existing;
411
- }
412
-
413
- function stripUrls(text: string, urls: string[]) {
414
- let output = text;
415
- for (const url of urls) {
416
- if (!url) {
417
- continue;
418
- }
419
- const variants = new Set<string>([url]);
420
- try {
421
- const parsed = new URL(url);
422
- variants.add(parsed.href);
423
- variants.add(`${parsed.host}${parsed.pathname}${parsed.search}`);
424
- variants.add(
425
- `${parsed.hostname.replace(/^www\./, "")}${parsed.pathname}${parsed.search}`,
426
- );
427
- } catch {
428
- // keep raw variant only
429
- }
430
- for (const variant of variants) {
431
- output = output.split(variant).join(" ");
432
- }
433
- }
434
- return output.replaceAll(URL_WHITESPACE, " ").trim();
435
- }
436
-
437
- function parseMedia(value: unknown) {
438
- return parseJsonField<TweetMediaItem[]>(value, []);
439
- }
440
-
441
- function buildTweetUrl(
442
- handle: string | null | undefined,
443
- tweetId: string | null,
444
- ) {
445
- const cleanHandle = handle?.replace(/^@/, "").trim();
446
- if (!cleanHandle || !tweetId) {
447
- return null;
448
- }
449
- return `https://x.com/${cleanHandle}/status/${tweetId}`;
450
- }
451
-
452
- function sourceLabel(row: LinkInsightRow) {
453
- if (row.source_kind === "dm") {
454
- return row.direction ? `DM ${row.direction}` : "DM";
455
- }
456
- return "tweet";
457
- }
458
-
459
- function buildMention(row: LinkInsightRow, normalized: NormalizedUrl) {
460
- const sharedBy =
461
- row.source_kind === "tweet"
462
- ? toProfile(row, "source_author_")
463
- : toProfile(row, "dm_sender_");
464
- const participant =
465
- row.source_kind === "dm" ? toProfile(row, "participant_") : null;
466
- const contentAuthor = toProfile(row, "linked_author_");
467
- const rawText = String(row.source_text ?? "");
468
- const text = stripUrls(rawText, [
469
- row.short_url,
470
- row.expanded_url,
471
- row.final_url,
472
- normalized.url,
473
- normalized.displayUrl,
474
- ...(rawText.match(RAW_URL_PATTERN) ?? []),
475
- ]);
476
- const sharedContentText =
477
- row.linked_text && row.linked_text !== rawText ? row.linked_text : null;
478
- const timelineTweetId = row.source_kind === "tweet" ? row.source_id : null;
479
- const contentTweetId = row.expanded_tweet_id;
480
- const sourceUrl =
481
- row.source_kind === "tweet"
482
- ? buildTweetUrl(sharedBy?.handle, timelineTweetId)
483
- : null;
484
- const contentTweetUrl = buildTweetUrl(
485
- contentAuthor?.handle ?? row.expanded_handle,
486
- contentTweetId,
487
- );
488
- const media = [
489
- ...parseMedia(row.source_media_json),
490
- ...parseMedia(row.linked_media_json),
491
- ];
492
- const mention: LinkInsightMention = {
493
- id: `${row.source_kind}:${row.source_id}:${String(row.source_position)}:${row.short_url}`,
494
- sourceKind: row.source_kind,
495
- sourceId: row.source_id,
496
- sourceUrl,
497
- sourceLabel: sourceLabel(row),
498
- shortUrl: row.short_url,
499
- conversationId: row.conversation_id,
500
- createdAt: row.created_at,
501
- rawText,
502
- text,
503
- commentText: text,
504
- sharedContentText,
505
- hasComment: text.length > 0,
506
- isPureShare: text.length === 0,
507
- timelineTweetId,
508
- contentTweetId,
509
- contentTweetUrl,
510
- contentAuthor,
511
- media,
512
- direction: row.direction,
513
- accountHandle: row.account_handle,
514
- sharedBy,
515
- participant,
516
- };
517
- return mention;
518
- }
519
-
520
- function toInsight(
521
- group: InsightGroup,
522
- commentsLimit: number,
523
- ): LinkInsightItem {
524
- const sortedMentions = [...group.mentions].sort((a, b) => {
525
- const commentWeight = Number(b.hasComment) - Number(a.hasComment);
526
- if (commentWeight !== 0) {
527
- return commentWeight;
528
- }
529
- const influence =
530
- getInfluenceScore(b.sharedBy ?? null) -
531
- getInfluenceScore(a.sharedBy ?? null);
532
- if (influence !== 0) {
533
- return influence;
534
- }
535
- return b.createdAt.localeCompare(a.createdAt);
536
- });
537
- const mentions = sortedMentions.slice(0, commentsLimit);
538
- const mentionCount = sortedMentions.length;
539
- const commentCount = sortedMentions.filter(
540
- (mention) => mention.hasComment,
541
- ).length;
542
- const pureShareCount = mentionCount - commentCount;
543
- const sharers = [...group.sharerProfiles.values()].sort((a, b) => {
544
- const influence = getInfluenceScore(b) - getInfluenceScore(a);
545
- if (influence !== 0) {
546
- return influence;
547
- }
548
- return a.handle.localeCompare(b.handle);
549
- });
550
- return {
551
- id: group.canonicalKey,
552
- kind: group.kind,
553
- url: group.url,
554
- canonicalKey: group.canonicalKey,
555
- displayUrl: group.displayUrl,
556
- host: group.host,
557
- title: group.title ?? deriveTitleFromUrl(group.url),
558
- description: group.description,
559
- shareCount: group.shareCount,
560
- uniqueSharers: group.sharers.size,
561
- totalInfluence: group.totalInfluence,
562
- mentionCount,
563
- commentCount,
564
- pureShareCount,
565
- hiddenMentionCount: Math.max(0, mentionCount - mentions.length),
566
- firstSeenAt: group.firstSeenAt,
567
- lastSeenAt: group.lastSeenAt,
568
- topSharer: group.topSharer,
569
- sharers,
570
- mentions,
571
- };
572
- }
573
-
574
- function compareRank(left: LinkInsightItem, right: LinkInsightItem) {
575
- if (right.shareCount !== left.shareCount) {
576
- return right.shareCount - left.shareCount;
577
- }
578
- if (right.totalInfluence !== left.totalInfluence) {
579
- return right.totalInfluence - left.totalInfluence;
580
- }
581
- return right.lastSeenAt.localeCompare(left.lastSeenAt);
582
- }
583
-
584
- function compareInsights(sort: LinkInsightSort) {
585
- return (left: LinkInsightItem, right: LinkInsightItem) => {
586
- if (sort === "recent") {
587
- return (
588
- right.lastSeenAt.localeCompare(left.lastSeenAt) ||
589
- compareRank(left, right)
590
- );
591
- }
592
- if (sort === "comments") {
593
- return (
594
- right.commentCount - left.commentCount ||
595
- right.shareCount - left.shareCount ||
596
- right.lastSeenAt.localeCompare(left.lastSeenAt)
597
- );
598
- }
599
- return compareRank(left, right);
600
- };
601
- }
602
-
603
- export function getLinkInsights(
604
- query: LinkInsightQuery = {},
605
- ): LinkInsightResponse {
606
- const kind = query.kind ?? "links";
607
- const range = query.range ?? "week";
608
- const sort = query.sort ?? "rank";
609
- const source = query.source ?? "all";
610
- const limit =
611
- typeof query.limit === "number" && Number.isFinite(query.limit)
612
- ? Math.max(1, Math.trunc(query.limit))
613
- : DEFAULT_LIMIT;
614
- const commentsLimit =
615
- typeof query.commentsLimit === "number" &&
616
- Number.isFinite(query.commentsLimit)
617
- ? Math.max(1, Math.trunc(query.commentsLimit))
618
- : DEFAULT_COMMENTS_LIMIT;
619
- const bounds = resolveRange(
620
- range,
621
- query.now ?? new Date(),
622
- query.since,
623
- query.until,
624
- );
625
-
626
- const params: Array<string | number> = [];
627
- const conditions = ["e.status = 'hit'"];
628
- if (bounds.since) {
629
- conditions.push("o.created_at >= ?");
630
- params.push(bounds.since);
631
- }
632
- if (bounds.until) {
633
- conditions.push("o.created_at < ?");
634
- params.push(bounds.until);
635
- }
636
- if (source === "tweet" || source === "dm") {
637
- conditions.push("o.source_kind = ?");
638
- params.push(source);
639
- }
640
- if (query.account && query.account !== "all") {
641
- conditions.push(`(
642
- (o.source_kind = 'dm' and o.account_id = ?)
643
- or (
644
- o.source_kind = 'tweet'
645
- and (
646
- o.account_id = ?
647
- or exists (
648
- select 1
649
- from tweet_account_edges edge
650
- where edge.account_id = ?
651
- and edge.tweet_id = o.source_id
652
- )
653
- or exists (
654
- select 1
655
- from tweet_collections collection
656
- where collection.account_id = ?
657
- and collection.tweet_id = o.source_id
658
- )
659
- )
660
- )
661
- )`);
662
- params.push(query.account, query.account, query.account, query.account);
663
- }
664
- if (kind === "videos") {
665
- addVideoUrlPrefilter(conditions);
666
- }
667
-
668
- const db = getNativeDb({ seedDemoData: false });
669
- const rows = db
670
- .prepare(`
671
- select
672
- o.source_kind,
673
- o.source_id,
674
- o.source_position,
675
- o.short_url,
676
- o.account_id,
677
- o.conversation_id,
678
- o.direction,
679
- o.created_at,
680
- e.expanded_url,
681
- e.final_url,
682
- e.expanded_tweet_id,
683
- e.expanded_handle,
684
- e.title,
685
- e.description,
686
- coalesce(dm.text, source_tweet.text, '') as source_text,
687
- source_tweet.media_json as source_media_json,
688
- account.handle as account_handle,
689
- source_author.id as source_author_id,
690
- source_author.handle as source_author_handle,
691
- source_author.display_name as source_author_display_name,
692
- source_author.bio as source_author_bio,
693
- source_author.followers_count as source_author_followers_count,
694
- source_author.following_count as source_author_following_count,
695
- source_author.avatar_hue as source_author_avatar_hue,
696
- source_author.avatar_url as source_author_avatar_url,
697
- source_author.location as source_author_location,
698
- source_author.url as source_author_url,
699
- source_author.verified_type as source_author_verified_type,
700
- source_author.entities_json as source_author_entities_json,
701
- source_author.created_at as source_author_created_at,
702
- dm_sender.id as dm_sender_id,
703
- dm_sender.handle as dm_sender_handle,
704
- dm_sender.display_name as dm_sender_display_name,
705
- dm_sender.bio as dm_sender_bio,
706
- dm_sender.followers_count as dm_sender_followers_count,
707
- dm_sender.following_count as dm_sender_following_count,
708
- dm_sender.avatar_hue as dm_sender_avatar_hue,
709
- dm_sender.avatar_url as dm_sender_avatar_url,
710
- dm_sender.location as dm_sender_location,
711
- dm_sender.url as dm_sender_url,
712
- dm_sender.verified_type as dm_sender_verified_type,
713
- dm_sender.entities_json as dm_sender_entities_json,
714
- dm_sender.created_at as dm_sender_created_at,
715
- participant.id as participant_id,
716
- participant.handle as participant_handle,
717
- participant.display_name as participant_display_name,
718
- participant.bio as participant_bio,
719
- participant.followers_count as participant_followers_count,
720
- participant.following_count as participant_following_count,
721
- participant.avatar_hue as participant_avatar_hue,
722
- participant.avatar_url as participant_avatar_url,
723
- participant.location as participant_location,
724
- participant.url as participant_url,
725
- participant.verified_type as participant_verified_type,
726
- participant.entities_json as participant_entities_json,
727
- participant.created_at as participant_created_at,
728
- linked.text as linked_text,
729
- linked.media_json as linked_media_json,
730
- linked_author.id as linked_author_id,
731
- linked_author.handle as linked_author_handle,
732
- linked_author.display_name as linked_author_display_name,
733
- linked_author.bio as linked_author_bio,
734
- linked_author.followers_count as linked_author_followers_count,
735
- linked_author.following_count as linked_author_following_count,
736
- linked_author.avatar_hue as linked_author_avatar_hue,
737
- linked_author.avatar_url as linked_author_avatar_url,
738
- linked_author.location as linked_author_location,
739
- linked_author.url as linked_author_url,
740
- linked_author.verified_type as linked_author_verified_type,
741
- linked_author.entities_json as linked_author_entities_json,
742
- linked_author.created_at as linked_author_created_at
743
- from link_occurrences o
744
- join url_expansions e on e.short_url = o.short_url
745
- left join accounts account on account.id = o.account_id
746
- left join dm_messages dm
747
- on o.source_kind = 'dm' and dm.id = o.source_id
748
- left join profiles dm_sender
749
- on dm_sender.id = dm.sender_profile_id
750
- left join dm_conversations conversation
751
- on conversation.id = o.conversation_id
752
- left join profiles participant
753
- on participant.id = conversation.participant_profile_id
754
- left join tweets source_tweet
755
- on o.source_kind = 'tweet' and source_tweet.id = o.source_id
756
- left join profiles source_author
757
- on source_author.id = source_tweet.author_profile_id
758
- left join tweets linked
759
- on linked.id = e.expanded_tweet_id
760
- left join profiles linked_author
761
- on linked_author.id = linked.author_profile_id
762
- where ${conditions.join(" and ")}
763
- order by o.created_at desc
764
- `)
765
- .all(...params) as LinkInsightRow[];
766
-
767
- const groups = new Map<string, InsightGroup>();
768
- let occurrences = 0;
769
- for (const row of rows) {
770
- const rawUrl = row.final_url || row.expanded_url || row.short_url;
771
- const normalized = normalizeUrl(rawUrl);
772
- if (!normalized) {
773
- continue;
774
- }
775
- const rowKind: LinkInsightKind = isVideoHost(normalized.host)
776
- ? "videos"
777
- : "links";
778
- if (rowKind !== kind) {
779
- continue;
780
- }
781
- occurrences++;
782
-
783
- const mention = buildMention(row, normalized);
784
- const sharerKey = mention.sharedBy
785
- ? mention.sharedBy.id
786
- : `${row.source_kind}:${row.source_id}`;
787
- const influence = getInfluenceScore(mention.sharedBy ?? null);
788
- const existing = groups.get(normalized.canonicalKey);
789
- if (existing) {
790
- if (!existing.seenMentions.has(mention.id)) {
791
- existing.seenMentions.add(mention.id);
792
- existing.mentions.push(mention);
793
- existing.shareCount++;
794
- existing.totalInfluence += influence;
795
- existing.sharers.add(sharerKey);
796
- if (mention.sharedBy) {
797
- existing.sharerProfiles.set(mention.sharedBy.id, mention.sharedBy);
798
- }
799
- if (
800
- !existing.topSharer ||
801
- influence > getInfluenceScore(existing.topSharer)
802
- ) {
803
- existing.topSharer = mention.sharedBy ?? null;
804
- }
805
- }
806
- existing.title = chooseMetadata(existing.title, row.title);
807
- existing.description = chooseMetadata(
808
- existing.description,
809
- row.description,
810
- );
811
- if (row.created_at < existing.firstSeenAt) {
812
- existing.firstSeenAt = row.created_at;
813
- }
814
- if (row.created_at > existing.lastSeenAt) {
815
- existing.lastSeenAt = row.created_at;
816
- }
817
- continue;
818
- }
819
-
820
- groups.set(normalized.canonicalKey, {
821
- canonicalKey: normalized.canonicalKey,
822
- description: row.description,
823
- displayUrl: normalized.displayUrl,
824
- firstSeenAt: row.created_at,
825
- host: normalized.host,
826
- kind: rowKind,
827
- lastSeenAt: row.created_at,
828
- mentions: [mention],
829
- seenMentions: new Set([mention.id]),
830
- sharers: new Set([sharerKey]),
831
- sharerProfiles: mention.sharedBy
832
- ? new Map([[mention.sharedBy.id, mention.sharedBy]])
833
- : new Map(),
834
- shareCount: 1,
835
- title: row.title,
836
- topSharer: mention.sharedBy ?? null,
837
- totalInfluence: influence,
838
- url: normalized.url,
839
- });
840
- }
841
-
842
- const items = [...groups.values()]
843
- .map((group) => toInsight(group, commentsLimit))
844
- .sort(compareInsights(sort))
845
- .slice(0, limit);
846
-
847
- return {
848
- kind,
849
- range,
850
- sort,
851
- source,
852
- since: bounds.since,
853
- until: bounds.until,
854
- items,
855
- stats: {
856
- occurrences,
857
- groups: groups.size,
858
- },
859
- };
860
- }