|
| 1 | +import { safeParse, flatten } from 'valibot' |
| 2 | +import type { Comment, CommentEmbed } from '#shared/types/blog-post' |
| 3 | +import { |
| 4 | + AppBskyFeedDefs, |
| 5 | + AppBskyFeedPost, |
| 6 | + AppBskyEmbedImages, |
| 7 | + AppBskyEmbedExternal, |
| 8 | +} from '@atproto/api' |
| 9 | +import { BlueSkyUriSchema } from '#shared/schemas/atproto' |
| 10 | +import { CACHE_MAX_AGE_ONE_MINUTE, BLUESKY_API, AT_URI_REGEX } from '#shared/utils/constants' |
| 11 | + |
| 12 | +import { jsonToLex } from '@atproto/api' |
| 13 | + |
| 14 | +type ThreadResponse = { thread: AppBskyFeedDefs.ThreadViewPost } |
| 15 | + |
| 16 | +type LikesResponse = { |
| 17 | + likes: Array<{ |
| 18 | + actor: { |
| 19 | + did: string |
| 20 | + handle: string |
| 21 | + displayName?: string |
| 22 | + avatar?: string |
| 23 | + } |
| 24 | + }> |
| 25 | +} |
| 26 | + |
| 27 | +type PostsResponse = { posts: Array<{ likeCount?: number }> } |
| 28 | + |
| 29 | +/** |
| 30 | + * Provides both build and runtime comments refreshes |
| 31 | + * During build, cache aggressively to avoid rate limits |
| 32 | + * During runtime, refresh cache once every minute |
| 33 | + */ |
| 34 | +export default defineCachedEventHandler( |
| 35 | + async event => { |
| 36 | + const query = getQuery(event) |
| 37 | + const parsed = safeParse(BlueSkyUriSchema, query) |
| 38 | + |
| 39 | + if (!parsed.success) { |
| 40 | + throw createError({ |
| 41 | + statusCode: 400, |
| 42 | + statusMessage: `Invalid URI format: ${flatten(parsed.issues).root?.[0] || 'Must be a valid at:// URI'}`, |
| 43 | + }) |
| 44 | + } |
| 45 | + |
| 46 | + const { uri } = parsed.output |
| 47 | + |
| 48 | + try { |
| 49 | + // Fetch thread, likes, and post metadata in parallel |
| 50 | + const [threadResponse, likesResponse, postsResponse] = await Promise.all([ |
| 51 | + $fetch<ThreadResponse>(`${BLUESKY_API}app.bsky.feed.getPostThread`, { |
| 52 | + query: { uri, depth: 10 }, |
| 53 | + }).catch((err: Error) => { |
| 54 | + console.warn(`[Bluesky] Thread fetch failed for ${uri}:`, err.message) |
| 55 | + return null |
| 56 | + }), |
| 57 | + |
| 58 | + $fetch<LikesResponse>(`${BLUESKY_API}app.bsky.feed.getLikes`, { |
| 59 | + query: { uri, limit: 50 }, |
| 60 | + }).catch(() => ({ likes: [] })), |
| 61 | + |
| 62 | + $fetch<PostsResponse>(`${BLUESKY_API}app.bsky.feed.getPosts`, { |
| 63 | + query: { uris: [uri] }, |
| 64 | + }).catch(() => ({ posts: [] })), |
| 65 | + ]) |
| 66 | + |
| 67 | + // Early return if thread fetch fails w/o 404 |
| 68 | + if (!threadResponse) { |
| 69 | + return { |
| 70 | + thread: null, |
| 71 | + likes: [], |
| 72 | + totalLikes: 0, |
| 73 | + postUrl: atUriToWebUrl(uri), |
| 74 | + _empty: true, |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + const thread = parseThread(threadResponse.thread) |
| 79 | + |
| 80 | + return { |
| 81 | + thread, |
| 82 | + likes: likesResponse.likes || [], |
| 83 | + totalLikes: postsResponse.posts?.[0]?.likeCount || thread?.likeCount || 0, |
| 84 | + postUrl: atUriToWebUrl(uri), |
| 85 | + } |
| 86 | + } catch (error) { |
| 87 | + // Fail open during build to prevent build breakage |
| 88 | + console.error('[Bluesky] Unexpected error:', error) |
| 89 | + return { |
| 90 | + thread: null, |
| 91 | + likes: [], |
| 92 | + totalLikes: 0, |
| 93 | + postUrl: atUriToWebUrl(uri), |
| 94 | + _error: true, |
| 95 | + } |
| 96 | + } |
| 97 | + }, |
| 98 | + { |
| 99 | + name: 'bluesky-comments', |
| 100 | + maxAge: CACHE_MAX_AGE_ONE_MINUTE, |
| 101 | + getKey: event => { |
| 102 | + const { uri } = getQuery(event) |
| 103 | + return `bluesky:${uri}` |
| 104 | + }, |
| 105 | + }, |
| 106 | +) |
| 107 | + |
| 108 | +// Helper to convert AT URI to web URL |
| 109 | +function atUriToWebUrl(uri: string): string | null { |
| 110 | + const match = uri.match(AT_URI_REGEX) |
| 111 | + if (!match) return null |
| 112 | + const [, did, rkey] = match |
| 113 | + return `https://bsky.app/profile/${did}/post/${rkey}` |
| 114 | +} |
| 115 | + |
| 116 | +function parseEmbed(embed: AppBskyFeedDefs.PostView['embed']): CommentEmbed | undefined { |
| 117 | + if (!embed) return undefined |
| 118 | + |
| 119 | + if (AppBskyEmbedImages.isView(embed)) { |
| 120 | + return { |
| 121 | + type: 'images', |
| 122 | + images: embed.images, |
| 123 | + } |
| 124 | + } |
| 125 | + |
| 126 | + if (AppBskyEmbedExternal.isView(embed)) { |
| 127 | + return { |
| 128 | + type: 'external', |
| 129 | + external: embed.external, |
| 130 | + } |
| 131 | + } |
| 132 | + |
| 133 | + return undefined |
| 134 | +} |
| 135 | + |
| 136 | +function parseThread(thread: AppBskyFeedDefs.ThreadViewPost): Comment | null { |
| 137 | + if (!AppBskyFeedDefs.isThreadViewPost(thread)) return null |
| 138 | + |
| 139 | + const { post } = thread |
| 140 | + |
| 141 | + // This casts our external.thumb as a blobRef which is needed to validateRecord |
| 142 | + const lexPostRecord = jsonToLex(post.record) |
| 143 | + const recordValidation = AppBskyFeedPost.validateRecord(lexPostRecord) |
| 144 | + |
| 145 | + if (!recordValidation.success) return null |
| 146 | + const record = recordValidation.value |
| 147 | + |
| 148 | + const replies: Comment[] = [] |
| 149 | + if (thread.replies) { |
| 150 | + for (const reply of thread.replies) { |
| 151 | + if (AppBskyFeedDefs.isThreadViewPost(reply)) { |
| 152 | + const parsed = parseThread(reply) |
| 153 | + if (parsed) replies.push(parsed) |
| 154 | + } |
| 155 | + } |
| 156 | + replies.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()) |
| 157 | + } |
| 158 | + |
| 159 | + return { |
| 160 | + uri: post.uri, |
| 161 | + cid: post.cid, |
| 162 | + author: { |
| 163 | + did: post.author.did, |
| 164 | + handle: post.author.handle, |
| 165 | + displayName: post.author.displayName, |
| 166 | + avatar: post.author.avatar, |
| 167 | + }, |
| 168 | + text: record.text, |
| 169 | + facets: record.facets, |
| 170 | + embed: parseEmbed(post.embed), |
| 171 | + createdAt: record.createdAt, |
| 172 | + likeCount: post.likeCount ?? 0, |
| 173 | + replyCount: post.replyCount ?? 0, |
| 174 | + repostCount: post.repostCount ?? 0, |
| 175 | + replies, |
| 176 | + } |
| 177 | +} |
0 commit comments