~james/core

core/web/src/lib/api/uri.ts -rw-r--r-- 1.3 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// at-uri helpers: at://<authority>/<collection>/<rkey>

import { parseResourceUri } from "@atcute/lexicons/syntax";
import { didOf, recordKeyOf, type Did, type Rkey } from "#lib/api/syntax.ts";

const legacyAuthority = (uri: string): string => {
	const rest = uri.startsWith("at://") ? uri.slice(5) : uri;
	const slash = rest.indexOf("/");
	return slash === -1 ? rest : rest.slice(0, slash);
};

export const didFromUri = (uri: string): Did => {
	try {
		return didOf(parseResourceUri(uri).repo);
	} catch {
		return didOf(legacyAuthority(uri));
	}
};

export const collectionFromUri = (uri: string): string | undefined => {
	try {
		return parseResourceUri(uri).collection;
	} catch {
		return undefined;
	}
};

// on a knot the uri names the repo, and x-tngl-editor is whoever wrote the latest version
export const authorDidOf = (record: { uri: string; value?: unknown }): Did => {
	const editor = (record.value as Record<string, unknown> | undefined)?.["x-tngl-editor"];
	return typeof editor === "string" ? didOf(editor) : didFromUri(record.uri);
};

export const rkeyFromUri = (uri: string): Rkey => {
	const fallback = uri.slice(uri.lastIndexOf("/") + 1);
	try {
		return recordKeyOf(parseResourceUri(uri).rkey ?? fallback);
	} catch {
		return recordKeyOf(fallback);
	}
};