UNPKG

8.01 kBJavaScriptView Raw
1// uuid.js
2//
3// Copyright (c) 2010-2012 Robert Kieffer
4// MIT License - http://opensource.org/licenses/mit-license.php
5
6/*global window, require, define */
7(function(_window) {
8 'use strict';
9
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;
14
15 function setupBrowser() {
16 // Allow for MSIE11 msCrypto
17 var _crypto = _window.crypto || _window.msCrypto;
18
19 if (!_rng && _crypto && _crypto.getRandomValues) {
20 // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto
21 //
22 // Moderately fast, high quality
23 try {
24 var _rnds8 = new Uint8Array(16);
25 _whatwgRNG = _rng = function whatwgRNG() {
26 _crypto.getRandomValues(_rnds8);
27 return _rnds8;
28 };
29 _rng();
30 } catch(e) {}
31 }
32
33 if (!_rng) {
34 // Math.random()-based (RNG)
35 //
36 // If all else fails, use Math.random(). It's fast, but is of unspecified
37 // quality.
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;
43 }
44
45 return _rnds;
46 };
47 if ('undefined' !== typeof console && console.warn) {
48 console.warn("[SECURITY] node-uuid: crypto not usable, falling back to insecure Math.random()");
49 }
50 }
51 }
52
53 function setupNode() {
54 // Node.js crypto-based RNG - http://nodejs.org/docs/v0.6.2/api/crypto.html
55 //
56 // Moderately fast, high quality
57 if ('function' === typeof require) {
58 try {
59 var _rb = require('crypto').randomBytes;
60 _nodeRNG = _rng = _rb && function() {return _rb(16);};
61 _rng();
62 } catch(e) {}
63 }
64 }
65
66 if (_window) {
67 setupBrowser();
68 } else {
69 setupNode();
70 }
71
72 // Buffer class to use
73 var BufferClass = ('function' === typeof Buffer) ? Buffer : Array;
74
75 // Maps for number <-> hex string conversion
76 var _byteToHex = [];
77 var _hexToByte = {};
78 for (var i = 0; i < 256; i++) {
79 _byteToHex[i] = (i + 0x100).toString(16).substr(1);
80 _hexToByte[_byteToHex[i]] = i;
81 }
82
83 // **`parse()` - Parse a UUID into it's component bytes**
84 function parse(s, buf, offset) {
85 var i = (buf && offset) || 0, ii = 0;
86
87 buf = buf || [];
88 s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) {
89 if (ii < 16) { // Don't overflow!
90 buf[i + ii++] = _hexToByte[oct];
91 }
92 });
93
94 // Zero out remaining bytes if string was short
95 while (ii < 16) {
96 buf[i + ii++] = 0;
97 }
98
99 return buf;
100 }
101
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++]];
113 }
114
115 // **`v1()` - Generate time-based UUID**
116 //
117 // Inspired by https://github.com/LiosK/UUID.js
118 // and http://docs.python.org/library/uuid.html
119
120 // random #'s we need to init node and clockseq
121 var _seedBytes = _rng();
122
123 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
124 var _nodeId = [
125 _seedBytes[0] | 0x01,
126 _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
127 ];
128
129 // Per 4.2.2, randomize (14 bit) clockseq
130 var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
131
132 // Previous uuid creation time
133 var _lastMSecs = 0, _lastNSecs = 0;
134
135 // See https://github.com/broofa/node-uuid for API details
136 function v1(options, buf, offset) {
137 var i = buf && offset || 0;
138 var b = buf || [];
139
140 options = options || {};
141
142 var clockseq = (options.clockseq != null) ? options.clockseq : _clockseq;
143
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();
149
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;
153
154 // Time since last uuid creation (in msecs)
155 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
156
157 // Per 4.2.1.2, Bump clockseq on clock regression
158 if (dt < 0 && options.clockseq == null) {
159 clockseq = clockseq + 1 & 0x3fff;
160 }
161
162 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
163 // time interval
164 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs == null) {
165 nsecs = 0;
166 }
167
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');
171 }
172
173 _lastMSecs = msecs;
174 _lastNSecs = nsecs;
175 _clockseq = clockseq;
176
177 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
178 msecs += 12219292800000;
179
180 // `time_low`
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;
185 b[i++] = tl & 0xff;
186
187 // `time_mid`
188 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
189 b[i++] = tmh >>> 8 & 0xff;
190 b[i++] = tmh & 0xff;
191
192 // `time_high_and_version`
193 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
194 b[i++] = tmh >>> 16 & 0xff;
195
196 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
197 b[i++] = clockseq >>> 8 | 0x80;
198
199 // `clock_seq_low`
200 b[i++] = clockseq & 0xff;
201
202 // `node`
203 var node = options.node || _nodeId;
204 for (var n = 0; n < 6; n++) {
205 b[i + n] = node[n];
206 }
207
208 return buf ? buf : unparse(b);
209 }
210
211 // **`v4()` - Generate random UUID**
212
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;
217
218 if (typeof(options) === 'string') {
219 buf = (options === 'binary') ? new BufferClass(16) : null;
220 options = null;
221 }
222 options = options || {};
223
224 var rnds = options.random || (options.rng || _rng)();
225
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;
229
230 // Copy bytes to buffer, if provided
231 if (buf) {
232 for (var ii = 0; ii < 16; ii++) {
233 buf[i + ii] = rnds[ii];
234 }
235 }
236
237 return buf || unparse(rnds);
238 }
239
240 // Export public API
241 var uuid = v4;
242 uuid.v1 = v1;
243 uuid.v4 = v4;
244 uuid.parse = parse;
245 uuid.unparse = unparse;
246 uuid.BufferClass = BufferClass;
247 uuid._rng = _rng;
248 uuid._mathRNG = _mathRNG;
249 uuid._nodeRNG = _nodeRNG;
250 uuid._whatwgRNG = _whatwgRNG;
251
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;});
258
259
260 } else {
261 // Publish as global (in browsers)
262 _previousRoot = _window.uuid;
263
264 // **`noConflict()` - (browser only) to reset global 'uuid' var**
265 uuid.noConflict = function() {
266 _window.uuid = _previousRoot;
267 return uuid;
268 };
269
270 _window.uuid = uuid;
271 }
272})('undefined' !== typeof window ? window : null);