UNPKG

1.72 kBJavaScriptView Raw
1import bytesToUuid from './bytesToUuid.js';
2
3function uuidToBytes(uuid) {
4 // Note: We assume we're being passed a valid uuid string
5 var bytes = [];
6 uuid.replace(/[a-fA-F0-9]{2}/g, function (hex) {
7 bytes.push(parseInt(hex, 16));
8 });
9 return bytes;
10}
11
12function stringToBytes(str) {
13 str = unescape(encodeURIComponent(str)); // UTF8 escape
14
15 var bytes = [];
16
17 for (var i = 0; i < str.length; ++i) {
18 bytes.push(str.charCodeAt(i));
19 }
20
21 return bytes;
22}
23
24export var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
25export var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
26export default function (name, version, hashfunc) {
27 function generateUUID(value, namespace, buf, offset) {
28 if (typeof value === 'string') {
29 value = stringToBytes(value);
30 }
31
32 if (typeof namespace === 'string') {
33 namespace = uuidToBytes(namespace);
34 }
35
36 if (!Array.isArray(value)) {
37 throw TypeError('value must be an array of bytes');
38 }
39
40 if (!Array.isArray(namespace) || namespace.length !== 16) {
41 throw TypeError('namespace must be uuid string or an Array of 16 byte values');
42 } // Per 4.3
43
44
45 var bytes = hashfunc(namespace.concat(value));
46 bytes[6] = bytes[6] & 0x0f | version;
47 bytes[8] = bytes[8] & 0x3f | 0x80;
48
49 if (buf) {
50 offset = offset || 0;
51
52 for (var i = 0; i < 16; ++i) {
53 buf[offset + i] = bytes[i];
54 }
55
56 return buf;
57 }
58
59 return bytesToUuid(bytes);
60 } // Function#name is not settable on some platforms (#270)
61
62
63 try {
64 generateUUID.name = name; // eslint-disable-next-line no-empty
65 } catch (err) {} // For CommonJS default export support
66
67
68 generateUUID.DNS = DNS;
69 generateUUID.URL = URL;
70 return generateUUID;
71}
\No newline at end of file