3 // Copyright (c) 2010-2012 Robert Kieffer
4 // MIT License - http://opensource.org/licenses/mit-license.php
6 /*global window, require, define */
10 // Unique ID creation requires a high quality random # generator. We feature
11 // detect to determine the best RNG source, normalizing to a function that
12 // returns 128-bits of randomness, since that's what's usually required
13 var _rng, _mathRNG, _nodeRNG, _whatwgRNG, _previousRoot;
15 function setupBrowser() {
16 // Allow for MSIE11 msCrypto
17 var _crypto = _window.crypto || _window.msCrypto;
19 if (!_rng && _crypto && _crypto.getRandomValues) {
20 // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
22 // Moderately fast, high quality
24 var _rnds8 = new Uint8Array(16);
25 _whatwgRNG = _rng = function whatwgRNG() {
26 _crypto.getRandomValues(_rnds8);
34 // Math.random()-based (RNG)
36 // If all else fails, use Math.random(). It's fast, but is of unspecified
38 var _rnds = new Array(16);
39 _mathRNG = _rng = function() {
40 for (var i = 0, r; i < 16; i++) {
41 if ((i & 0x03) === 0) { r = Math.random() * 0x100000000; }
42 _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
47 if ('undefined' !== typeof console && console.warn) {
48 console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()");
53 function setupNode() {
54 // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
56 // Moderately fast, high quality
57 if ('function' === typeof require) {
59 var _rb = require('crypto').randomBytes;
60 _nodeRNG = _rng = _rb && function() {return _rb(16);};
72 // Buffer class to use
73 var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;
75 // Maps for number <-> hex string conversion
78 for (var i = 0; i < 256; i++) {
79 _byteToHex[i] = (i + 0x100).toString(16).substr(1);
80 _hexToByte[_byteToHex[i]] = i;
83 // **`parse()` - Parse a UUID into it's component bytes**
84 function parse(s, buf, offset) {
85 var i = (buf && offset) || 0, ii = 0;
88 s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
89 if (ii < 16) { // Don't overflow!
90 buf[i + ii++] = _hexToByte[oct];
94 // Zero out remaining bytes if string was short
102 // **`unparse()` - Convert UUID byte array (ala parse()) into a string**
103 function unparse(buf, offset) {
104 var i = offset || 0, bth = _byteToHex;
105 return bth[buf[i++]] + bth[buf[i++]] +
106 bth[buf[i++]] + bth[buf[i++]] + '-' +
107 bth[buf[i++]] + bth[buf[i++]] + '-' +
108 bth[buf[i++]] + bth[buf[i++]] + '-' +
109 bth[buf[i++]] + bth[buf[i++]] + '-' +
110 bth[buf[i++]] + bth[buf[i++]] +
111 bth[buf[i++]] + bth[buf[i++]] +
112 bth[buf[i++]] + bth[buf[i++]];
115 // **`v1()` - Generate time-based UUID**
117 // Inspired by https://github.com/LiosK/UUID.js
118 // and http://docs.python.org/library/uuid.html
120 // random #'s we need to init node and clockseq
121 var _seedBytes = _rng();
123 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
125 _seedBytes[0] | 0x01,
126 _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
129 // Per 4.2.2, randomize (14 bit) clockseq
130 var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
132 // Previous uuid creation time
133 var _lastMSecs = 0, _lastNSecs = 0;
135 // See https://github.com/broofa/node-uuid for API details
136 function v1(options, buf, offset) {
137 var i = buf && offset || 0;
140 options = options || {};
142 var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;
144 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
145 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
146 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
147 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
148 var msecs = (options.msecs != null) ? options.msecs : new Date().getTime();
150 // Per 4.2.1.2, use count of uuid's generated during the current clock
151 // cycle to simulate higher resolution clock
152 var nsecs = (options.nsecs != null) ? options.nsecs : _lastNSecs + 1;
154 // Time since last uuid creation (in msecs)
155 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
157 // Per 4.2.1.2, Bump clockseq on clock regression
158 if (dt < 0 && options.clockseq == null) {
159 clockseq = clockseq + 1 & 0x3fff;
162 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
164 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
168 // Per 4.2.1.2 Throw error if too many uuids are requested
169 if (nsecs >= 10000) {
170 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
175 _clockseq = clockseq;
177 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
178 msecs += 12219292800000;
181 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
182 b[i++] = tl >>> 24 & 0xff;
183 b[i++] = tl >>> 16 & 0xff;
184 b[i++] = tl >>> 8 & 0xff;
188 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
189 b[i++] = tmh >>> 8 & 0xff;
192 // `time_high_and_version`
193 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
194 b[i++] = tmh >>> 16 & 0xff;
196 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
197 b[i++] = clockseq >>> 8 | 0x80;
200 b[i++] = clockseq & 0xff;
203 var node = options.node || _nodeId;
204 for (var n = 0; n < 6; n++) {
208 return buf ? buf : unparse(b);
211 // **`v4()` - Generate random UUID**
213 // See https://github.com/broofa/node-uuid for API details
214 function v4(options, buf, offset) {
215 // Deprecated - 'format' argument, as supported in v1.2
216 var i = buf && offset || 0;
218 if (typeof(options) === 'string') {
219 buf = (options === 'binary') ? new BufferClass(16) : null;
222 options = options || {};
224 var rnds = options.random || (options.rng || _rng)();
226 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
227 rnds[6] = (rnds[6] & 0x0f) | 0x40;
228 rnds[8] = (rnds[8] & 0x3f) | 0x80;
230 // Copy bytes to buffer, if provided
232 for (var ii = 0; ii < 16; ii++) {
233 buf[i + ii] = rnds[ii];
237 return buf || unparse(rnds);
245 uuid.unparse = unparse;
246 uuid.BufferClass = BufferClass;
248 uuid._mathRNG = _mathRNG;
249 uuid._nodeRNG = _nodeRNG;
250 uuid._whatwgRNG = _whatwgRNG;
252 if (('undefined' !== typeof module) && module.exports) {
253 // Publish as node.js module
254 module.exports = uuid;
255 } else if (typeof define === 'function' && define.amd) {
256 // Publish as AMD module
257 define(function() {return uuid;});
261 // Publish as global (in browsers)
262 _previousRoot = _window.uuid;
264 // **`noConflict()` - (browser only) to reset global 'uuid' var**
265 uuid.noConflict = function() {
266 _window.uuid = _previousRoot;
272 })('undefined' !== typeof window ? window : null);