diff --git a/packages/did/README.md b/packages/did/README.md index 047a92b..21cade2 100644 --- a/packages/did/README.md +++ b/packages/did/README.md @@ -34,6 +34,10 @@ Used to describe which Tangle network interacts. * [~decodeFromDid(tangleid)](#module_did..decodeFromDid) + * [~isDidUrl(url)](#module_did..isDidUrl) + + * [~decodeFromDidUrl(url)](#module_did..decodeFromDidUrl) + * [~createMetaPublicKeys(controller, publicKeyPems)](#module_did..createMetaPublicKeys) @@ -62,6 +66,28 @@ Encode TangleID DID with specific network and address. Decode infromation of network and address from TangleID. **Returns**: Object - } The infromation of network and address. + + +### *did*~isDidUrl(url) + +| Param | Type | Description | +| --- | --- | --- | +| url | string | the URL to be checked. | + +Checks if given URL is a DID URL. + +**Returns**: boolean - The boolean that represent the url whether DID URL. + + +### *did*~decodeFromDidUrl(url) + +| Param | Type | Description | +| --- | --- | --- | +| url | string | the DID URL that will be decoded. | + +Decode information of the DID URL. + +**Returns**: Object - The information of the DID URL. [https://w3c-ccg.github.io/did-spec/#generic-did-syntax](https://w3c-ccg.github.io/did-spec/#generic-did-syntax) ### *did*~createMetaPublicKeys(controller, publicKeyPems) diff --git a/packages/did/src/did.ts b/packages/did/src/did.ts index 3cdc9a3..02d9d0a 100644 --- a/packages/did/src/did.ts +++ b/packages/did/src/did.ts @@ -3,6 +3,9 @@ import { encodeToMnid, decodeFromMnid } from '@tangleid/mnid'; // @ts-ignore import { parse } from 'did-resolver'; import { Did, MnidModel, PublicKeyPem, PublicKeyMeta } from '../../types'; + +const DID_URL_REGEX = /^did:(?[a-z0-9]+):(?[A-Za-z0-9\.\-_]+)(?:#(?.*))?$/; + /** * Encode TangleID DID with specific network and address. * @function encodeToDid @@ -36,6 +39,39 @@ export const decodeFromDid = (tangleid: Did): MnidModel => { return mamParsed; }; +/** + * Checks if given URL is a DID URL. + * @function isDidUrl + * @param {string} url - the URL to be checked. + * @return {boolean} The boolean that represent the url whether DID URL. + */ +export const isDidUrl = (url: string): boolean => { + return DID_URL_REGEX.test(url); +}; + +/** + * Decode information of the DID URL. + * @function decodeFromDidUrl + * @param {string} url - the DID URL that will be decoded. + * @return {{did: string, method: string, idstring: string, fragment: string | null}} + * The information of the DID URL. {@link https://w3c-ccg.github.io/did-spec/#generic-did-syntax} + */ +export const decodeFromDidUrl = (url: string) => { + const matches = DID_URL_REGEX.exec(url); + if (matches === null) { + throw new Error('Invalid DID URL'); + } + + const [, method, idstring, fragment] = matches; + + return { + did: `did:${method}:${idstring}`, + method, + idstring, + fragment: fragment || null, + }; +}; + /** * Create metadata of public keys from PEM-formatted public Keys. * @function createMetaPublicKeys