at main 2.2 kB view raw
1import { Client, CredentialManager, ok, simpleFetchHandler } from '@atcute/client'; 2import { CompositeDidDocumentResolver, PlcDidDocumentResolver, WebDidDocumentResolver } from '@atcute/identity-resolver'; 3 4// cleanup needed 5 6const docResolver = new CompositeDidDocumentResolver({ 7 methods: { 8 plc: new PlcDidDocumentResolver(), 9 web: new WebDidDocumentResolver(), 10 }, 11}); 12 13async function resolve_did(did) { 14 return await docResolver.resolve(did); 15} 16 17function pds({ service }) { 18 if (!service) { 19 throw new Error('missing service from identity doc'); 20 } 21 const { serviceEndpoint } = service[0]; 22 if (!serviceEndpoint) { 23 throw new Error('missing serviceEndpoint from identity service array'); 24 } 25 return serviceEndpoint; 26} 27 28 29async function get_pds_record(endpoint, did, collection, rkey) { 30 const handler = simpleFetchHandler({ service: endpoint }); 31 const rpc = new Client({ handler }); 32 const { ok, data } = await rpc.get('com.atproto.repo.getRecord', { 33 params: { repo: did, collection, rkey }, 34 }); 35 if (!ok) throw new Error('fetching pds record failed'); 36 return data; 37} 38 39function parse_at_uri(uri) { 40 let collection, rkey; 41 if (!uri.startsWith('at://')) { 42 throw new Error('invalid at-uri: did not start with "at://"'); 43 } 44 let remaining = uri.slice('at://'.length); // remove the at:// prefix 45 remaining = remaining.split('#')[0]; // hash is valid in at-uri but we don't handle them 46 remaining = remaining.split('?')[0]; // query is valid in at-uri but we don't handle it 47 const segments = remaining.split('/'); 48 if (segments.length === 0) { 49 throw new Error('invalid at-uri: could not find did after "at://"'); 50 } 51 const did = segments[0]; 52 if (segments.length > 1) { 53 collection = segments[1]; 54 } 55 if (segments.length > 2) { 56 rkey = segments.slice(2).join('/'); // hmm are slashes actually valid in rkey? 57 } 58 return { did, collection, rkey }; 59} 60 61export async function getAtUri(atUri) { 62 const { did, collection, rkey } = parse_at_uri(atUri); 63 const doc = await resolve_did(did); 64 const endpoint = pds(doc); 65 const { value } = await get_pds_record(endpoint, did, collection, rkey); 66 return value; 67}