UNPKG

@arcblock/did

Version:

Javascript lib to work with ArcBlock DID

77 lines (75 loc) 2.14 kB
//#region src/name.ts /** * Parse a name identifier into its hierarchy components. * * @param name - The name to parse (e.g. 'robertmao', 'bob.myorg', 'anything.local') * @returns Parsed hierarchy * @throws If name is invalid */ function parseNameHierarchy(name) { if (typeof name !== "string") throw new Error("Name must be a string"); if (!name) throw new Error("Name cannot be empty"); if (name.startsWith(".")) throw new Error("Name cannot start with a dot"); if (name.endsWith(".")) throw new Error("Name cannot end with a dot"); if (name.includes("..")) throw new Error("Name cannot contain consecutive dots"); const segments = name.split("."); if (segments.some((s) => !s)) throw new Error("Name contains empty segments"); const tld = segments[segments.length - 1]; const isLocal = tld === "local"; const isGlobal = segments.length === 1 && !isLocal; const depth = segments.length; return { segments: [...segments], tld, isLocal, isGlobal, depth }; } /** * Determine the resolve route for a name. * * - Single segment (e.g. 'robertmao') → global route * - Ends with '.local' → local route * - Multi-segment (e.g. 'bob.myorg') → delegated route * * @param name - The name to route * @returns The resolve route * @throws If name is invalid */ function getResolveRoute(name) { const hierarchy = parseNameHierarchy(name); if (hierarchy.isLocal) return { type: "local", name: hierarchy.segments.slice(0, -1).join(".") }; if (hierarchy.isGlobal) return { type: "global", name }; const subName = hierarchy.segments.slice(0, -1).join("."); return { type: "delegated", tld: hierarchy.tld, subName }; } /** * Check if a name is a .local name. */ function isLocalName(name) { if (!name || !name.includes(".")) return false; return name.endsWith(".local"); } /** * Check if a name is a global name (single segment, not .local). */ function isGlobalName(name) { if (!name) return false; return !name.includes("."); } //#endregion exports.getResolveRoute = getResolveRoute; exports.isGlobalName = isGlobalName; exports.isLocalName = isLocalName; exports.parseNameHierarchy = parseNameHierarchy;