UNPKG

@kodex-data/prototypes

Version:

A library of TypeScript prototypes that extend built-in types in JavaScript, providing additional functionality to make development easier and more efficient. This library includes prototypes for working with big numbers, Ethereum Virtual Machine (EVM) fu

1,138 lines (1,120 loc) 37 kB
'use strict'; var Uint8Arrays = require('uint8arrays'); var bignumber_js = require('bignumber.js'); var bignumber = require('@ethersproject/bignumber'); var lodash = require('lodash'); var multiformats = require('multiformats'); var sha3 = require('js-sha3'); var BN = require('bn.js'); var base16 = require('multiformats/bases/base16'); function _interopNamespaceDefault(e) { var n = Object.create(null); if (e) { Object.keys(e).forEach(function (k) { if (k !== 'default') { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); } n.default = e; return Object.freeze(n); } var Uint8Arrays__namespace = /*#__PURE__*/_interopNamespaceDefault(Uint8Arrays); const EVM_NUMBER = /^-{0,1}\d+$/; const EVM_HEX = /^0x|[0-9a-f]+$/i; const EVM_EMPTY_ADDR = /^0x[0]{40}$/; const EVM_ADDRESS = /^0x[a-fA-F\d]{40}$/; const EVM_HASH = /^0x[a-fA-F\d]{64}$/; const TWITTER_REGEX = /http(?:s)?:\/\/(?:www\.)?twitter\.com\/([a-zA-Z0-9_]+)/; function isTwitterUrl(url) { return TWITTER_REGEX.test(url); } function getTwitterUsername(url) { if (isTwitterUrl(url)) { const result = TWITTER_REGEX.exec(url); if (result) return Array.from(result)[1]; } } const saveParse = (data, errorHandler) => { try { if (!data || !isValidJSON(data)) throw new Error('INVALID JSON PROVIDED'); const parsed = JSON.parse(data); return parsed; } catch (eParse) { if (errorHandler) errorHandler(eParse); return; } }; function toSha256Hex(str) { const { createHash } = require('crypto'); return createHash('sha256').update(str).digest('hex'); } /** * Checks if a piece of code is valid JSON * @date 5/24/2022 - 12:20:00 AM * * @export * @param {string} code containing a piece of JSON code * @returns {code is string} */ function isValidJSON(code) { try { // Check for common JSON syntax errors using regex const regex = /^[\],:{}\s]*$/.test(code .replace(/\\["\\\/bfnrtu]/g, '@') .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']') .replace(/(?:^|:|,)(?:\s*\[)+/g, '')); if (!regex) { return false; } JSON.parse(code); return true; } catch (e) { return false; } } class ToJSON_WithSpaces_Options { constructor() { this.insideObjectBraces = false; this.insideArrayBrackets = false; this.betweenPropsOrItems = true; this.betweenPropNameAndValue = true; } } function ToJSON_WithSpaces(obj, options) { options = Object.assign({}, new ToJSON_WithSpaces_Options(), options); let result = JSON.stringify(obj, null, 1); // stringify, with line-breaks and indents result = result.replace(/^ +/gm, ' '); // remove all but the first space for each line result = result.replace(/\n/g, ''); // remove line-breaks if (!options.insideObjectBraces) result = result.replace(/{ /g, '{').replace(/ }/g, '}'); if (!options.insideArrayBrackets) result = result.replace(/\[ /g, '[').replace(/ \]/g, ']'); if (!options.betweenPropsOrItems) result = result.replace(/, /g, ','); if (!options.betweenPropNameAndValue) result = result.replace(/": /g, `":`); return result; } function formatJSON(input, options) { const parsed = saveParse(input); if (isValidJSON(input)) return ToJSON_WithSpaces(parsed, options || { betweenPropNameAndValue: true }); return input; } const genRanHex = (size) => [...Array(size)].map(() => Math.floor(Math.random() * 16).toString(16)).join(''); function isError(candidate) { if (candidate instanceof Error) return true; return false; } function createError(message, ...metaData) { const error = isError(message) ? message : new Error(message); let meta = { timestamp: new Date().valueOf() }; if (metaData && Array.isArray(metaData) && metaData.length > 0) { for (const item of metaData) { if (lodash.isObject(item)) meta = Object.assign(Object.assign({}, meta), item); } } Object.assign(error, meta); return error; } function matcher$1(regex, txt) { const matches = []; let match = regex.exec(txt); while (match != null) { const candidate = match[0]; if (!matches.includes(candidate) && regex.test(candidate)) matches.push(candidate); match = regex.exec(txt); } return matches; } function compare(candidate, comparator, checkAddr) { if (!isHEX$1(candidate) || (checkAddr && !isAddress(candidate))) throw new Error('INVALID ADDRESS ' + candidate); if (!isHEX$1(comparator) || (checkAddr && !isAddress(comparator))) throw new Error('INVALID COMPARE ADDRESS ' + comparator); if (candidate.toLowerCase() === comparator.toLowerCase()) return true; return false; } function findHex(str, _type = 'hex', match = EVM_HEX) { if (_type === 'address') match = EVM_ADDRESS; if (_type === 'keccak') match = EVM_HASH; return lodash.uniq(matcher$1(match, str) || []); } function isEtherAddress(query) { return EVM_EMPTY_ADDR.test(query); } function isKeccakHash(query) { return EVM_HASH.test(query); } function isAddress(query) { return EVM_ADDRESS.test(query); } function toHEX$1(input) { return multiformats.bytes.toHex(Uint8Arrays.fromString(input)); } function fromHEX$1(input) { return Uint8Arrays.toString(multiformats.bytes.fromHex(input)); } function isHEX$1(input) { return EVM_HEX.test(input); } function toUint(inputValue) { return lodash.padStart(toHEX$1(new bignumber_js.BigNumber(inputValue).toFixed()).substring(2), 64, '0'); } function parseUint(inputValue, add0x) { const value = inputValue instanceof bignumber_js.BigNumber ? inputValue.toFixed() : new bignumber_js.BigNumber(inputValue.toString()).toFixed(); const result = lodash.padStart(toHEX$1(value).substring(2), 64, '0'); return add0x ? `0x${result}` : result; } function toSHA3(data) { return '0x' + sha3.keccak_256(data); } function isNumber(query) { return EVM_NUMBER.test(query); } function strip0x(input) { if (!isHEX$1(input)) return input; return input.replace(/0x/i, ''); } /** * Calculates the checksum address of an EVM address. * @date 11.7.2023 - 20:50:02 * * @export * @param {string} address - The EVM address (with or without '0x' prefix). * @returns {string} The checksum address. */ function toChecksumAddress(address) { address = address.toLowerCase().replace('0x', ''); const hash = sha3.keccak_256(address); let checksumAddress = '0x'; for (let i = 0; i < address.length; i++) { if (parseInt(hash[i], 16) >= 8) { checksumAddress += address[i].toUpperCase(); } else { checksumAddress += address[i]; } } return checksumAddress; } /** * Returns the Unix timestamp (number of seconds since January 1, 1970) rounded up to the nearest second. * @date 8.3.2023 - 09:53:47 * * @export * @returns {number} - The Unix timestamp in seconds. */ function timestamp() { return Math.ceil(new Date().valueOf() / 1e3); } /** * Returns a promise that resolves after a given number of milliseconds. * @date 8.3.2023 - 09:54:22 * * @export * @param {number} ms - The number of milliseconds to wait before resolving the promise. * @returns {Promise<void>} - A promise that resolves after the specified number of milliseconds */ function sleep(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } /** * Converts a Unix timestamp to a date string in the format "MM/DD/YYYY HH:MM:SS". * @date 8.3.2023 - 09:55:03 * * @export * @param {number} ts - The Unix timestamp in seconds. * @returns {string} - The date string in the format "MM/DD/YYYY HH:MM:SS". */ function ts2date(ts) { const d = new Date(ts * 1e3); return ([d.getMonth() + 1, d.getDate(), d.getFullYear()].join('/') + ' ' + [d.getHours(), d.getMinutes(), d.getSeconds()].join(':')); } /** * Formats a date object as a string in the format "YYYY-MM-DD". * @date 8.3.2023 - 09:56:08 * * @export * @param {Date} date - The date object to format. * @returns {string} The formatted date string in the format "YYYY-MM-DD". */ function formatMMDDYYYY(date) { return date.getFullYear() + '-' + date.getMonth().toString().padStart(2, '0') + '-' + date.getDate().toString().padStart(2, '0'); } /** * Converts a number of seconds to a human-readable string in the format "X units". * @date 8.3.2023 - 09:56:41 * * @export * @param {number} seconds - The number of seconds to convert. * @param {?string} [tags=''] - (optional) The HTML tags to wrap around the unit name. Defaults to an empty string. * @returns {string} The human-readable string in the format "X units". */ function sec2read(seconds, tags = '') { if (seconds <= 0) { if (tags === '') { return '0 seconds'; } else { return '<' + tags + '>0</' + tags + '>'; } } let units = ['years', 'months', 'days', 'hours', 'minutes', 'seconds']; let divisors = [365.25 * 24 * 60 * 60, 30.4 * 24 * 60 * 60, 24 * 60 * 60, 60 * 60, 60, 1]; for (let idx in units) { var unit = units[idx]; var divisor = divisors[idx]; if (seconds > divisor) { if (tags === '') { return (seconds / divisor).toFixed(1) + ' ' + unit; } else { return (seconds / divisor).toFixed(1) + ' <' + tags + '>' + unit + '</' + tags + '>'; } } } if (tags === '') { return `${seconds.toFixed()} seconds`; } else { return `${seconds.toFixed(1)} <${tags}>seconds</${tags}>`; } } /** * Returns the time part of a Date object in the format "HH:MM:SS" or "HH:MM:SS:MS" if addMS is true. * @date 8.3.2023 - 09:57:48 * * @export * @param {Date} date - The Date object to format. * @param {?boolean} [addMS] - Optional. Whether to include the milliseconds part in the returned string. * @returns {string} - The time part of the Date object in the specified format. */ function formatHHMMSS(date, addMS) { const hhmmss = date.toTimeString().split(' ')[0]; if (addMS) { const ms = date.getMilliseconds().toLocaleString('en-US', { minimumIntegerDigits: 4, useGrouping: false }); return `${hhmmss}:${ms}`; } else { return hhmmss; } } /** * Returns an array of strings representing the days of the specified month and year. * Each string in the array has the format "DD-dayName", where "DD" is the day of the month and "dayName" is the name of the day (e.g. "01-Sun"). * @date 8.3.2023 - 09:59:43 * * @export * @param {number} year - The year of the month to get days for. * @param {number} month - The month to get days for (1-based). * @returns {string[]} - An array of strings representing the days of the specified month and year. */ function getDaysArray(year, month) { const names = Object.freeze(['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat']); const date = new Date(year, month - 1, 1); const result = []; while (date.getMonth() == month - 1) { result.push(`${date.getDate()}-${names[date.getDay()]}`); date.setDate(date.getDate() + 1); } return result; } /** * Converts the specified input into a big number object. * @date 8.3.2023 - 08:25:00 * * @export * @param {ToBnInputs} input The input to convert. * @param {ToBnOptions} [options={}] Options for the conversion. * @param {?BnTypes} options.type - The library to use for big number conversion. Defaults to 'bignumber.js'. * @param {?number} options.base - The base to use when converting from a string. Only used for 'bignumber.js'. * @returns {BN | BigNumber | BigNumberJS | bigint} The input as a big number object. */ function toBN(input, options = {}) { if (!options.type) options.type = 'bignumber.js'; if (input instanceof bignumber_js.BigNumber) { input = input.toFixed(); } else { input = input.toString(); } switch (options.type) { case 'bignumber.js': return new bignumber_js.BigNumber(input, options.base); case 'ethers-bn': return bignumber.BigNumber.from(input); case 'bn.js': return new BN(input); case 'bigint': return BigInt(input); default: throw new Error('unsupported bignumber format'); } } /** * Converts a number to a pretty string with thousands separators. * @date 8.3.2023 - 08:30:06 * * @export * @param {(string | number | BigNumber | BigNumberJS)} input The input number as a string, number, BigNumber, or BigNumberJS. * @returns {string} The input number as a pretty string. */ function prettyNum(input) { if (input instanceof bignumber_js.BigNumber) input = input.toFixed(); if (input instanceof bignumber.BigNumber) input = input.toString(); return Number(input).toLocaleString(); } /** * Computes the sum of an array of numbers or BigNumbers. * @date 8.3.2023 - 08:30:17 * * @export * @param {(string | number | BigNumber | BigNumberJS)[]} inputs The array of numbers or BigNumbers to sum. * @returns {BigNumberJS} The sum of the input array as a BigNumberJS. */ function sum(inputs) { return inputs.reduce((sum, input) => { return sum.plus(new bignumber_js.BigNumber(input.toString())); }, new bignumber_js.BigNumber(0)); } /** * Computes the mean of an array of numbers or BigNumbers. * @date 8.3.2023 - 08:30:11 * * @export * @param {(string | number | BigNumber | BigNumberJS)[]} inputs The array of numbers or BigNumbers to compute the mean of. * @returns {BigNumberJS} The mean of the input array as a BigNumberJS. */ function mean(inputs) { return sum(inputs).dividedBy(inputs.length); } /** * Computes the minimum and maximum values of an array of numbers or BigNumbers. * @date 8.3.2023 - 08:30:50 * * @export * @param {(string | number | BigNumber | BigNumberJS)[]} items The array of numbers or BigNumbers to compute the minimum and maximum of. * @returns {MinMax} An object containing the minimum and maximum values as BigNumberJS instances. */ function minMax(items) { return items.reduce((acc, _val) => { const val = toBN(_val); acc.min = !acc.min || val.lt(acc.min) ? val : acc.min; acc.max = !acc.max || val.lt(acc.max) ? val : acc.max; return acc; }, {}); } /** * Computes the minimum value of an array of numbers or BigNumbers. * @date 8.3.2023 - 08:30:56 * * @export * @param {(string | number | BigNumber | BigNumberJS)[]} items The array of numbers or BigNumbers to compute the minimum of. * @returns {(BigNumberJS)} The minimum value of the input array as a BigNumberJS. */ function min(items) { return minMax(items).min; } /** * Computes the maximum value of an array of numbers or BigNumbers. * @date 8.3.2023 - 08:31:01 * * @export * @param {(string | number | BigNumber | BigNumberJS)[]} items The array of numbers or BigNumbers to compute the maximum of. * @returns {(BigNumberJS)} The maximum value of the input array as a BigNumberJS. */ function max(items) { return minMax(items).max; } function toFraction(input, asBigInt) { if (input instanceof bignumber_js.BigNumber) input = input.toFixed(); if (input instanceof bignumber.BigNumber) input = input.toString(); const [mul, div] = new bignumber_js.BigNumber(input).toFraction(); if (asBigInt === true) return { mul, div }; return { mul: mul.toFixed(), div: div.toFixed() }; } /** * Shifts the decimal point of a given `bigint` by the specified number of positions. * @returns {bigint} * @date 7.7.2023 - 23:40:36 * * @export * @param {bigint} input - The `bigint` number to shift. * @param {number} n - The number of positions to shift the decimal point. * A positive value shifts the decimal point to the right, and a negative value to the left. * @returns {bigint} The `bigint` with the decimal point shifted by `n` positions. */ function shiftedBy(input, n) { const powerOf10 = BigInt(Math.pow(10, Math.abs(n))); const isNegativeShift = n < 0; if (isNegativeShift) { return input / powerOf10; } else { return input * powerOf10; } } var utils = /*#__PURE__*/Object.freeze({ __proto__: null, EVM_ADDRESS: EVM_ADDRESS, EVM_EMPTY_ADDR: EVM_EMPTY_ADDR, EVM_HASH: EVM_HASH, EVM_HEX: EVM_HEX, EVM_NUMBER: EVM_NUMBER, TWITTER_REGEX: TWITTER_REGEX, ToJSON_WithSpaces: ToJSON_WithSpaces, ToJSON_WithSpaces_Options: ToJSON_WithSpaces_Options, compare: compare, createError: createError, findHex: findHex, formatHHMMSS: formatHHMMSS, formatJSON: formatJSON, formatMMDDYYYY: formatMMDDYYYY, fromHEX: fromHEX$1, genRanHex: genRanHex, getDaysArray: getDaysArray, getTwitterUsername: getTwitterUsername, isAddress: isAddress, isError: isError, isEtherAddress: isEtherAddress, isHEX: isHEX$1, isKeccakHash: isKeccakHash, isNumber: isNumber, isTwitterUrl: isTwitterUrl, isValidJSON: isValidJSON, max: max, mean: mean, min: min, minMax: minMax, parseUint: parseUint, prettyNum: prettyNum, saveParse: saveParse, sec2read: sec2read, shiftedBy: shiftedBy, sleep: sleep, strip0x: strip0x, sum: sum, timestamp: timestamp, toBN: toBN, toChecksumAddress: toChecksumAddress, toFraction: toFraction, toHEX: toHEX$1, toSHA3: toSHA3, toSha256Hex: toSha256Hex, toUint: toUint, ts2date: ts2date }); Number.prototype.isOdd = function () { return this % 2 === 1; }; Number.prototype.toUint = function (add0x) { return parseUint(this, add0x); }; Number.prototype.toHex = function () { return `0x${this.toString(16)}`; }; String.prototype.parseJSON = function (errorHandler) { if (errorHandler) return saveParse(String(this), errorHandler); if (!isValidJSON(String(this))) throw new Error('INPUT STRING IS NOT VALID JSON FORMAT'); return JSON.parse(String(this)); }; String.prototype.isValidJSON = function () { try { return isValidJSON(String(this)); } catch (error) { } return false; }; String.prototype.isValidJson = String.prototype.isValidJSON; String.prototype.sleep = function () { return new Promise((resolve) => setTimeout(resolve, parseInt(this))); }; String.prototype.formatJSON = function (options) { return formatJSON(String(this), options); }; String.prototype.formatJson = String.prototype.formatJSON; String.prototype.rndHex = function (l) { let len; if (this.isNumber()) len = Number(this); else if (!this.isNumber() && l) len = l; else l = 6; return `0x${genRanHex(len)}`; }; String.prototype.isTwitterUrl = function () { return isTwitterUrl(this); }; String.prototype.getTwitterUsername = function () { return getTwitterUsername(this); }; String.prototype.trimAddress = function () { return `${this.slice(0, 10)}...${this.slice(-10)}`; }; String.prototype.isValidJSON = function () { return isValidJSON(this); }; String.prototype.findHex = function (_type) { return findHex(this, _type); }; String.prototype.isEtherAddress = function () { return isEtherAddress(this); }; String.prototype.addrIsEqual = function (address) { return compare(this, address, true); }; String.prototype.toUint = function (add0x) { return parseUint(this, add0x); }; String.prototype.toSha3 = function () { return toSHA3(this); }; String.prototype.toUtf8Bytes = function () { return Uint8Arrays__namespace.fromString(this); }; String.prototype.toHex = function () { return toHEX$1(this); }; String.prototype.toAscii = function () { return toHEX$1(this); }; String.prototype.isKeccakHash = function () { return isKeccakHash(this); }; String.prototype.isHex = function () { return isHEX$1(this); }; String.prototype.isAddress = function () { return isAddress(this); }; String.prototype.toChecksumAddress = function () { return toChecksumAddress(this); }; String.prototype.strip0x = function () { return strip0x(this); }; String.prototype.isNumber = function () { return isNumber(this); }; function _strictLength(input, l) { const isValid = input.strip0x().length % l === 0; if (!isValid) throw new Error(`invalid string length. not a power of ${l}`); } String.prototype.split64 = function (_strict) { if (_strict === true) _strictLength(this, 64); return this.replace(/0x/i, '').match(/.{1,64}/g) || []; }; String.prototype.split32 = function (_strict) { if (_strict === true) _strictLength(this, 32); return this.replace(/0x/i, '').match(/.{1,32}/g) || []; }; if (typeof String.prototype.prettyNum === 'undefined') { String.prototype.prettyNum = function () { return prettyNum(this); }; } if (typeof Number.prototype.prettyNum === 'undefined') { Number.prototype.prettyNum = function () { return prettyNum(this); }; } if (typeof String.prototype.toBN === 'undefined') { String.prototype.toBN = function (param1, param2) { return toBN(this, { type: param1, base: param2 }); }; } if (typeof Number.prototype.toBN === 'undefined') { Number.prototype.toBN = function (param1, param2) { return toBN(this, { type: param1, base: param2 }); }; } if (typeof String.prototype.shiftedBy === 'undefined') { String.prototype.shiftedBy = function (n, ...rest) { //if (!this.isNumber()) return this if (!Number.isSafeInteger(n)) return this; try { const bn = new bignumber_js.BigNumber(this).shiftedBy(n); if (rest[0] === true) return bn; return bn.toFixed(); } catch (error) { return self; } }; } if (typeof Number.prototype.shiftedBy === 'undefined') { Number.prototype.shiftedBy = function (n, ...rest) { const bn = new bignumber_js.BigNumber(this).shiftedBy(n); if (rest[0]) return bn; return bn.toFixed(); }; } if (typeof Number.prototype.noExponents === 'undefined') { Number.prototype.noExponents = function () { var data = String(this).split(/[eE]/); if (data.length === 1) return data[0]; var z = '', sign = this < 0 ? '-' : '', str = data[0].replace('.', ''), mag = Number(data[1]) + 1; if (mag < 0) { z = sign + '0.'; while (mag++) z += '0'; // eslint-disable-next-line return z + str.replace(/^\-/, ''); } mag -= str.length; while (mag--) z += '0'; return str + z; }; } if (typeof bignumber.BigNumber.prototype.toBN === 'undefined') { bignumber.BigNumber.prototype.toBN = function (param1, param2) { return toBN(this, { type: param1, base: param2 }); }; } if (typeof bignumber_js.BigNumber.prototype.toBN === 'undefined') { bignumber_js.BigNumber.prototype.toBN = function (param1, param2) { return toBN(this, { type: param1, base: param2 }); }; } if (typeof bignumber.BigNumber.prototype.shiftedBy === 'undefined') { bignumber.BigNumber.prototype.shiftedBy = function (n) { return this.toString().shiftedBy(n); }; } if (typeof bignumber_js.BigNumber.prototype.pretty === 'undefined') { bignumber_js.BigNumber.prototype.pretty = function () { return prettyNum(this); }; } if (typeof bignumber.BigNumber.prototype.pretty === 'undefined') { bignumber.BigNumber.prototype.pretty = function () { return prettyNum(this); }; } if (typeof bignumber.BigNumber.prototype.toFraction === 'undefined') { bignumber.BigNumber.prototype.toFraction = function () { return toFraction(this); }; } if (typeof BigInt.prototype.toNumber === 'undefined') { BigInt.prototype.toNumber = function () { return parseInt(this.toString()); }; } if (typeof BigInt.prototype.shiftedBy === 'undefined') { BigInt.prototype.shiftedBy = function (n, asBn) { if (asBn && asBn === true) { return new bignumber_js.BigNumber(this.toString()).shiftedBy(n); } return shiftedBy(this, n); }; } if (typeof BigInt.prototype.toBN === 'undefined') { BigInt.prototype.toBN = function (param1, param2) { return toBN(this, { type: param1, base: param2 }); }; } if (typeof String.prototype.toFraction === 'undefined') { String.prototype.toFraction = function (asBigInt) { if (asBigInt === 'bigint') { const { mul, div } = toFraction(this, true); return { div: div.toBN('bigint'), mul: mul.toBN('bigint') }; } else { return toFraction(this, asBigInt); } }; } /** * Regular expression pattern for matching CID v1. * @date 8.3.2023 - 09:26:36 * * @type {RegExp} */ const CID_V1 = /bafy[a-zA-Z0-9a-z]{55}/g; /** * Regular expression pattern for matching CID v0. * @date 8.3.2023 - 09:26:36 * * @type {RegExp} */ const CID_V0 = /Qm[a-zA-Z0-9a-f]{44}/g; /** * Returns an array of all CIDs that match the provided regular expression pattern in the given text. * @date 8.3.2023 - 09:27:36 * * @export * @param {RegExp} regex - Regular expression pattern to match CIDs. * @param {string} txt - Text to search for CIDs. * @returns {string[]} - An array of CIDs that match the provided regular expression pattern. */ function matcher(regex, txt) { const matches = []; let match = regex.exec(txt); while (match != null) { const candidate = match[0]; if (typeof candidate === 'string' && candidate.isCID()) { if (!matches.includes(candidate)) matches.push(candidate); } match = regex.exec(txt); } return matches; } /** * Extracts IPFS hashes from the provided URI * @date 8.3.2023 - 09:35:03 * * @export * @param {string} uri - The URI to extract IPFS hashes from * @returns {string[]} An array of IPFS hashes */ function extractIpfsHashes(uri) { let cids = []; const candidatesV0 = matcher(CID_V0, uri); if (candidatesV0.length === 0) { const candidatesV1 = matcher(CID_V1, uri); if (candidatesV1.length > 0) candidatesV1.map(x => !cids.includes(x) && cids.push(x)); } else candidatesV0.map(x => !cids.includes(x) && cids.push(x)); return cids; } /** * Extracts the first IPFS hash from the provided URI * @date 8.3.2023 - 09:35:42 * * @export * @param {string} uri - The URI to extract the IPFS hash from * @returns {string} The first IPFS hash in the URI, or undefined if no hash was found */ function extractIpfsHash(uri) { return extractIpfsHashes(uri)[0]; } /** * Finds all Content Identifiers (CIDs) in the provided string * @date 8.3.2023 - 09:36:26 * * @export * @param {string} txt - The string to search for CIDs in * @returns {string[]} An array of unique CIDs found in the string */ function findCIDs(txt) { return lodash.uniq(matcher(CID_V0, txt).concat(matcher(CID_V1, txt))); } /** * Determines whether the provided string is a hexadecimal string * @date 8.3.2023 - 09:37:02 * * @export * @param {string} input - The string to test * @returns {boolean} True if the string is hexadecimal, false otherwise */ function isHEX(input) { return /^0x|[0-9a-f]+$/i.test(input); } /** * Converts the provided string to a hexadecimal string * @date 8.3.2023 - 09:37:55 * * @export * @param {string} input - The string to convert * @returns {string} The hexadecimal representation of the input string */ function toHEX(input) { return multiformats.bytes.toHex(Uint8Arrays.fromString(input)); } /** * Converts the provided hexadecimal string to a regular string * @date 8.3.2023 - 09:38:00 * * @export * @param {string} input - The hexadecimal string to convert * @returns {string} The regular string representation of the input hexadecimal string */ function fromHEX(input) { return Uint8Arrays.toString(multiformats.bytes.fromHex(input)); } /** * Determines whether the provided string is a CID version 0 (v0) hash * @date 8.3.2023 - 09:39:15 * * @export * @param {string} query - The string to test * @returns {boolean} True if the string is a v0 CID hash, false otherwise */ function isV0(query) { return /^Qm[a-zA-Z0-9a-f]{44}$/.test(query); } /** * Determines whether the provided string is a CID version 1 (v1) hash * @date 8.3.2023 - 09:39:15 * * @export * @param {string} query - The string to test * @returns {boolean} True if the string is a v1 CID hash, false otherwise */ function isV1(query) { return /^bafy[a-zA-Z0-9a-f]{55}$/.test(query); } /** * Determines whether the provided string is a hexadecimal CID hash * @date 8.3.2023 - 09:40:43 * * @export * @param {string} input - The string to test * @returns {boolean} True if the string is a hexadecimal CID hash, false otherwise */ function isHexCID(input) { return isHEX(input) && input.length >= 73 && input.length <= 75; } /** * Determines whether the provided string is a valid CID hash * @date 8.3.2023 - 09:41:12 * * @export * @param {string} input - The string to test * @param {?CIDVersions} [version] - The CID version to check for (optional) * @returns {boolean} True if the string is a valid CID hash, false otherwise */ function isCID(input, version) { if (!version) return isHexCID(input) || isV0(input) || isV1(input); switch (version) { case 'v0': return isV0(input); case 'v1': return isV1(input); case 'hex': return isHexCID(input); default: return false; } } /** * Gets the CID version of the provided CID hash * @date 8.3.2023 - 09:41:52 * * @export * @param {string} input - The CID hash to get the version of * @returns {CIDVersions} The version of the CID hash ('v0', 'v1', or 'hex') * @throws {Error} An error if the input string is not a valid CID hash */ function getCIDVersion(input) { if (isHexCID(input)) return 'hex'; if (isV0(input)) return 'v0'; if (isV1(input)) return 'v1'; throw new Error('invalid cid ' + input); } /** * Returns an object with the string representation of the input CID in various versions. * @date 8.3.2023 - 09:43:37 * * @export * @param {CID} cid - The input CID to be converted to various versions. * @returns {{ v0: string, v1: string, hex: string }} - Object containing string representation of the input CID in various versions */ function getCIDs(cid) { return { v0: cid.toV0().toString(), v1: cid.toV1().toString(), hex: cid.toV1().toString(base16.base16.encoder) }; } /** * Parses the input string into a CID object. * @date 8.3.2023 - 09:44:50 * * @export * @param {string} input - The input string to be parsed into a CID object. * @param {?CIDVersions} [version] - The version of CID to be parsed. Defaults to 'v1'. * @throws {Error} If parsing the input string fails, throws an error with message "error parsing content hash". * @returns {CID} - The CID object obtained from parsing the input string. */ function parseCID(input, version) { let cid; if (isHEX(input)) { try { cid = multiformats.CID.decode(base16.base16.decode(input)); } catch (error) { } } try { cid = multiformats.CID.parse(input); } catch (error) { } if (typeof cid === 'undefined') throw new Error('error parsing content hash'); return cid; } multiformats.CID.prototype.getCIDs = function () { return getCIDs(this); }; String.prototype.findCIDs = function (parse) { const cids = findCIDs(String(this)); if (parse === true) return cids.map(cid => multiformats.CID.parse(cid)); return cids; }; String.prototype.isCID = function (version) { return isCID(String(this), version); }; String.prototype.getCIDs = function () { if (!isCID(String(this))) return {}; return String(this).parseCID().getCIDs(); }; String.prototype.parseCID = function () { return parseCID(String(this)); }; /****************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ /* global Reflect, Promise, SuppressedError, Symbol */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { var e = new Error(message); return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; }; if (typeof Date.prototype.unix === 'undefined') { Date.prototype.unix = function () { return Math.ceil(this.valueOf() / 1e3); }; } if (typeof Date.prototype.formatMMDDYYYY === 'undefined') { Date.prototype.formatMMDDYYYY = function () { return formatMMDDYYYY(this); }; } if (typeof Date.prototype.formatHHMMSS === 'undefined') { Date.prototype.formatHHMMSS = function (addMSeconds) { return formatHHMMSS(this, addMSeconds); }; } if (typeof Date.prototype.formatMMDDYYYY_HHMMSS === 'undefined') { Date.prototype.formatMMDDYYYY_HHMMSS = function (addMSeconds) { return `${this.formatMMDDYYYY()}_${this.formatHHMMSS()}`; }; } if (typeof Date.prototype.getDaysArray === 'undefined') { Date.prototype.getDaysArray = function (year, month) { if (!year) year = this.getFullYear(); if (!month) month = this.getMonth(); return getDaysArray(year, month); }; } if (typeof String.prototype.sleep === 'undefined') { String.prototype.sleep = function () { return sleep(Number(this)); }; } if (typeof Number.prototype.sleep === 'undefined') { Number.prototype.sleep = function () { return __awaiter(this, void 0, void 0, function* () { return sleep(this); }); }; } if (typeof String.prototype.ts2date === 'undefined') { String.prototype.ts2date = function () { return ts2date(Number(this)); }; } if (typeof Number.prototype.ts2date === 'undefined') { Number.prototype.ts2date = function () { return ts2date(this); }; } if (typeof String.prototype.sec2read === 'undefined') { String.prototype.sec2read = function () { return sec2read(Number(this)); }; } if (typeof Number.prototype.sec2read === 'undefined') { Number.prototype.sec2read = function () { return sec2read(this); }; } const VERSION = '0.0.1-rc.7'; exports.CID_V0 = CID_V0; exports.CID_V1 = CID_V1; exports.Utils = utils; exports.VERSION = VERSION; exports.extractIpfsHash = extractIpfsHash; exports.extractIpfsHashes = extractIpfsHashes; exports.fromHEX = fromHEX; exports.getCIDVersion = getCIDVersion; exports.getCIDs = getCIDs; exports.isCID = isCID; exports.isHEX = isHEX; exports.isHexCID = isHexCID; exports.isV0 = isV0; exports.isV1 = isV1; exports.matcher = matcher; exports.parseCID = parseCID; exports.toHEX = toHEX; //# sourceMappingURL=index.js.map