UNPKG

1.27 kBJavaScriptView Raw
1var sha1 = require('./lib/sha1-browser');
2var bytesToUuid = require('./lib/bytesToUuid');
3
4function uuidToBytes(uuid) {
5 // Note: We assume we're being passed a valid uuid string
6 var bytes = [];
7 uuid.replace(/[a-fA-F0-9]{2}/g, function(hex) {
8 bytes.push(parseInt(hex, 16));
9 });
10
11 return bytes;
12}
13
14function stringToBytes(str) {
15 str = unescape(encodeURIComponent(str)); // UTF8 escape
16 var bytes = new Array(str.length);
17 for (var i = 0; i < str.length; i++) {
18 bytes[i] = str.charCodeAt(i);
19 }
20 return bytes;
21}
22
23function v5(name, namespace, buf, offset) {
24 if (typeof(name) == 'string') name = stringToBytes(name);
25 if (typeof(namespace) == 'string') namespace = uuidToBytes(namespace);
26
27 if (!Array.isArray(name)) throw TypeError('name must be an array of bytes');
28 if (!Array.isArray(namespace) || namespace.length != 16) throw TypeError('namespace must be uuid string or an Array of 16 byte values');
29
30 // Per 4.3
31 var bytes = sha1(namespace.concat(name));
32 bytes[6] = (bytes[6] & 0x0f) | 0x50;
33 bytes[8] = (bytes[8] & 0x3f) | 0x80;
34
35 return buf || bytesToUuid(bytes);
36}
37
38// Pre-defined namespaces, per Appendix C
39v5.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
40v5.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
41
42module.exports = v5;