1import type { Agent } from "@atproto/api"; 2import type { 3 GetLeafletDocumentsParams, 4 GetSingleLeafletDocumentParams, 5 MiniDoc, 6} from "./types.js"; 7import { LiveLoaderError } from "./leaflet-live-loader.js"; 8 9export function uriToRkey(uri: string) { 10 const rkey = uri.split("/").pop(); 11 if (!rkey) { 12 throw new Error("Failed to get rkey from uri."); 13 } 14 return rkey; 15} 16 17export async function resolveMiniDoc(handleOrDid: string) { 18 try { 19 const response = await fetch( 20 `https://slingshot.microcosm.blue/xrpc/com.bad-example.identity.resolveMiniDoc?identifier=${handleOrDid}`, 21 ); 22 23 if (!response.ok || response.status >= 300) { 24 throw new Error( 25 `could not resolve did doc due to invalid handle or did ${handleOrDid}`, 26 ); 27 } 28 const data = (await response.json()) as MiniDoc; 29 30 return data.pds; 31 } catch (error) { 32 throw new Error(`failed to resolve handle: ${handleOrDid}`); 33 } 34} 35 36export async function getLeafletDocuments({ 37 repo, 38 reverse, 39 cursor, 40 agent, 41 limit, 42}: GetLeafletDocumentsParams) { 43 const response = await agent.com.atproto.repo.listRecords({ 44 repo, 45 collection: "pub.leaflet.document", 46 cursor, 47 reverse, 48 limit, 49 }); 50 51 if (response.success === false) { 52 throw new LiveLoaderError( 53 "Could not fetch leaflet documents", 54 "FETCH_FAILED", 55 ); 56 } 57 58 return response?.data?.records; 59} 60 61export async function getSingleLeafletDocument({ 62 agent, 63 repo, 64 id, 65}: GetSingleLeafletDocumentParams) { 66 const response = await agent.com.atproto.repo.getRecord({ 67 repo, 68 collection: "pub.leaflet.document", 69 rkey: id, 70 }); 71 72 if (response.success === false) { 73 throw new LiveLoaderError( 74 "error fetching document", 75 "DOCUMENT_FETCH_ERROR", 76 ); 77 } 78 79 return response; 80}