@arcblock/did
Version:
Javascript lib to work with ArcBlock DID
46 lines (44 loc) • 1.46 kB
JavaScript
import { formatDid } from "./parse.mjs";
import { isValid } from "./index.mjs";
//#region src/short-form.ts
/**
* Short-form DID Resolution
*
* Deterministic expansion of short-form identifiers to full DIDs.
* Based on base58 checksum validation (not heuristic guessing).
*
* Rules:
* - Already a full DID (starts with "did:") → return as-is
* - Valid cryptographic address (passes isValid checksum) → did:abt:{address}
* - Everything else → did:name:{input}
*/
/**
* Expand a short-form identifier to a full DID.
*
* @param input - Short-form identifier (address, name, or full DID)
* @returns Full DID string
* @throws If input is not a non-empty string
*/
function expandShortForm(input) {
if (typeof input !== "string") throw new Error("Input must be a string");
if (!input) throw new Error("Input cannot be empty");
if (input.startsWith("did:")) return input;
if (isValid(input)) return formatDid(input, "abt");
return formatDid(input, "name");
}
/**
* Convert a full DID to its short form (strip the did:{method}: prefix).
*
* @param did - Full DID string
* @returns Short-form identifier
* @throws If input is not a non-empty string
*/
function toShortForm(did) {
if (typeof did !== "string") throw new Error("Input must be a string");
if (!did) throw new Error("Input cannot be empty");
const match = did.match(/^did:[a-z0-9]+:(.+)$/);
if (match) return match[1];
return did;
}
//#endregion
export { expandShortForm, toShortForm };