// 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);
}
};