@arcblock/did
Version:
Javascript lib to work with ArcBlock DID
45 lines (43 loc) • 1.5 kB
JavaScript
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
let _ocap_util = require("@ocap/util");
let lodash_padStart = require("lodash/padStart");
lodash_padStart = require_rolldown_runtime.__toESM(lodash_padStart);
//#region src/util.ts
const DID_PREFIX = "did:abt:";
/**
* Convert did to bytes with length of 26
*
* @param {string} did
* @returns {Buffer}
*/
const toBytes = (did) => {
try {
if ((0, _ocap_util.isHexStrict)(did)) return Buffer.from((0, _ocap_util.stripHexPrefix)(did), "hex");
let bytes = (0, _ocap_util.fromBase58)(did.replace(/^did:[a-z0-9]+:/, ""));
while (bytes.length < 26) bytes = Buffer.concat([Uint8Array.from([0]), Uint8Array.from(bytes)]);
return bytes;
} catch (err) {
throw new Error(`Cannot convert DID string to byte array: ${err.message}`);
}
};
/**
* Convert number to bit string with predefined length
*/
const toBits = (number, length) => (0, lodash_padStart.default)((0, _ocap_util.toBN)(number).toString(2), length, "0");
/**
* Ensure the hex length is even number, 2, 4, 6, 8
*
* @param {string} hex
* @param {number} length
* @returns {string} hex
*/
const toStrictHex = (hex, length) => {
const str = hex.replace(/^0x/i, "");
if (typeof length === "number" && length % 2 === 0) return (0, lodash_padStart.default)(hex, length, "0");
return str.length % 2 === 0 ? str : `0${str}`;
};
//#endregion
exports.DID_PREFIX = DID_PREFIX;
exports.toBits = toBits;
exports.toBytes = toBytes;
exports.toStrictHex = toStrictHex;