UNPKG

@shopify/app-bridge-core

Version:

**[Join our team and work on libraries like this one.](https://www.shopify.ca/careers)**

57 lines (55 loc) 1.6 kB
/** * Convert a number or array of integers to a string of padded hex octets. */ function asHex(value) { return Array.from(value) .map((i) => `00${i.toString(16)}`.slice(-2)) .join(''); } /** * Attempt to securely generate random bytes/ */ function getRandomBytes(size) { // SPRNG if (typeof Uint8Array === 'function' && typeof window === 'object' && window.crypto) { const buffer = new Uint8Array(size); const randomValues = window.crypto.getRandomValues(buffer); if (randomValues) { return randomValues; } } // Insecure random return Array.from(new Array(size), () => (Math.random() * 255) | 0); } /** * Generate a RFC4122-compliant v4 UUID. * * @see http://www.ietf.org/rfc/rfc4122.txt */ function generateUuid() { const version = 0b01000000; const clockSeqHiAndReserved = getRandomBytes(1); const timeHiAndVersion = getRandomBytes(2); clockSeqHiAndReserved[0] &= 0b00111111 | 0b10000000; // tslint:disable-next-line:binary-expression-operand-order timeHiAndVersion[0] &= 0b00001111 | version; return [ // time-low asHex(getRandomBytes(4)), '-', // time-mid asHex(getRandomBytes(2)), '-', // time-high-and-version asHex(timeHiAndVersion), '-', // clock-seq-and-reserved asHex(clockSeqHiAndReserved), // clock-seq-loq asHex(getRandomBytes(1)), '-', // node asHex(getRandomBytes(6)), ].join(''); } export { generateUuid as default, generateUuid };