// Posts elsewhere on Bluesky that link to this article. // // The document's `bskyPostRef` names one discussion thread, but other people // write their own posts about an article without being in it. The appview's // search can answer "which posts link this URL", unauthenticated, so the // popup can show the wider conversation without asking for a write scope. // // The search service is optional infrastructure: it may require auth for some // deployments, rate-limit, or change its response. Every failure is a hidden // row, never an error in the popup. import { bskyProfileUrl, parseAtUri } from './atproto' import { type RequestOptions, requestJson } from './http' import { pubSiteUrl } from './readers' import type { DocInfo, PubInfo } from './types' // `public.api.bsky.app` is the read-only host for most of what this extension // asks Bluesky, but it refuses search without a session. `api.bsky.app` answers // it anonymously today; the lexicon warns that search may require auth on some // deployments, which is why a failure here is only a missing row. const SEARCH = 'https://api.bsky.app/xrpc/app.bsky.feed.searchPosts' /** Enough to fill the row and learn whether there are more. */ const LIMIT = 10 /** Cosmetic and third-party: fail fast, and never hold the popup open. */ const OPTIONS: RequestOptions = { timeoutMs: 5_000, retries: 1 } export interface MentionAuthor { did: string handle?: string displayName?: string avatarUrl?: string } export interface Mention { uri: string author: MentionAuthor text: string likeCount: number replyCount: number } export interface MentionResult { posts: Mention[] /** The search had more than the page we asked for. */ more: boolean } /** * The URL other posts are most likely to link: the article's canonical home, * `publication.url` plus its `path`. A document without a path falls back to * the page when the page is on the publication's own origin, and to the * publication's home otherwise. */ export function canonicalArticleUrl( pub: PubInfo, doc?: DocInfo, pageUrl?: string, ): string | null { const site = pubSiteUrl(pub) if (!site) return null const base = site.replace(/\/+$/, '') const path = doc?.record.path?.trim() if (path) { // Records are third-party data. A `path` that is an absolute URL is not // what the lexicon asks for, but it is what the popup has to survive. if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) { try { const absolute = new URL(path) return absolute.protocol === 'https:' || absolute.protocol === 'http:' ? absolute.href : null } catch { return null } } return base + (path.startsWith('/') ? path : `/${path}`) } try { if (pageUrl && new URL(pageUrl).origin === new URL(base).origin) return pageUrl } catch { // A page URL that does not parse says nothing; fall through to the home. } return base } /** * The appview requires `q` even when `url` is the real filter. `*` matches * everything, leaving the URL to decide which posts come back. */ export function searchMentionsUrl(url: string): string { const u = new URL(SEARCH) u.searchParams.set('q', '*') u.searchParams.set('url', url) u.searchParams.set('sort', 'top') u.searchParams.set('limit', String(LIMIT)) return u.toString() } /** bsky.app's own search for the article URL, for the row's "see all". */ export function bskySearchUrl(url: string): string { const u = new URL('https://bsky.app/search') u.searchParams.set('q', url) return u.toString() } /** The post on bsky.app; undefined for a uri that is not a post. */ export function mentionUrl(mention: Mention): string | undefined { const parsed = parseAtUri(mention.uri) if (!parsed || parsed.collection !== 'app.bsky.feed.post') return undefined return `${bskyProfileUrl(parsed.did)}/post/${encodeURIComponent(parsed.rkey)}` } function count(value: unknown): number { return typeof value === 'number' && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0 } function text(value: unknown): string | undefined { if (typeof value !== 'string') return undefined const trimmed = value.trim() return trimmed || undefined } /** One search result, validated; null for anything that is not a post view. */ function mentionFromPost(raw: unknown): Mention | null { if (!raw || typeof raw !== 'object') return null const post = raw as { uri?: unknown author?: unknown record?: unknown likeCount?: unknown replyCount?: unknown } if (typeof post.uri !== 'string') return null const parsed = parseAtUri(post.uri) if (!parsed || parsed.collection !== 'app.bsky.feed.post') return null const author = post.author as | { did?: unknown; handle?: unknown; displayName?: unknown; avatar?: unknown } | undefined if (!author || typeof author.did !== 'string' || !author.did.startsWith('did:')) return null const record = post.record as { text?: unknown } | undefined if (!record || typeof record.text !== 'string') return null const avatar = author.avatar return { uri: post.uri, author: { did: author.did, handle: text(author.handle), displayName: text(author.displayName), // The appview serves avatars over https; anything else is not worth a // mixed-content request. avatarUrl: typeof avatar === 'string' && avatar.startsWith('https://') ? avatar : undefined, }, text: record.text.trim(), likeCount: count(post.likeCount), replyCount: count(post.replyCount), } } /** * The posts linking `url`, most relevant first. Throws when the appview cannot * be asked, so a caller can leave the row out instead of caching an empty * answer it does not believe. */ export async function searchMentions(url: string): Promise { const data = await requestJson<{ posts?: unknown; cursor?: unknown }>( searchMentionsUrl(url), OPTIONS, ) if (!Array.isArray(data.posts)) throw new Error('unexpected search response') return { posts: data.posts .map(mentionFromPost) .filter((post): post is Mention => post !== null) .slice(0, LIMIT), more: typeof data.cursor === 'string' && data.cursor.length > 0, } }