this repo has no description
at main 754 lines 19 kB view raw
1import { Agent, AtpAgent } from "@atproto/api"; 2import * as mimeTypes from "mime-types"; 3import * as fs from "node:fs/promises"; 4import * as path from "node:path"; 5import { getTextContent } from "./markdown"; 6import { getOAuthClient } from "./oauth-client"; 7import type { 8 BlobObject, 9 BlogPost, 10 Credentials, 11 PublicationRecord, 12 PublisherConfig, 13 StrongRef, 14} from "./types"; 15import { isAppPasswordCredentials, isOAuthCredentials } from "./types"; 16 17/** 18 * Type guard to check if a record value is a DocumentRecord 19 */ 20function isDocumentRecord(value: unknown): value is DocumentRecord { 21 if (!value || typeof value !== "object") return false; 22 const v = value as Record<string, unknown>; 23 return ( 24 v.$type === "site.standard.document" && 25 typeof v.title === "string" && 26 typeof v.site === "string" && 27 typeof v.path === "string" && 28 typeof v.textContent === "string" && 29 typeof v.publishedAt === "string" 30 ); 31} 32 33async function fileExists(filePath: string): Promise<boolean> { 34 try { 35 await fs.access(filePath); 36 return true; 37 } catch { 38 return false; 39 } 40} 41 42/** 43 * Resolve a handle to a DID 44 */ 45export async function resolveHandleToDid(handle: string): Promise<string> { 46 if (handle.startsWith("did:")) { 47 return handle; 48 } 49 50 // Try to resolve handle via Bluesky API 51 const resolveUrl = `https://public.api.bsky.app/xrpc/com.atproto.identity.resolveHandle?handle=${encodeURIComponent(handle)}`; 52 const resolveResponse = await fetch(resolveUrl); 53 if (!resolveResponse.ok) { 54 throw new Error("Could not resolve handle"); 55 } 56 const resolveData = (await resolveResponse.json()) as { did: string }; 57 return resolveData.did; 58} 59 60export async function resolveHandleToPDS(handle: string): Promise<string> { 61 // First, resolve the handle to a DID 62 const did = await resolveHandleToDid(handle); 63 64 // Now resolve the DID to get the PDS URL from the DID document 65 let pdsUrl: string | undefined; 66 67 if (did.startsWith("did:plc:")) { 68 // Fetch DID document from plc.directory 69 const didDocUrl = `https://plc.directory/${did}`; 70 const didDocResponse = await fetch(didDocUrl); 71 if (!didDocResponse.ok) { 72 throw new Error("Could not fetch DID document"); 73 } 74 const didDoc = (await didDocResponse.json()) as { 75 service?: Array<{ id: string; type: string; serviceEndpoint: string }>; 76 }; 77 78 // Find the PDS service endpoint 79 const pdsService = didDoc.service?.find( 80 (s) => s.id === "#atproto_pds" || s.type === "AtprotoPersonalDataServer", 81 ); 82 pdsUrl = pdsService?.serviceEndpoint; 83 } else if (did.startsWith("did:web:")) { 84 // For did:web, fetch the DID document from the domain 85 const domain = did.replace("did:web:", ""); 86 const didDocUrl = `https://${domain}/.well-known/did.json`; 87 const didDocResponse = await fetch(didDocUrl); 88 if (!didDocResponse.ok) { 89 throw new Error("Could not fetch DID document"); 90 } 91 const didDoc = (await didDocResponse.json()) as { 92 service?: Array<{ id: string; type: string; serviceEndpoint: string }>; 93 }; 94 95 const pdsService = didDoc.service?.find( 96 (s) => s.id === "#atproto_pds" || s.type === "AtprotoPersonalDataServer", 97 ); 98 pdsUrl = pdsService?.serviceEndpoint; 99 } 100 101 if (!pdsUrl) { 102 throw new Error("Could not find PDS URL for user"); 103 } 104 105 return pdsUrl; 106} 107 108export interface CreatePublicationOptions { 109 url: string; 110 name: string; 111 description?: string; 112 iconPath?: string; 113 showInDiscover?: boolean; 114} 115 116export async function createAgent(credentials: Credentials): Promise<Agent> { 117 if (isOAuthCredentials(credentials)) { 118 // OAuth flow - restore session from stored tokens 119 const client = await getOAuthClient(); 120 try { 121 const oauthSession = await client.restore(credentials.did); 122 // Wrap the OAuth session in an Agent which provides the atproto API 123 return new Agent(oauthSession); 124 } catch (error) { 125 if (error instanceof Error) { 126 // Check for common OAuth errors 127 if ( 128 error.message.includes("expired") || 129 error.message.includes("revoked") 130 ) { 131 throw new Error( 132 `OAuth session expired or revoked. Please run 'sequoia login' to re-authenticate.`, 133 ); 134 } 135 } 136 throw error; 137 } 138 } 139 140 // App password flow 141 if (!isAppPasswordCredentials(credentials)) { 142 throw new Error("Invalid credential type"); 143 } 144 const agent = new AtpAgent({ service: credentials.pdsUrl }); 145 146 await agent.login({ 147 identifier: credentials.identifier, 148 password: credentials.password, 149 }); 150 151 return agent; 152} 153 154export async function uploadImage( 155 agent: Agent, 156 imagePath: string, 157): Promise<BlobObject | undefined> { 158 if (!(await fileExists(imagePath))) { 159 return undefined; 160 } 161 162 try { 163 const imageBuffer = await fs.readFile(imagePath); 164 const mimeType = mimeTypes.lookup(imagePath) || "application/octet-stream"; 165 166 const response = await agent.com.atproto.repo.uploadBlob( 167 new Uint8Array(imageBuffer), 168 { 169 encoding: mimeType, 170 }, 171 ); 172 173 return { 174 $type: "blob", 175 ref: { 176 $link: response.data.blob.ref.toString(), 177 }, 178 mimeType, 179 size: imageBuffer.byteLength, 180 }; 181 } catch (error) { 182 console.error(`Error uploading image ${imagePath}:`, error); 183 return undefined; 184 } 185} 186 187export async function resolveImagePath( 188 ogImage: string, 189 imagesDir: string | undefined, 190 contentDir: string, 191): Promise<string | null> { 192 // Try multiple resolution strategies 193 194 // 1. If imagesDir is specified, look there 195 if (imagesDir) { 196 // Get the base name of the images directory (e.g., "blog-images" from "public/blog-images") 197 const imagesDirBaseName = path.basename(imagesDir); 198 199 // Check if ogImage contains the images directory name and extract the relative path 200 // e.g., "/blog-images/other/file.png" with imagesDirBaseName "blog-images" -> "other/file.png" 201 const imagesDirIndex = ogImage.indexOf(imagesDirBaseName); 202 let relativePath: string; 203 204 if (imagesDirIndex !== -1) { 205 // Extract everything after "blog-images/" 206 const afterImagesDir = ogImage.substring( 207 imagesDirIndex + imagesDirBaseName.length, 208 ); 209 // Remove leading slash if present 210 relativePath = afterImagesDir.replace(/^[/\\]/, ""); 211 } else { 212 // Fall back to just the filename 213 relativePath = path.basename(ogImage); 214 } 215 216 const imagePath = path.join(imagesDir, relativePath); 217 if (await fileExists(imagePath)) { 218 const stat = await fs.stat(imagePath); 219 if (stat.size > 0) { 220 return imagePath; 221 } 222 } 223 } 224 225 // 2. Try the ogImage path directly (if it's absolute) 226 if (path.isAbsolute(ogImage)) { 227 return ogImage; 228 } 229 230 // 3. Try relative to content directory 231 const contentRelative = path.join(contentDir, ogImage); 232 if (await fileExists(contentRelative)) { 233 const stat = await fs.stat(contentRelative); 234 if (stat.size > 0) { 235 return contentRelative; 236 } 237 } 238 239 return null; 240} 241 242export async function createDocument( 243 agent: Agent, 244 post: BlogPost, 245 config: PublisherConfig, 246 coverImage?: BlobObject, 247): Promise<string> { 248 const publishDate = new Date(post.frontmatter.publishDate); 249 const trimmedContent = post.content.trim(); 250 const textContent = getTextContent(post, config.textContentField); 251 const titleMatch = trimmedContent.match(/^# (.+)$/m); 252 const title = titleMatch ? titleMatch[1] : post.frontmatter.title; 253 254 const record: Record<string, unknown> = { 255 $type: "site.standard.document", 256 title, 257 site: config.publicationUri, 258 path: `/${post.slug}`, 259 textContent: textContent.slice(0, 10000), 260 publishedAt: publishDate.toISOString(), 261 }; 262 263 if (post.frontmatter.description) { 264 record.description = post.frontmatter.description; 265 } 266 267 if (coverImage) { 268 record.coverImage = coverImage; 269 } 270 271 if (post.frontmatter.tags && post.frontmatter.tags.length > 0) { 272 record.tags = post.frontmatter.tags; 273 } 274 275 const response = await agent.com.atproto.repo.createRecord({ 276 repo: agent.did!, 277 collection: "site.standard.document", 278 record, 279 }); 280 281 const atUri = response.data.uri; 282 const parsed = parseAtUri(atUri); 283 284 if (parsed) { 285 const slugName = post.slug 286 .split("/") 287 .pop()! 288 .replace(/\.pub$/, ""); 289 const finalPath = `/pub/${parsed.rkey}/${slugName}`; 290 record.path = finalPath; 291 record.canonicalUrl = config.canonicalUrlBuilder 292 ? config.canonicalUrlBuilder(atUri, post) 293 : `${config.siteUrl}${finalPath}`; 294 await agent.com.atproto.repo.putRecord({ 295 repo: agent.did!, 296 collection: parsed.collection, 297 rkey: parsed.rkey, 298 record, 299 }); 300 } 301 302 return atUri; 303} 304 305export async function updateDocument( 306 agent: Agent, 307 post: BlogPost, 308 atUri: string, 309 config: PublisherConfig, 310 coverImage?: BlobObject, 311): Promise<void> { 312 // Parse the atUri to get the collection and rkey 313 // Format: at://did:plc:xxx/collection/rkey 314 const uriMatch = atUri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/); 315 if (!uriMatch) { 316 throw new Error(`Invalid atUri format: ${atUri}`); 317 } 318 319 const [, , collection, rkey] = uriMatch; 320 321 const slugName = post.slug 322 .split("/") 323 .pop()! 324 .replace(/\.pub$/, ""); 325 const finalPath = `/pub/${rkey}/${slugName}`; 326 const publishDate = new Date(post.frontmatter.publishDate); 327 const trimmedContent = post.content.trim(); 328 const textContent = getTextContent(post, config.textContentField); 329 const titleMatch = trimmedContent.match(/^# (.+)$/m); 330 const title = titleMatch ? titleMatch[1] : post.frontmatter.title; 331 332 // Fetch existing record to preserve PDS-side fields (e.g. bskyPostRef) 333 const existingResponse = await agent.com.atproto.repo.getRecord({ 334 repo: agent.did!, 335 collection: collection!, 336 rkey: rkey!, 337 }); 338 const existingRecord = existingResponse.data.value as Record<string, unknown>; 339 340 const record: Record<string, unknown> = { 341 ...existingRecord, 342 $type: "site.standard.document", 343 title, 344 site: config.publicationUri, 345 path: finalPath, 346 textContent: textContent.slice(0, 10000), 347 publishedAt: publishDate.toISOString(), 348 canonicalUrl: config.canonicalUrlBuilder 349 ? config.canonicalUrlBuilder(atUri, post) 350 : `${config.siteUrl}${finalPath}`, 351 }; 352 353 if (post.frontmatter.description) { 354 record.description = post.frontmatter.description; 355 } 356 357 if (coverImage) { 358 record.coverImage = coverImage; 359 } 360 361 if (post.frontmatter.tags && post.frontmatter.tags.length > 0) { 362 record.tags = post.frontmatter.tags; 363 } 364 365 await agent.com.atproto.repo.putRecord({ 366 repo: agent.did!, 367 collection: collection!, 368 rkey: rkey!, 369 record, 370 }); 371} 372 373export function parseAtUri( 374 atUri: string, 375): { did: string; collection: string; rkey: string } | null { 376 const match = atUri.match(/^at:\/\/([^/]+)\/([^/]+)\/(.+)$/); 377 if (!match) return null; 378 return { 379 did: match[1]!, 380 collection: match[2]!, 381 rkey: match[3]!, 382 }; 383} 384 385export interface DocumentRecord { 386 $type: "site.standard.document"; 387 title: string; 388 site: string; 389 path: string; 390 textContent: string; 391 publishedAt: string; 392 canonicalUrl?: string; 393 description?: string; 394 coverImage?: BlobObject; 395 tags?: string[]; 396 location?: string; 397} 398 399export interface ListDocumentsResult { 400 uri: string; 401 cid: string; 402 value: DocumentRecord; 403} 404 405export async function listDocuments( 406 agent: Agent, 407 publicationUri?: string, 408): Promise<ListDocumentsResult[]> { 409 const documents: ListDocumentsResult[] = []; 410 let cursor: string | undefined; 411 412 do { 413 const response = await agent.com.atproto.repo.listRecords({ 414 repo: agent.did!, 415 collection: "site.standard.document", 416 limit: 100, 417 cursor, 418 }); 419 420 for (const record of response.data.records) { 421 if (!isDocumentRecord(record.value)) { 422 continue; 423 } 424 425 // If publicationUri is specified, only include documents from that publication 426 if (publicationUri && record.value.site !== publicationUri) { 427 continue; 428 } 429 430 documents.push({ 431 uri: record.uri, 432 cid: record.cid, 433 value: record.value, 434 }); 435 } 436 437 cursor = response.data.cursor; 438 } while (cursor); 439 440 return documents; 441} 442 443export async function createPublication( 444 agent: Agent, 445 options: CreatePublicationOptions, 446): Promise<string> { 447 let icon: BlobObject | undefined; 448 449 if (options.iconPath) { 450 icon = await uploadImage(agent, options.iconPath); 451 } 452 453 const record: Record<string, unknown> = { 454 $type: "site.standard.publication", 455 url: options.url, 456 name: options.name, 457 createdAt: new Date().toISOString(), 458 }; 459 460 if (options.description) { 461 record.description = options.description; 462 } 463 464 if (icon) { 465 record.icon = icon; 466 } 467 468 if (options.showInDiscover !== undefined) { 469 record.preferences = { 470 showInDiscover: options.showInDiscover, 471 }; 472 } 473 474 const response = await agent.com.atproto.repo.createRecord({ 475 repo: agent.did!, 476 collection: "site.standard.publication", 477 record, 478 }); 479 480 return response.data.uri; 481} 482 483export interface GetPublicationResult { 484 uri: string; 485 cid: string; 486 value: PublicationRecord; 487} 488 489export async function getPublication( 490 agent: Agent, 491 publicationUri: string, 492): Promise<GetPublicationResult | null> { 493 const parsed = parseAtUri(publicationUri); 494 if (!parsed) { 495 return null; 496 } 497 498 try { 499 const response = await agent.com.atproto.repo.getRecord({ 500 repo: parsed.did, 501 collection: parsed.collection, 502 rkey: parsed.rkey, 503 }); 504 505 return { 506 uri: publicationUri, 507 cid: response.data.cid!, 508 value: response.data.value as unknown as PublicationRecord, 509 }; 510 } catch { 511 return null; 512 } 513} 514 515export interface UpdatePublicationOptions { 516 url?: string; 517 name?: string; 518 description?: string; 519 iconPath?: string; 520 showInDiscover?: boolean; 521} 522 523export async function updatePublication( 524 agent: Agent, 525 publicationUri: string, 526 options: UpdatePublicationOptions, 527 existingRecord: PublicationRecord, 528): Promise<void> { 529 const parsed = parseAtUri(publicationUri); 530 if (!parsed) { 531 throw new Error(`Invalid publication URI: ${publicationUri}`); 532 } 533 534 // Build updated record, preserving createdAt and $type 535 const record: Record<string, unknown> = { 536 $type: existingRecord.$type, 537 url: options.url ?? existingRecord.url, 538 name: options.name ?? existingRecord.name, 539 createdAt: existingRecord.createdAt, 540 }; 541 542 // Handle description - can be cleared with empty string 543 if (options.description !== undefined) { 544 if (options.description) { 545 record.description = options.description; 546 } 547 // If empty string, don't include description (clears it) 548 } else if (existingRecord.description) { 549 record.description = existingRecord.description; 550 } 551 552 // Handle icon - upload new if provided, otherwise keep existing 553 if (options.iconPath) { 554 const icon = await uploadImage(agent, options.iconPath); 555 if (icon) { 556 record.icon = icon; 557 } 558 } else if (existingRecord.icon) { 559 record.icon = existingRecord.icon; 560 } 561 562 // Handle preferences 563 if (options.showInDiscover !== undefined) { 564 record.preferences = { 565 showInDiscover: options.showInDiscover, 566 }; 567 } else if (existingRecord.preferences) { 568 record.preferences = existingRecord.preferences; 569 } 570 571 await agent.com.atproto.repo.putRecord({ 572 repo: parsed.did, 573 collection: parsed.collection, 574 rkey: parsed.rkey, 575 record, 576 }); 577} 578 579export async function deleteRecord(agent: Agent, atUri: string): Promise<void> { 580 const parsed = parseAtUri(atUri); 581 if (!parsed) throw new Error(`Invalid atUri format: ${atUri}`); 582 await agent.com.atproto.repo.deleteRecord({ 583 repo: parsed.did, 584 collection: parsed.collection, 585 rkey: parsed.rkey, 586 }); 587} 588 589// --- Bluesky Post Creation --- 590 591export interface CreateBlueskyPostOptions { 592 title: string; 593 description?: string; 594 bskyPost?: string; 595 canonicalUrl: string; 596 coverImage?: BlobObject; 597 publishedAt: string; // Used as createdAt for the post 598} 599 600/** 601 * Count graphemes in a string (for Bluesky's 300 grapheme limit) 602 */ 603function countGraphemes(str: string): number { 604 // Use Intl.Segmenter if available, otherwise fallback to spread operator 605 if (typeof Intl !== "undefined" && Intl.Segmenter) { 606 const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" }); 607 return [...segmenter.segment(str)].length; 608 } 609 return [...str].length; 610} 611 612/** 613 * Truncate a string to a maximum number of graphemes 614 */ 615function truncateToGraphemes(str: string, maxGraphemes: number): string { 616 if (typeof Intl !== "undefined" && Intl.Segmenter) { 617 const segmenter = new Intl.Segmenter("en", { granularity: "grapheme" }); 618 const segments = [...segmenter.segment(str)]; 619 if (segments.length <= maxGraphemes) return str; 620 return `${segments 621 .slice(0, maxGraphemes - 3) 622 .map((s) => s.segment) 623 .join("")}...`; 624 } 625 // Fallback 626 const chars = [...str]; 627 if (chars.length <= maxGraphemes) return str; 628 return `${chars.slice(0, maxGraphemes - 3).join("")}...`; 629} 630 631/** 632 * Create a Bluesky post with external link embed 633 */ 634export async function createBlueskyPost( 635 agent: Agent, 636 options: CreateBlueskyPostOptions, 637): Promise<StrongRef> { 638 const { 639 title, 640 description, 641 bskyPost, 642 canonicalUrl, 643 coverImage, 644 publishedAt, 645 } = options; 646 647 // Build post text: title + description 648 // Max 300 graphemes for Bluesky posts 649 const MAX_GRAPHEMES = 300; 650 651 let postText: string; 652 653 if (bskyPost) { 654 // Custom bsky post overrides any default behavior 655 postText = bskyPost; 656 } else if (description) { 657 // Try: title + description 658 const fullText = `${title}\n\n${description}`; 659 if (countGraphemes(fullText) <= MAX_GRAPHEMES) { 660 postText = fullText; 661 } else { 662 // Truncate description to fit 663 const availableForDesc = 664 MAX_GRAPHEMES - countGraphemes(title) - countGraphemes("\n\n"); 665 if (availableForDesc > 10) { 666 const truncatedDesc = truncateToGraphemes( 667 description, 668 availableForDesc, 669 ); 670 postText = `${title}\n\n${truncatedDesc}`; 671 } else { 672 // Just title 673 postText = `${title}`; 674 } 675 } 676 } else { 677 // Just title 678 postText = `${title}`; 679 } 680 681 // Final truncation in case title or bskyPost are longer than expected 682 if (countGraphemes(postText) > MAX_GRAPHEMES) { 683 postText = truncateToGraphemes(postText, MAX_GRAPHEMES); 684 } 685 686 // Build external embed 687 const embed: Record<string, unknown> = { 688 $type: "app.bsky.embed.external", 689 external: { 690 uri: canonicalUrl, 691 title: title.substring(0, 500), // Max 500 chars for title 692 description: (description || "").substring(0, 1000), // Max 1000 chars for description 693 }, 694 }; 695 696 // Add thumbnail if coverImage is available 697 if (coverImage) { 698 (embed.external as Record<string, unknown>).thumb = coverImage; 699 } 700 701 // Create the post record 702 const record: Record<string, unknown> = { 703 $type: "app.bsky.feed.post", 704 text: postText, 705 embed, 706 createdAt: new Date(publishedAt).toISOString(), 707 }; 708 709 const response = await agent.com.atproto.repo.createRecord({ 710 repo: agent.did!, 711 collection: "app.bsky.feed.post", 712 record, 713 }); 714 715 return { 716 uri: response.data.uri, 717 cid: response.data.cid, 718 }; 719} 720 721/** 722 * Add bskyPostRef to an existing document record 723 */ 724export async function addBskyPostRefToDocument( 725 agent: Agent, 726 documentAtUri: string, 727 bskyPostRef: StrongRef, 728): Promise<void> { 729 const parsed = parseAtUri(documentAtUri); 730 if (!parsed) { 731 throw new Error(`Invalid document URI: ${documentAtUri}`); 732 } 733 734 // Fetch existing record 735 const existingRecord = await agent.com.atproto.repo.getRecord({ 736 repo: parsed.did, 737 collection: parsed.collection, 738 rkey: parsed.rkey, 739 }); 740 741 // Add bskyPostRef to the record 742 const updatedRecord = { 743 ...(existingRecord.data.value as Record<string, unknown>), 744 bskyPostRef, 745 }; 746 747 // Update the record 748 await agent.com.atproto.repo.putRecord({ 749 repo: parsed.did, 750 collection: parsed.collection, 751 rkey: parsed.rkey, 752 record: updatedRecord, 753 }); 754}