UNPKG

90.6 kBJavaScriptView Raw
1(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2(function() {
3 'use strict';
4
5 if (self.fetch) {
6 return
7 }
8
9 function normalizeName(name) {
10 if (typeof name !== 'string') {
11 name = String(name)
12 }
13 if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
14 throw new TypeError('Invalid character in header field name')
15 }
16 return name.toLowerCase()
17 }
18
19 function normalizeValue(value) {
20 if (typeof value !== 'string') {
21 value = String(value)
22 }
23 return value
24 }
25
26 function Headers(headers) {
27 this.map = {}
28
29 if (headers instanceof Headers) {
30 headers.forEach(function(value, name) {
31 this.append(name, value)
32 }, this)
33
34 } else if (headers) {
35 Object.getOwnPropertyNames(headers).forEach(function(name) {
36 this.append(name, headers[name])
37 }, this)
38 }
39 }
40
41 Headers.prototype.append = function(name, value) {
42 name = normalizeName(name)
43 value = normalizeValue(value)
44 var list = this.map[name]
45 if (!list) {
46 list = []
47 this.map[name] = list
48 }
49 list.push(value)
50 }
51
52 Headers.prototype['delete'] = function(name) {
53 delete this.map[normalizeName(name)]
54 }
55
56 Headers.prototype.get = function(name) {
57 var values = this.map[normalizeName(name)]
58 return values ? values[0] : null
59 }
60
61 Headers.prototype.getAll = function(name) {
62 return this.map[normalizeName(name)] || []
63 }
64
65 Headers.prototype.has = function(name) {
66 return this.map.hasOwnProperty(normalizeName(name))
67 }
68
69 Headers.prototype.set = function(name, value) {
70 this.map[normalizeName(name)] = [normalizeValue(value)]
71 }
72
73 Headers.prototype.forEach = function(callback, thisArg) {
74 Object.getOwnPropertyNames(this.map).forEach(function(name) {
75 this.map[name].forEach(function(value) {
76 callback.call(thisArg, value, name, this)
77 }, this)
78 }, this)
79 }
80
81 function consumed(body) {
82 if (body.bodyUsed) {
83 return Promise.reject(new TypeError('Already read'))
84 }
85 body.bodyUsed = true
86 }
87
88 function fileReaderReady(reader) {
89 return new Promise(function(resolve, reject) {
90 reader.onload = function() {
91 resolve(reader.result)
92 }
93 reader.onerror = function() {
94 reject(reader.error)
95 }
96 })
97 }
98
99 function readBlobAsArrayBuffer(blob) {
100 var reader = new FileReader()
101 reader.readAsArrayBuffer(blob)
102 return fileReaderReady(reader)
103 }
104
105 function readBlobAsText(blob) {
106 var reader = new FileReader()
107 reader.readAsText(blob)
108 return fileReaderReady(reader)
109 }
110
111 var support = {
112 blob: 'FileReader' in self && 'Blob' in self && (function() {
113 try {
114 new Blob();
115 return true
116 } catch(e) {
117 return false
118 }
119 })(),
120 formData: 'FormData' in self,
121 arrayBuffer: 'ArrayBuffer' in self
122 }
123
124 function Body() {
125 this.bodyUsed = false
126
127
128 this._initBody = function(body) {
129 this._bodyInit = body
130 if (typeof body === 'string') {
131 this._bodyText = body
132 } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
133 this._bodyBlob = body
134 } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
135 this._bodyFormData = body
136 } else if (!body) {
137 this._bodyText = ''
138 } else if (support.arrayBuffer && ArrayBuffer.prototype.isPrototypeOf(body)) {
139 // Only support ArrayBuffers for POST method.
140 // Receiving ArrayBuffers happens via Blobs, instead.
141 } else {
142 throw new Error('unsupported BodyInit type')
143 }
144 }
145
146 if (support.blob) {
147 this.blob = function() {
148 var rejected = consumed(this)
149 if (rejected) {
150 return rejected
151 }
152
153 if (this._bodyBlob) {
154 return Promise.resolve(this._bodyBlob)
155 } else if (this._bodyFormData) {
156 throw new Error('could not read FormData body as blob')
157 } else {
158 return Promise.resolve(new Blob([this._bodyText]))
159 }
160 }
161
162 this.arrayBuffer = function() {
163 return this.blob().then(readBlobAsArrayBuffer)
164 }
165
166 this.text = function() {
167 var rejected = consumed(this)
168 if (rejected) {
169 return rejected
170 }
171
172 if (this._bodyBlob) {
173 return readBlobAsText(this._bodyBlob)
174 } else if (this._bodyFormData) {
175 throw new Error('could not read FormData body as text')
176 } else {
177 return Promise.resolve(this._bodyText)
178 }
179 }
180 } else {
181 this.text = function() {
182 var rejected = consumed(this)
183 return rejected ? rejected : Promise.resolve(this._bodyText)
184 }
185 }
186
187 if (support.formData) {
188 this.formData = function() {
189 return this.text().then(decode)
190 }
191 }
192
193 this.json = function() {
194 return this.text().then(JSON.parse)
195 }
196
197 return this
198 }
199
200 // HTTP methods whose capitalization should be normalized
201 var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']
202
203 function normalizeMethod(method) {
204 var upcased = method.toUpperCase()
205 return (methods.indexOf(upcased) > -1) ? upcased : method
206 }
207
208 function Request(input, options) {
209 options = options || {}
210 var body = options.body
211 if (Request.prototype.isPrototypeOf(input)) {
212 if (input.bodyUsed) {
213 throw new TypeError('Already read')
214 }
215 this.url = input.url
216 this.credentials = input.credentials
217 if (!options.headers) {
218 this.headers = new Headers(input.headers)
219 }
220 this.method = input.method
221 this.mode = input.mode
222 if (!body) {
223 body = input._bodyInit
224 input.bodyUsed = true
225 }
226 } else {
227 this.url = input
228 }
229
230 this.credentials = options.credentials || this.credentials || 'omit'
231 if (options.headers || !this.headers) {
232 this.headers = new Headers(options.headers)
233 }
234 this.method = normalizeMethod(options.method || this.method || 'GET')
235 this.mode = options.mode || this.mode || null
236 this.referrer = null
237
238 if ((this.method === 'GET' || this.method === 'HEAD') && body) {
239 throw new TypeError('Body not allowed for GET or HEAD requests')
240 }
241 this._initBody(body)
242 }
243
244 Request.prototype.clone = function() {
245 return new Request(this)
246 }
247
248 function decode(body) {
249 var form = new FormData()
250 body.trim().split('&').forEach(function(bytes) {
251 if (bytes) {
252 var split = bytes.split('=')
253 var name = split.shift().replace(/\+/g, ' ')
254 var value = split.join('=').replace(/\+/g, ' ')
255 form.append(decodeURIComponent(name), decodeURIComponent(value))
256 }
257 })
258 return form
259 }
260
261 function headers(xhr) {
262 var head = new Headers()
263 var pairs = xhr.getAllResponseHeaders().trim().split('\n')
264 pairs.forEach(function(header) {
265 var split = header.trim().split(':')
266 var key = split.shift().trim()
267 var value = split.join(':').trim()
268 head.append(key, value)
269 })
270 return head
271 }
272
273 Body.call(Request.prototype)
274
275 function Response(bodyInit, options) {
276 if (!options) {
277 options = {}
278 }
279
280 this._initBody(bodyInit)
281 this.type = 'default'
282 this.status = options.status
283 this.ok = this.status >= 200 && this.status < 300
284 this.statusText = options.statusText
285 this.headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers)
286 this.url = options.url || ''
287 }
288
289 Body.call(Response.prototype)
290
291 Response.prototype.clone = function() {
292 return new Response(this._bodyInit, {
293 status: this.status,
294 statusText: this.statusText,
295 headers: new Headers(this.headers),
296 url: this.url
297 })
298 }
299
300 Response.error = function() {
301 var response = new Response(null, {status: 0, statusText: ''})
302 response.type = 'error'
303 return response
304 }
305
306 var redirectStatuses = [301, 302, 303, 307, 308]
307
308 Response.redirect = function(url, status) {
309 if (redirectStatuses.indexOf(status) === -1) {
310 throw new RangeError('Invalid status code')
311 }
312
313 return new Response(null, {status: status, headers: {location: url}})
314 }
315
316 self.Headers = Headers;
317 self.Request = Request;
318 self.Response = Response;
319
320 self.fetch = function(input, init) {
321 return new Promise(function(resolve, reject) {
322 var request
323 if (Request.prototype.isPrototypeOf(input) && !init) {
324 request = input
325 } else {
326 request = new Request(input, init)
327 }
328
329 var xhr = new XMLHttpRequest()
330
331 function responseURL() {
332 if ('responseURL' in xhr) {
333 return xhr.responseURL
334 }
335
336 // Avoid security warnings on getResponseHeader when not allowed by CORS
337 if (/^X-Request-URL:/m.test(xhr.getAllResponseHeaders())) {
338 return xhr.getResponseHeader('X-Request-URL')
339 }
340
341 return;
342 }
343
344 xhr.onload = function() {
345 var status = (xhr.status === 1223) ? 204 : xhr.status
346 if (status < 100 || status > 599) {
347 reject(new TypeError('Network request failed'))
348 return
349 }
350 var options = {
351 status: status,
352 statusText: xhr.statusText,
353 headers: headers(xhr),
354 url: responseURL()
355 }
356 var body = 'response' in xhr ? xhr.response : xhr.responseText;
357 resolve(new Response(body, options))
358 }
359
360 xhr.onerror = function() {
361 reject(new TypeError('Network request failed'))
362 }
363
364 xhr.open(request.method, request.url, true)
365
366 if (request.credentials === 'include') {
367 xhr.withCredentials = true
368 }
369
370 if ('responseType' in xhr && support.blob) {
371 xhr.responseType = 'blob'
372 }
373
374 request.headers.forEach(function(value, name) {
375 xhr.setRequestHeader(name, value)
376 })
377
378 xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit)
379 })
380 }
381 self.fetch.polyfill = true
382})();
383
384},{}],2:[function(require,module,exports){
385(function (global){
386/*
387 * js-sha1 v0.3.0
388 * https://github.com/emn178/js-sha1
389 *
390 * Copyright 2014-2015, emn178@gmail.com
391 *
392 * Licensed under the MIT license:
393 * http://www.opensource.org/licenses/MIT
394 */
395;(function(root, undefined){
396 'use strict';
397
398 var NODE_JS = typeof(module) != 'undefined';
399 if(NODE_JS) {
400 root = global;
401 }
402 var HEX_CHARS = '0123456789abcdef'.split('');
403 var EXTRA = [-2147483648, 8388608, 32768, 128];
404 var SHIFT = [24, 16, 8, 0];
405
406 var blocks = [];
407
408 var sha1 = function(message) {
409 var notString = typeof(message) != 'string';
410 if(notString && message.constructor == ArrayBuffer) {
411 message = new Uint8Array(message);
412 }
413
414 var h0, h1, h2, h3, h4, block = 0, code, end = false, t, f,
415 i, j, index = 0, start = 0, bytes = 0, length = message.length;
416
417 h0 = 0x67452301;
418 h1 = 0xEFCDAB89;
419 h2 = 0x98BADCFE;
420 h3 = 0x10325476;
421 h4 = 0xC3D2E1F0;
422
423 do {
424 blocks[0] = block;
425 blocks[16] = blocks[1] = blocks[2] = blocks[3] =
426 blocks[4] = blocks[5] = blocks[6] = blocks[7] =
427 blocks[8] = blocks[9] = blocks[10] = blocks[11] =
428 blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
429 if(notString) {
430 for (i = start;index < length && i < 64; ++index) {
431 blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
432 }
433 } else {
434 for (i = start;index < length && i < 64; ++index) {
435 code = message.charCodeAt(index);
436 if (code < 0x80) {
437 blocks[i >> 2] |= code << SHIFT[i++ & 3];
438 } else if (code < 0x800) {
439 blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
440 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
441 } else if (code < 0xd800 || code >= 0xe000) {
442 blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
443 blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
444 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
445 } else {
446 code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
447 blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
448 blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
449 blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
450 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
451 }
452 }
453 }
454 bytes += i - start;
455 start = i - 64;
456 if(index == length) {
457 blocks[i >> 2] |= EXTRA[i & 3];
458 ++index;
459 }
460 block = blocks[16];
461 if(index > length && i < 56) {
462 blocks[15] = bytes << 3;
463 end = true;
464 }
465
466 for(j = 16;j < 80;++j) {
467 t = blocks[j - 3] ^ blocks[j - 8] ^ blocks[j - 14] ^ blocks[j - 16];
468 blocks[j] = (t << 1) | (t >>> 31);
469 }
470
471 var a = h0, b = h1, c = h2, d = h3, e = h4;
472 for(j = 0;j < 20;j += 5) {
473 f = (b & c) | ((~b) & d);
474 t = (a << 5) | (a >>> 27);
475 e = t + f + e + 1518500249 + blocks[j] << 0;
476 b = (b << 30) | (b >>> 2);
477
478 f = (a & b) | ((~a) & c);
479 t = (e << 5) | (e >>> 27);
480 d = t + f + d + 1518500249 + blocks[j + 1] << 0;
481 a = (a << 30) | (a >>> 2);
482
483 f = (e & a) | ((~e) & b);
484 t = (d << 5) | (d >>> 27);
485 c = t + f + c + 1518500249 + blocks[j + 2] << 0;
486 e = (e << 30) | (e >>> 2);
487
488 f = (d & e) | ((~d) & a);
489 t = (c << 5) | (c >>> 27);
490 b = t + f + b + 1518500249 + blocks[j + 3] << 0;
491 d = (d << 30) | (d >>> 2);
492
493 f = (c & d) | ((~c) & e);
494 t = (b << 5) | (b >>> 27);
495 a = t + f + a + 1518500249 + blocks[j + 4] << 0;
496 c = (c << 30) | (c >>> 2);
497 }
498
499 for(;j < 40;j += 5) {
500 f = b ^ c ^ d;
501 t = (a << 5) | (a >>> 27);
502 e = t + f + e + 1859775393 + blocks[j] << 0;
503 b = (b << 30) | (b >>> 2);
504
505 f = a ^ b ^ c;
506 t = (e << 5) | (e >>> 27);
507 d = t + f + d + 1859775393 + blocks[j + 1] << 0;
508 a = (a << 30) | (a >>> 2);
509
510 f = e ^ a ^ b;
511 t = (d << 5) | (d >>> 27);
512 c = t + f + c + 1859775393 + blocks[j + 2] << 0;
513 e = (e << 30) | (e >>> 2);
514
515 f = d ^ e ^ a;
516 t = (c << 5) | (c >>> 27);
517 b = t + f + b + 1859775393 + blocks[j + 3] << 0;
518 d = (d << 30) | (d >>> 2);
519
520 f = c ^ d ^ e;
521 t = (b << 5) | (b >>> 27);
522 a = t + f + a + 1859775393 + blocks[j + 4] << 0;
523 c = (c << 30) | (c >>> 2);
524 }
525
526 for(;j < 60;j += 5) {
527 f = (b & c) | (b & d) | (c & d);
528 t = (a << 5) | (a >>> 27);
529 e = t + f + e - 1894007588 + blocks[j] << 0;
530 b = (b << 30) | (b >>> 2);
531
532 f = (a & b) | (a & c) | (b & c);
533 t = (e << 5) | (e >>> 27);
534 d = t + f + d - 1894007588 + blocks[j + 1] << 0;
535 a = (a << 30) | (a >>> 2);
536
537 f = (e & a) | (e & b) | (a & b);
538 t = (d << 5) | (d >>> 27);
539 c = t + f + c - 1894007588 + blocks[j + 2] << 0;
540 e = (e << 30) | (e >>> 2);
541
542 f = (d & e) | (d & a) | (e & a);
543 t = (c << 5) | (c >>> 27);
544 b = t + f + b - 1894007588 + blocks[j + 3] << 0;
545 d = (d << 30) | (d >>> 2);
546
547 f = (c & d) | (c & e) | (d & e);
548 t = (b << 5) | (b >>> 27);
549 a = t + f + a - 1894007588 + blocks[j + 4] << 0;
550 c = (c << 30) | (c >>> 2);
551 }
552
553 for(;j < 80;j += 5) {
554 f = b ^ c ^ d;
555 t = (a << 5) | (a >>> 27);
556 e = t + f + e - 899497514 + blocks[j] << 0;
557 b = (b << 30) | (b >>> 2);
558
559 f = a ^ b ^ c;
560 t = (e << 5) | (e >>> 27);
561 d = t + f + d - 899497514 + blocks[j + 1] << 0;
562 a = (a << 30) | (a >>> 2);
563
564 f = e ^ a ^ b;
565 t = (d << 5) | (d >>> 27);
566 c = t + f + c - 899497514 + blocks[j + 2] << 0;
567 e = (e << 30) | (e >>> 2);
568
569 f = d ^ e ^ a;
570 t = (c << 5) | (c >>> 27);
571 b = t + f + b - 899497514 + blocks[j + 3] << 0;
572 d = (d << 30) | (d >>> 2);
573
574 f = c ^ d ^ e;
575 t = (b << 5) | (b >>> 27);
576 a = t + f + a - 899497514 + blocks[j + 4] << 0;
577 c = (c << 30) | (c >>> 2);
578 }
579
580 h0 = h0 + a << 0;
581 h1 = h1 + b << 0;
582 h2 = h2 + c << 0;
583 h3 = h3 + d << 0;
584 h4 = h4 + e << 0;
585 } while(!end);
586
587 return HEX_CHARS[(h0 >> 28) & 0x0F] + HEX_CHARS[(h0 >> 24) & 0x0F] +
588 HEX_CHARS[(h0 >> 20) & 0x0F] + HEX_CHARS[(h0 >> 16) & 0x0F] +
589 HEX_CHARS[(h0 >> 12) & 0x0F] + HEX_CHARS[(h0 >> 8) & 0x0F] +
590 HEX_CHARS[(h0 >> 4) & 0x0F] + HEX_CHARS[h0 & 0x0F] +
591 HEX_CHARS[(h1 >> 28) & 0x0F] + HEX_CHARS[(h1 >> 24) & 0x0F] +
592 HEX_CHARS[(h1 >> 20) & 0x0F] + HEX_CHARS[(h1 >> 16) & 0x0F] +
593 HEX_CHARS[(h1 >> 12) & 0x0F] + HEX_CHARS[(h1 >> 8) & 0x0F] +
594 HEX_CHARS[(h1 >> 4) & 0x0F] + HEX_CHARS[h1 & 0x0F] +
595 HEX_CHARS[(h2 >> 28) & 0x0F] + HEX_CHARS[(h2 >> 24) & 0x0F] +
596 HEX_CHARS[(h2 >> 20) & 0x0F] + HEX_CHARS[(h2 >> 16) & 0x0F] +
597 HEX_CHARS[(h2 >> 12) & 0x0F] + HEX_CHARS[(h2 >> 8) & 0x0F] +
598 HEX_CHARS[(h2 >> 4) & 0x0F] + HEX_CHARS[h2 & 0x0F] +
599 HEX_CHARS[(h3 >> 28) & 0x0F] + HEX_CHARS[(h3 >> 24) & 0x0F] +
600 HEX_CHARS[(h3 >> 20) & 0x0F] + HEX_CHARS[(h3 >> 16) & 0x0F] +
601 HEX_CHARS[(h3 >> 12) & 0x0F] + HEX_CHARS[(h3 >> 8) & 0x0F] +
602 HEX_CHARS[(h3 >> 4) & 0x0F] + HEX_CHARS[h3 & 0x0F] +
603 HEX_CHARS[(h4 >> 28) & 0x0F] + HEX_CHARS[(h4 >> 24) & 0x0F] +
604 HEX_CHARS[(h4 >> 20) & 0x0F] + HEX_CHARS[(h4 >> 16) & 0x0F] +
605 HEX_CHARS[(h4 >> 12) & 0x0F] + HEX_CHARS[(h4 >> 8) & 0x0F] +
606 HEX_CHARS[(h4 >> 4) & 0x0F] + HEX_CHARS[h4 & 0x0F];
607 };
608
609 if(!root.JS_SHA1_TEST && typeof(module) != 'undefined') {
610 var crypto = require('crypto');
611 var Buffer = require('buffer').Buffer;
612
613 module.exports = function(message) {
614 if(typeof(message) == 'string') {
615 return crypto.createHash('sha1').update(message, 'utf8').digest('hex');
616 }
617 if(message.constructor == ArrayBuffer) {
618 message = new Uint8Array(message);
619 }
620 return crypto.createHash('sha1').update(new Buffer(message)).digest('hex');
621 };
622 } else if(root) {
623 root.sha1 = sha1;
624 }
625}(this));
626
627}).call(this,typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
628},{"buffer":12,"crypto":14}],3:[function(require,module,exports){
629/**
630 *
631 * @param strUrl {string} [strUrl] - A valid Url to parse. If not specified then current URL is taken. Make sure that query string tokens are encoded (use encodeURIComponent)
632 * @returns {{url: String, tokens: {}, has: Function, get: Function, getAll: Function, log: Function}}
633 * @constructor
634 */
635function QS(strUrl) {
636 var _qs = {
637 /** @property {string} version - Current library version */
638 version: QS.version,
639
640 /** @property {string} url - Url to parse */
641 url: (strUrl || (window && window.location.href)),
642
643 /** @property {string} url - Query string tokens object */
644 tokens: {},
645
646 /**
647 * Checks if url contains specific query string token's key
648 * @name has
649 * @example
650 * // returns true
651 * QS('http://www.somedomain.com/somepage?foo=bar').has('foo');
652 * @param {string} strKey - Query string token's key to search
653 * @returns {boolean} True if key exists, false otherwise
654 */
655 has: function (strKey) {
656 return _qs.tokens.hasOwnProperty(strKey);
657 },
658
659 /**
660 * Gets query string token's decoded value
661 * @name get
662 * @example
663 * // returns 'bar'
664 * QS('http://www.somedomain.com/somepage?foo=bar').get('foo');
665 * @param {string} strKey - Query string token's key to search
666 * @returns {object} Query string token's value if key exists, otherwise null
667 */
668 get: function (strKey) {
669 return _qs.tokens[strKey];
670 },
671
672 /**
673 * Gets all query string tokens object
674 * @name getAll
675 * @example
676 * // returns {foo: "bar"}
677 * QS('http://www.somedomain.com/somepage?foo=bar').getAll();
678 * @returns {*} Query string keys & values collection
679 */
680 getAll: function () {
681 return _qs.tokens;
682 },
683
684 /**
685 * Sets (update or insert) a query string token and then updates URL property
686 * @name set
687 * @param {string} strKey - Query string key name to set (update or insert)
688 * @param {object} objValue - Query string value (plain, decoded)
689 * @example
690 * QS('http://www.somedomain.com/somepage?foo=bar').set('dom', true);
691 * @returns QS (for chaining purposes)
692 */
693 set: function (strKey, objValue) {
694 _qs.tokens[strKey] = objValue;
695 _updateURL();
696 return _qs;
697 },
698
699 /**
700 * Removes a query string token from URL
701 * @name remove
702 * @param {string} strKey - Query string key name to remove
703 * @example
704 * QS('http://www.somedomain.com/somepage?foo=bar').remove('foo');
705 * @returns QS (for chaining purposes)
706 */
707 remove: function (strKey) {
708 delete _qs.tokens[strKey];
709 _updateURL();
710 return _qs;
711 },
712
713 /**
714 * Changes browser location to QS url (usually after manipulating query string tokens)
715 * @name go
716 * @example
717 * QS('http://www.somedomain.com/somepage?foo=bar').set('rob', 5).go();
718 */
719 go: function () {
720 document.location.href = _qs.url;
721 },
722
723 /**
724 * Logs all query string tokens to browser's console
725 * @name log
726 * @example
727 * QS('http://www.somedomain.com/somepage?foo=bar').log();
728 */
729 log: function () {
730 console.log(_qs.tokens);
731 }
732 };
733
734 // Cast values of tokens:
735 function _cast(objValue) {
736 // Null value:
737 if (objValue === null) {
738 return;
739 }
740
741 // Numeric value:
742 if (!isNaN(objValue) && Number(objValue).toString() === objValue) {
743 return Number(objValue);
744 }
745
746 // Boolean value:
747 if (objValue === 'true') {
748 return true;
749 }
750
751 if (objValue === 'false') {
752 return false;
753 }
754
755 // Undefined:
756 if (objValue === 'undefined') {
757 return undefined;
758 }
759
760 // Null value:
761 if (objValue === 'null') {
762 return null;
763 }
764
765 // String value:
766 return objValue;
767 }
768
769 QS.version = '0.3.10';
770
771 /**
772 * Update url property (usually after manipulating query string tokens)
773 * @name _updateURL
774 * @ignore
775 * @private
776 */
777 function _updateURL() {
778 var strUpdatedUrl = '',
779 strBaseURL = _qs.url.substr(0, (_qs.url.indexOf('?') > 0 && _qs.url.indexOf('?')) || _qs.url.length),
780 strHash = _qs.url.indexOf('#') > 0 && _qs.url.substr(_qs.url.indexOf('#'));
781 arrTokens = [];
782
783 // Compose query strings:
784 for (var key in _qs.tokens) {
785 if (_qs.tokens.hasOwnProperty(key)) {
786 arrTokens.push(encodeURIComponent(key) + (_qs.tokens[key] ? '=' + encodeURIComponent(_qs.tokens[key]) : ''));
787 }
788 }
789
790 // Set updated url to base + qs + hash:
791 strUpdatedUrl = strBaseURL;
792 strUpdatedUrl += (arrTokens.length > 0 ? '?' + arrTokens.join('&') : '');
793 strUpdatedUrl += (strHash && strHash.length > 0 ? strHash : '');
794
795 _qs.url = strUpdatedUrl;
796 }
797
798 /**
799 * Extracts all query string tokens from url
800 * @constructs
801 */
802 (function _init() {
803 var re = /[?&]([^=&#]+)(?:=([^&#]+))?/g,
804 match;
805
806 match = re.exec(_qs.url);
807 while (match !== null) {
808 // Register _qs keys as object's properties:
809 _qs.tokens[decodeURIComponent(match[1])] = match[2] ? _cast(decodeURIComponent(match[2])) : null;
810 match = re.exec(_qs.url);
811 }
812
813 // We update URL to apply encoded query string token, if user hasn't done it:
814 _updateURL();
815 })();
816
817 // Reveal methods & properties:
818 return _qs;
819}
820
821},{}],4:[function(require,module,exports){
822'use strict';
823
824var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
825
826Object.defineProperty(exports, "__esModule", {
827 value: true
828});
829
830var _Util = require('./Util');
831
832var _Util2 = _interopRequireDefault(_Util);
833
834function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
835
836function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
837
838var Translator = (function () {
839 function Translator(alias) {
840 var key = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
841 var uri = arguments.length <= 2 || arguments[2] === undefined ? '' : arguments[2];
842
843 _classCallCheck(this, Translator);
844
845 this.langs = [];
846 this.cache = {};
847 this.provider = Translator.createProvider(alias, key, uri);
848 }
849
850 _createClass(Translator, [{
851 key: 'getLangs',
852 value: function getLangs() {
853 if (this.langs.length) {
854 return Promise.resolve(this.langs);
855 }
856
857 return this.provider.getLangs();
858 }
859 }, {
860 key: 'translate',
861 value: function translate(text, to, from) {
862 var hash = _Util2.default.sha1(text);
863 var lang = _Util2.default.composeLangsAlias(from, to);
864
865 if (typeof this.cache[lang] !== 'undefined' && typeof this.cache[lang][hash] !== 'undefined') {
866 return Promise.resolve(this.cache[lang][hash]);
867 }
868
869 return this.provider.translate(text, to, from);
870 }
871 }, {
872 key: 'lookup',
873 value: function lookup() {
874 var text = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
875
876 var _this = this;
877
878 var to = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];
879 var from = arguments.length <= 2 || arguments[2] === undefined ? '' : arguments[2];
880
881 var lang = _Util2.default.composeLangsAlias(from, to);
882
883 return this.getLangs().then(function (langs) {
884 _this.langs = langs;
885
886 if (!_this.provider.supports(langs, to, from)) {
887 return null;
888 }
889
890 return _this.translate(text, to, from);
891 }).then(function (trans) {
892 if (typeof _this.cache[lang] === 'undefined') {
893 _this.cache[lang] = {};
894 }
895 _this.cache[lang][_Util2.default.sha1(text)] = trans;
896
897 return trans;
898 });
899 }
900 }], [{
901 key: 'addProvider',
902 value: function addProvider(alias, Factory) {
903 Translator.providerMap[alias] = Factory;
904 }
905 }, {
906 key: 'createProvider',
907 value: function createProvider(alias, key, uri) {
908 if (typeof Translator.providerMap[alias] === 'undefined') {
909 return null;
910 }
911
912 var Factory = Translator.providerMap[alias];
913
914 return new Factory(key, uri);
915 }
916 }]);
917
918 return Translator;
919})();
920
921Translator.providerMap = {};
922
923exports.default = Translator;
924},{"./Util":5}],5:[function(require,module,exports){
925'use strict';
926
927var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
928
929Object.defineProperty(exports, "__esModule", {
930 value: true
931});
932
933function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
934
935var Util = (function () {
936 function Util() {
937 _classCallCheck(this, Util);
938 }
939
940 _createClass(Util, null, [{
941 key: 'addHelper',
942 value: function addHelper(alias, helper) {
943 Util.helpers[alias] = helper;
944 }
945 }, {
946 key: 'getHelper',
947 value: function getHelper(alias) {
948 return Util.helpers[alias];
949 }
950 }, {
951 key: 'stringify',
952 value: function stringify(data) {
953 return '?' + Util.getHelper('stringify')(data);
954 }
955 }, {
956 key: 'sha1',
957 value: function sha1(text) {
958 return Util.getHelper('sha1')(text);
959 }
960 }, {
961 key: 'composeLangsAlias',
962 value: function composeLangsAlias(from, to) {
963 return from + '-' + to;
964 }
965 }]);
966
967 return Util;
968})();
969
970Util.helpers = {};
971
972exports.default = Util;
973},{}],6:[function(require,module,exports){
974'use strict';
975
976Object.defineProperty(exports, "__esModule", {
977 value: true
978});
979
980var _fetch = require('../bower_components/fetch/fetch.js');
981
982var _fetch2 = _interopRequireDefault(_fetch);
983
984var _sha = require('../bower_components/js-sha1/src/sha1.js');
985
986var _sha2 = _interopRequireDefault(_sha);
987
988var _qs = require('../bower_components/qs/src/qs.js');
989
990var _qs2 = _interopRequireDefault(_qs);
991
992var _fetch3 = require('./fetch');
993
994var _fetch4 = _interopRequireDefault(_fetch3);
995
996var _Util = require('./Util');
997
998var _Util2 = _interopRequireDefault(_Util);
999
1000var _Translator = require('./Translator');
1001
1002var _Translator2 = _interopRequireDefault(_Translator);
1003
1004var _NoopProvider = require('./provider/NoopProvider');
1005
1006var _NoopProvider2 = _interopRequireDefault(_NoopProvider);
1007
1008var _YandexProvider = require('./provider/YandexProvider');
1009
1010var _YandexProvider2 = _interopRequireDefault(_YandexProvider);
1011
1012var _GoogleProvider = require('./provider/GoogleProvider');
1013
1014var _GoogleProvider2 = _interopRequireDefault(_GoogleProvider);
1015
1016function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1017
1018_fetch4.default.setHelper(_fetch2.default);
1019
1020_Util2.default.addHelper('stringify', _qs2.default.stringify);
1021_Util2.default.addHelper('sha1', _sha2.default);
1022
1023_Translator2.default.addProvider('noop', _NoopProvider2.default);
1024_Translator2.default.addProvider('yandex', _YandexProvider2.default);
1025_Translator2.default.addProvider('google', _GoogleProvider2.default);
1026
1027window.doTranslate = {
1028 Translator: _Translator2.default,
1029 Util: _Util2.default,
1030 NoopProvider: _NoopProvider2.default,
1031 YandexProvider: _YandexProvider2.default,
1032 GoogleProvider: _GoogleProvider2.default
1033};
1034
1035exports.default = true;
1036},{"../bower_components/fetch/fetch.js":1,"../bower_components/js-sha1/src/sha1.js":2,"../bower_components/qs/src/qs.js":3,"./Translator":4,"./Util":5,"./fetch":7,"./provider/GoogleProvider":8,"./provider/NoopProvider":9,"./provider/YandexProvider":10}],7:[function(require,module,exports){
1037"use strict";
1038
1039Object.defineProperty(exports, "__esModule", {
1040 value: true
1041});
1042var helper = function helper() {};
1043
1044var fetch = function fetch(uri, data) {
1045 return helper(uri, data).then(function (response) {
1046 return response.json();
1047 });
1048};
1049
1050fetch.setHelper = function (fn) {
1051 helper = fn;
1052};
1053
1054fetch.getHelper = function () {
1055 return helper;
1056};
1057
1058exports.default = fetch;
1059},{}],8:[function(require,module,exports){
1060'use strict';
1061
1062var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
1063
1064Object.defineProperty(exports, "__esModule", {
1065 value: true
1066});
1067
1068var _fetch = require('./../fetch');
1069
1070var _fetch2 = _interopRequireDefault(_fetch);
1071
1072var _Util = require('./../Util');
1073
1074var _Util2 = _interopRequireDefault(_Util);
1075
1076function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1077
1078function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1079
1080var GoogleProvider = (function () {
1081 function GoogleProvider(key, uri) {
1082 _classCallCheck(this, GoogleProvider);
1083
1084 this.key = key;
1085 this.uri = uri;
1086 }
1087
1088 _createClass(GoogleProvider, [{
1089 key: 'supports',
1090 value: function supports(langs, to, from) {
1091 return langs.indexOf(from) > -1 && langs.indexOf(to) > -1;
1092 }
1093 }, {
1094 key: 'getLangs',
1095 value: function getLangs() {
1096 return (0, _fetch2.default)(this.uri + 'languages' + _Util2.default.stringify({ key: this.key })).then(function (response) {
1097 return response.data.languages.map(function (item) {
1098 return item.language;
1099 });
1100 });
1101 }
1102 }, {
1103 key: 'translate',
1104 value: function translate(text, to, from) {
1105 var data = {
1106 key: this.key,
1107 'q': text,
1108 source: from,
1109 target: to
1110 };
1111
1112 return (0, _fetch2.default)(this.uri + _Util2.default.stringify(data)).then(function (response) {
1113 return response.data.translations.shift().translatedText;
1114 });
1115 }
1116 }]);
1117
1118 return GoogleProvider;
1119})();
1120
1121exports.default = GoogleProvider;
1122},{"./../Util":5,"./../fetch":7}],9:[function(require,module,exports){
1123'use strict';
1124
1125var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
1126
1127Object.defineProperty(exports, "__esModule", {
1128 value: true
1129});
1130
1131var _Util = require('./../Util');
1132
1133var _Util2 = _interopRequireDefault(_Util);
1134
1135function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1136
1137function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1138
1139var NoopProvider = (function () {
1140 function NoopProvider(key, uri) {
1141 _classCallCheck(this, NoopProvider);
1142
1143 this.key = key;
1144 this.uri = uri;
1145 }
1146
1147 _createClass(NoopProvider, [{
1148 key: 'supports',
1149 value: function supports(langs, to, from) {
1150 var lang = _Util2.default.composeLangsAlias(from, to);
1151
1152 return [lang].indexOf(lang) > -1;
1153 }
1154 }, {
1155 key: 'getLangs',
1156 value: function getLangs() {
1157 return new Promise(function (resolve) {
1158 setTimeout(function () {
1159 resolve(['en-ru', 'ru-en']);
1160 }, 350);
1161 });
1162 }
1163 }, {
1164 key: 'translate',
1165 value: function translate(text, to, from) {
1166 var lang = _Util2.default.composeLangsAlias(from, to);
1167
1168 return new Promise(function (resolve) {
1169 setTimeout(function () {
1170 resolve(text + '_' + lang);
1171 }, 350);
1172 });
1173 }
1174 }]);
1175
1176 return NoopProvider;
1177})();
1178
1179exports.default = NoopProvider;
1180},{"./../Util":5}],10:[function(require,module,exports){
1181'use strict';
1182
1183var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
1184
1185Object.defineProperty(exports, "__esModule", {
1186 value: true
1187});
1188
1189var _fetch = require('./../fetch');
1190
1191var _fetch2 = _interopRequireDefault(_fetch);
1192
1193var _Util = require('./../Util');
1194
1195var _Util2 = _interopRequireDefault(_Util);
1196
1197function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
1198
1199function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
1200
1201var YandexProvider = (function () {
1202 function YandexProvider(key, uri) {
1203 _classCallCheck(this, YandexProvider);
1204
1205 this.key = key;
1206 this.uri = uri;
1207 }
1208
1209 _createClass(YandexProvider, [{
1210 key: 'supports',
1211 value: function supports(langs, to, from) {
1212 return langs.indexOf(_Util2.default.composeLangsAlias(from, to)) > -1;
1213 }
1214 }, {
1215 key: 'getLangs',
1216 value: function getLangs() {
1217 return (0, _fetch2.default)(this.uri + 'getLangs' + _Util2.default.stringify({ key: this.key })).then(function (response) {
1218 return response.dirs;
1219 });
1220 }
1221 }, {
1222 key: 'translate',
1223 value: function translate(text, to, from) {
1224 var data = {
1225 key: this.key,
1226 text: text,
1227 lang: _Util2.default.composeLangsAlias(from, to)
1228 };
1229
1230 return (0, _fetch2.default)(this.uri + 'translate' + _Util2.default.stringify(data)).then(function (response) {
1231 return response.text.shift();
1232 });
1233 }
1234 }]);
1235
1236 return YandexProvider;
1237})();
1238
1239exports.default = YandexProvider;
1240},{"./../Util":5,"./../fetch":7}],11:[function(require,module,exports){
1241var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1242
1243;(function (exports) {
1244 'use strict';
1245
1246 var Arr = (typeof Uint8Array !== 'undefined')
1247 ? Uint8Array
1248 : Array
1249
1250 var PLUS = '+'.charCodeAt(0)
1251 var SLASH = '/'.charCodeAt(0)
1252 var NUMBER = '0'.charCodeAt(0)
1253 var LOWER = 'a'.charCodeAt(0)
1254 var UPPER = 'A'.charCodeAt(0)
1255 var PLUS_URL_SAFE = '-'.charCodeAt(0)
1256 var SLASH_URL_SAFE = '_'.charCodeAt(0)
1257
1258 function decode (elt) {
1259 var code = elt.charCodeAt(0)
1260 if (code === PLUS ||
1261 code === PLUS_URL_SAFE)
1262 return 62 // '+'
1263 if (code === SLASH ||
1264 code === SLASH_URL_SAFE)
1265 return 63 // '/'
1266 if (code < NUMBER)
1267 return -1 //no match
1268 if (code < NUMBER + 10)
1269 return code - NUMBER + 26 + 26
1270 if (code < UPPER + 26)
1271 return code - UPPER
1272 if (code < LOWER + 26)
1273 return code - LOWER + 26
1274 }
1275
1276 function b64ToByteArray (b64) {
1277 var i, j, l, tmp, placeHolders, arr
1278
1279 if (b64.length % 4 > 0) {
1280 throw new Error('Invalid string. Length must be a multiple of 4')
1281 }
1282
1283 // the number of equal signs (place holders)
1284 // if there are two placeholders, than the two characters before it
1285 // represent one byte
1286 // if there is only one, then the three characters before it represent 2 bytes
1287 // this is just a cheap hack to not do indexOf twice
1288 var len = b64.length
1289 placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
1290
1291 // base64 is 4/3 + up to two characters of the original data
1292 arr = new Arr(b64.length * 3 / 4 - placeHolders)
1293
1294 // if there are placeholders, only get up to the last complete 4 chars
1295 l = placeHolders > 0 ? b64.length - 4 : b64.length
1296
1297 var L = 0
1298
1299 function push (v) {
1300 arr[L++] = v
1301 }
1302
1303 for (i = 0, j = 0; i < l; i += 4, j += 3) {
1304 tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
1305 push((tmp & 0xFF0000) >> 16)
1306 push((tmp & 0xFF00) >> 8)
1307 push(tmp & 0xFF)
1308 }
1309
1310 if (placeHolders === 2) {
1311 tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
1312 push(tmp & 0xFF)
1313 } else if (placeHolders === 1) {
1314 tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
1315 push((tmp >> 8) & 0xFF)
1316 push(tmp & 0xFF)
1317 }
1318
1319 return arr
1320 }
1321
1322 function uint8ToBase64 (uint8) {
1323 var i,
1324 extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
1325 output = "",
1326 temp, length
1327
1328 function encode (num) {
1329 return lookup.charAt(num)
1330 }
1331
1332 function tripletToBase64 (num) {
1333 return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
1334 }
1335
1336 // go through the array every three bytes, we'll deal with trailing stuff later
1337 for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
1338 temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
1339 output += tripletToBase64(temp)
1340 }
1341
1342 // pad the end with zeros, but make sure to not forget the extra bytes
1343 switch (extraBytes) {
1344 case 1:
1345 temp = uint8[uint8.length - 1]
1346 output += encode(temp >> 2)
1347 output += encode((temp << 4) & 0x3F)
1348 output += '=='
1349 break
1350 case 2:
1351 temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
1352 output += encode(temp >> 10)
1353 output += encode((temp >> 4) & 0x3F)
1354 output += encode((temp << 2) & 0x3F)
1355 output += '='
1356 break
1357 }
1358
1359 return output
1360 }
1361
1362 exports.toByteArray = b64ToByteArray
1363 exports.fromByteArray = uint8ToBase64
1364}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
1365
1366},{}],12:[function(require,module,exports){
1367/*!
1368 * The buffer module from node.js, for the browser.
1369 *
1370 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
1371 * @license MIT
1372 */
1373
1374var base64 = require('base64-js')
1375var ieee754 = require('ieee754')
1376
1377exports.Buffer = Buffer
1378exports.SlowBuffer = Buffer
1379exports.INSPECT_MAX_BYTES = 50
1380Buffer.poolSize = 8192
1381
1382/**
1383 * If `Buffer._useTypedArrays`:
1384 * === true Use Uint8Array implementation (fastest)
1385 * === false Use Object implementation (compatible down to IE6)
1386 */
1387Buffer._useTypedArrays = (function () {
1388 // Detect if browser supports Typed Arrays. Supported browsers are IE 10+, Firefox 4+,
1389 // Chrome 7+, Safari 5.1+, Opera 11.6+, iOS 4.2+. If the browser does not support adding
1390 // properties to `Uint8Array` instances, then that's the same as no `Uint8Array` support
1391 // because we need to be able to add all the node Buffer API methods. This is an issue
1392 // in Firefox 4-29. Now fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=695438
1393 try {
1394 var buf = new ArrayBuffer(0)
1395 var arr = new Uint8Array(buf)
1396 arr.foo = function () { return 42 }
1397 return 42 === arr.foo() &&
1398 typeof arr.subarray === 'function' // Chrome 9-10 lack `subarray`
1399 } catch (e) {
1400 return false
1401 }
1402})()
1403
1404/**
1405 * Class: Buffer
1406 * =============
1407 *
1408 * The Buffer constructor returns instances of `Uint8Array` that are augmented
1409 * with function properties for all the node `Buffer` API functions. We use
1410 * `Uint8Array` so that square bracket notation works as expected -- it returns
1411 * a single octet.
1412 *
1413 * By augmenting the instances, we can avoid modifying the `Uint8Array`
1414 * prototype.
1415 */
1416function Buffer (subject, encoding, noZero) {
1417 if (!(this instanceof Buffer))
1418 return new Buffer(subject, encoding, noZero)
1419
1420 var type = typeof subject
1421
1422 // Workaround: node's base64 implementation allows for non-padded strings
1423 // while base64-js does not.
1424 if (encoding === 'base64' && type === 'string') {
1425 subject = stringtrim(subject)
1426 while (subject.length % 4 !== 0) {
1427 subject = subject + '='
1428 }
1429 }
1430
1431 // Find the length
1432 var length
1433 if (type === 'number')
1434 length = coerce(subject)
1435 else if (type === 'string')
1436 length = Buffer.byteLength(subject, encoding)
1437 else if (type === 'object')
1438 length = coerce(subject.length) // assume that object is array-like
1439 else
1440 throw new Error('First argument needs to be a number, array or string.')
1441
1442 var buf
1443 if (Buffer._useTypedArrays) {
1444 // Preferred: Return an augmented `Uint8Array` instance for best performance
1445 buf = Buffer._augment(new Uint8Array(length))
1446 } else {
1447 // Fallback: Return THIS instance of Buffer (created by `new`)
1448 buf = this
1449 buf.length = length
1450 buf._isBuffer = true
1451 }
1452
1453 var i
1454 if (Buffer._useTypedArrays && typeof subject.byteLength === 'number') {
1455 // Speed optimization -- use set if we're copying from a typed array
1456 buf._set(subject)
1457 } else if (isArrayish(subject)) {
1458 // Treat array-ish objects as a byte array
1459 for (i = 0; i < length; i++) {
1460 if (Buffer.isBuffer(subject))
1461 buf[i] = subject.readUInt8(i)
1462 else
1463 buf[i] = subject[i]
1464 }
1465 } else if (type === 'string') {
1466 buf.write(subject, 0, encoding)
1467 } else if (type === 'number' && !Buffer._useTypedArrays && !noZero) {
1468 for (i = 0; i < length; i++) {
1469 buf[i] = 0
1470 }
1471 }
1472
1473 return buf
1474}
1475
1476// STATIC METHODS
1477// ==============
1478
1479Buffer.isEncoding = function (encoding) {
1480 switch (String(encoding).toLowerCase()) {
1481 case 'hex':
1482 case 'utf8':
1483 case 'utf-8':
1484 case 'ascii':
1485 case 'binary':
1486 case 'base64':
1487 case 'raw':
1488 case 'ucs2':
1489 case 'ucs-2':
1490 case 'utf16le':
1491 case 'utf-16le':
1492 return true
1493 default:
1494 return false
1495 }
1496}
1497
1498Buffer.isBuffer = function (b) {
1499 return !!(b !== null && b !== undefined && b._isBuffer)
1500}
1501
1502Buffer.byteLength = function (str, encoding) {
1503 var ret
1504 str = str + ''
1505 switch (encoding || 'utf8') {
1506 case 'hex':
1507 ret = str.length / 2
1508 break
1509 case 'utf8':
1510 case 'utf-8':
1511 ret = utf8ToBytes(str).length
1512 break
1513 case 'ascii':
1514 case 'binary':
1515 case 'raw':
1516 ret = str.length
1517 break
1518 case 'base64':
1519 ret = base64ToBytes(str).length
1520 break
1521 case 'ucs2':
1522 case 'ucs-2':
1523 case 'utf16le':
1524 case 'utf-16le':
1525 ret = str.length * 2
1526 break
1527 default:
1528 throw new Error('Unknown encoding')
1529 }
1530 return ret
1531}
1532
1533Buffer.concat = function (list, totalLength) {
1534 assert(isArray(list), 'Usage: Buffer.concat(list, [totalLength])\n' +
1535 'list should be an Array.')
1536
1537 if (list.length === 0) {
1538 return new Buffer(0)
1539 } else if (list.length === 1) {
1540 return list[0]
1541 }
1542
1543 var i
1544 if (typeof totalLength !== 'number') {
1545 totalLength = 0
1546 for (i = 0; i < list.length; i++) {
1547 totalLength += list[i].length
1548 }
1549 }
1550
1551 var buf = new Buffer(totalLength)
1552 var pos = 0
1553 for (i = 0; i < list.length; i++) {
1554 var item = list[i]
1555 item.copy(buf, pos)
1556 pos += item.length
1557 }
1558 return buf
1559}
1560
1561// BUFFER INSTANCE METHODS
1562// =======================
1563
1564function _hexWrite (buf, string, offset, length) {
1565 offset = Number(offset) || 0
1566 var remaining = buf.length - offset
1567 if (!length) {
1568 length = remaining
1569 } else {
1570 length = Number(length)
1571 if (length > remaining) {
1572 length = remaining
1573 }
1574 }
1575
1576 // must be an even number of digits
1577 var strLen = string.length
1578 assert(strLen % 2 === 0, 'Invalid hex string')
1579
1580 if (length > strLen / 2) {
1581 length = strLen / 2
1582 }
1583 for (var i = 0; i < length; i++) {
1584 var byte = parseInt(string.substr(i * 2, 2), 16)
1585 assert(!isNaN(byte), 'Invalid hex string')
1586 buf[offset + i] = byte
1587 }
1588 Buffer._charsWritten = i * 2
1589 return i
1590}
1591
1592function _utf8Write (buf, string, offset, length) {
1593 var charsWritten = Buffer._charsWritten =
1594 blitBuffer(utf8ToBytes(string), buf, offset, length)
1595 return charsWritten
1596}
1597
1598function _asciiWrite (buf, string, offset, length) {
1599 var charsWritten = Buffer._charsWritten =
1600 blitBuffer(asciiToBytes(string), buf, offset, length)
1601 return charsWritten
1602}
1603
1604function _binaryWrite (buf, string, offset, length) {
1605 return _asciiWrite(buf, string, offset, length)
1606}
1607
1608function _base64Write (buf, string, offset, length) {
1609 var charsWritten = Buffer._charsWritten =
1610 blitBuffer(base64ToBytes(string), buf, offset, length)
1611 return charsWritten
1612}
1613
1614function _utf16leWrite (buf, string, offset, length) {
1615 var charsWritten = Buffer._charsWritten =
1616 blitBuffer(utf16leToBytes(string), buf, offset, length)
1617 return charsWritten
1618}
1619
1620Buffer.prototype.write = function (string, offset, length, encoding) {
1621 // Support both (string, offset, length, encoding)
1622 // and the legacy (string, encoding, offset, length)
1623 if (isFinite(offset)) {
1624 if (!isFinite(length)) {
1625 encoding = length
1626 length = undefined
1627 }
1628 } else { // legacy
1629 var swap = encoding
1630 encoding = offset
1631 offset = length
1632 length = swap
1633 }
1634
1635 offset = Number(offset) || 0
1636 var remaining = this.length - offset
1637 if (!length) {
1638 length = remaining
1639 } else {
1640 length = Number(length)
1641 if (length > remaining) {
1642 length = remaining
1643 }
1644 }
1645 encoding = String(encoding || 'utf8').toLowerCase()
1646
1647 var ret
1648 switch (encoding) {
1649 case 'hex':
1650 ret = _hexWrite(this, string, offset, length)
1651 break
1652 case 'utf8':
1653 case 'utf-8':
1654 ret = _utf8Write(this, string, offset, length)
1655 break
1656 case 'ascii':
1657 ret = _asciiWrite(this, string, offset, length)
1658 break
1659 case 'binary':
1660 ret = _binaryWrite(this, string, offset, length)
1661 break
1662 case 'base64':
1663 ret = _base64Write(this, string, offset, length)
1664 break
1665 case 'ucs2':
1666 case 'ucs-2':
1667 case 'utf16le':
1668 case 'utf-16le':
1669 ret = _utf16leWrite(this, string, offset, length)
1670 break
1671 default:
1672 throw new Error('Unknown encoding')
1673 }
1674 return ret
1675}
1676
1677Buffer.prototype.toString = function (encoding, start, end) {
1678 var self = this
1679
1680 encoding = String(encoding || 'utf8').toLowerCase()
1681 start = Number(start) || 0
1682 end = (end !== undefined)
1683 ? Number(end)
1684 : end = self.length
1685
1686 // Fastpath empty strings
1687 if (end === start)
1688 return ''
1689
1690 var ret
1691 switch (encoding) {
1692 case 'hex':
1693 ret = _hexSlice(self, start, end)
1694 break
1695 case 'utf8':
1696 case 'utf-8':
1697 ret = _utf8Slice(self, start, end)
1698 break
1699 case 'ascii':
1700 ret = _asciiSlice(self, start, end)
1701 break
1702 case 'binary':
1703 ret = _binarySlice(self, start, end)
1704 break
1705 case 'base64':
1706 ret = _base64Slice(self, start, end)
1707 break
1708 case 'ucs2':
1709 case 'ucs-2':
1710 case 'utf16le':
1711 case 'utf-16le':
1712 ret = _utf16leSlice(self, start, end)
1713 break
1714 default:
1715 throw new Error('Unknown encoding')
1716 }
1717 return ret
1718}
1719
1720Buffer.prototype.toJSON = function () {
1721 return {
1722 type: 'Buffer',
1723 data: Array.prototype.slice.call(this._arr || this, 0)
1724 }
1725}
1726
1727// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1728Buffer.prototype.copy = function (target, target_start, start, end) {
1729 var source = this
1730
1731 if (!start) start = 0
1732 if (!end && end !== 0) end = this.length
1733 if (!target_start) target_start = 0
1734
1735 // Copy 0 bytes; we're done
1736 if (end === start) return
1737 if (target.length === 0 || source.length === 0) return
1738
1739 // Fatal error conditions
1740 assert(end >= start, 'sourceEnd < sourceStart')
1741 assert(target_start >= 0 && target_start < target.length,
1742 'targetStart out of bounds')
1743 assert(start >= 0 && start < source.length, 'sourceStart out of bounds')
1744 assert(end >= 0 && end <= source.length, 'sourceEnd out of bounds')
1745
1746 // Are we oob?
1747 if (end > this.length)
1748 end = this.length
1749 if (target.length - target_start < end - start)
1750 end = target.length - target_start + start
1751
1752 var len = end - start
1753
1754 if (len < 100 || !Buffer._useTypedArrays) {
1755 for (var i = 0; i < len; i++)
1756 target[i + target_start] = this[i + start]
1757 } else {
1758 target._set(this.subarray(start, start + len), target_start)
1759 }
1760}
1761
1762function _base64Slice (buf, start, end) {
1763 if (start === 0 && end === buf.length) {
1764 return base64.fromByteArray(buf)
1765 } else {
1766 return base64.fromByteArray(buf.slice(start, end))
1767 }
1768}
1769
1770function _utf8Slice (buf, start, end) {
1771 var res = ''
1772 var tmp = ''
1773 end = Math.min(buf.length, end)
1774
1775 for (var i = start; i < end; i++) {
1776 if (buf[i] <= 0x7F) {
1777 res += decodeUtf8Char(tmp) + String.fromCharCode(buf[i])
1778 tmp = ''
1779 } else {
1780 tmp += '%' + buf[i].toString(16)
1781 }
1782 }
1783
1784 return res + decodeUtf8Char(tmp)
1785}
1786
1787function _asciiSlice (buf, start, end) {
1788 var ret = ''
1789 end = Math.min(buf.length, end)
1790
1791 for (var i = start; i < end; i++)
1792 ret += String.fromCharCode(buf[i])
1793 return ret
1794}
1795
1796function _binarySlice (buf, start, end) {
1797 return _asciiSlice(buf, start, end)
1798}
1799
1800function _hexSlice (buf, start, end) {
1801 var len = buf.length
1802
1803 if (!start || start < 0) start = 0
1804 if (!end || end < 0 || end > len) end = len
1805
1806 var out = ''
1807 for (var i = start; i < end; i++) {
1808 out += toHex(buf[i])
1809 }
1810 return out
1811}
1812
1813function _utf16leSlice (buf, start, end) {
1814 var bytes = buf.slice(start, end)
1815 var res = ''
1816 for (var i = 0; i < bytes.length; i += 2) {
1817 res += String.fromCharCode(bytes[i] + bytes[i+1] * 256)
1818 }
1819 return res
1820}
1821
1822Buffer.prototype.slice = function (start, end) {
1823 var len = this.length
1824 start = clamp(start, len, 0)
1825 end = clamp(end, len, len)
1826
1827 if (Buffer._useTypedArrays) {
1828 return Buffer._augment(this.subarray(start, end))
1829 } else {
1830 var sliceLen = end - start
1831 var newBuf = new Buffer(sliceLen, undefined, true)
1832 for (var i = 0; i < sliceLen; i++) {
1833 newBuf[i] = this[i + start]
1834 }
1835 return newBuf
1836 }
1837}
1838
1839// `get` will be removed in Node 0.13+
1840Buffer.prototype.get = function (offset) {
1841 console.log('.get() is deprecated. Access using array indexes instead.')
1842 return this.readUInt8(offset)
1843}
1844
1845// `set` will be removed in Node 0.13+
1846Buffer.prototype.set = function (v, offset) {
1847 console.log('.set() is deprecated. Access using array indexes instead.')
1848 return this.writeUInt8(v, offset)
1849}
1850
1851Buffer.prototype.readUInt8 = function (offset, noAssert) {
1852 if (!noAssert) {
1853 assert(offset !== undefined && offset !== null, 'missing offset')
1854 assert(offset < this.length, 'Trying to read beyond buffer length')
1855 }
1856
1857 if (offset >= this.length)
1858 return
1859
1860 return this[offset]
1861}
1862
1863function _readUInt16 (buf, offset, littleEndian, noAssert) {
1864 if (!noAssert) {
1865 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1866 assert(offset !== undefined && offset !== null, 'missing offset')
1867 assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
1868 }
1869
1870 var len = buf.length
1871 if (offset >= len)
1872 return
1873
1874 var val
1875 if (littleEndian) {
1876 val = buf[offset]
1877 if (offset + 1 < len)
1878 val |= buf[offset + 1] << 8
1879 } else {
1880 val = buf[offset] << 8
1881 if (offset + 1 < len)
1882 val |= buf[offset + 1]
1883 }
1884 return val
1885}
1886
1887Buffer.prototype.readUInt16LE = function (offset, noAssert) {
1888 return _readUInt16(this, offset, true, noAssert)
1889}
1890
1891Buffer.prototype.readUInt16BE = function (offset, noAssert) {
1892 return _readUInt16(this, offset, false, noAssert)
1893}
1894
1895function _readUInt32 (buf, offset, littleEndian, noAssert) {
1896 if (!noAssert) {
1897 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1898 assert(offset !== undefined && offset !== null, 'missing offset')
1899 assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
1900 }
1901
1902 var len = buf.length
1903 if (offset >= len)
1904 return
1905
1906 var val
1907 if (littleEndian) {
1908 if (offset + 2 < len)
1909 val = buf[offset + 2] << 16
1910 if (offset + 1 < len)
1911 val |= buf[offset + 1] << 8
1912 val |= buf[offset]
1913 if (offset + 3 < len)
1914 val = val + (buf[offset + 3] << 24 >>> 0)
1915 } else {
1916 if (offset + 1 < len)
1917 val = buf[offset + 1] << 16
1918 if (offset + 2 < len)
1919 val |= buf[offset + 2] << 8
1920 if (offset + 3 < len)
1921 val |= buf[offset + 3]
1922 val = val + (buf[offset] << 24 >>> 0)
1923 }
1924 return val
1925}
1926
1927Buffer.prototype.readUInt32LE = function (offset, noAssert) {
1928 return _readUInt32(this, offset, true, noAssert)
1929}
1930
1931Buffer.prototype.readUInt32BE = function (offset, noAssert) {
1932 return _readUInt32(this, offset, false, noAssert)
1933}
1934
1935Buffer.prototype.readInt8 = function (offset, noAssert) {
1936 if (!noAssert) {
1937 assert(offset !== undefined && offset !== null,
1938 'missing offset')
1939 assert(offset < this.length, 'Trying to read beyond buffer length')
1940 }
1941
1942 if (offset >= this.length)
1943 return
1944
1945 var neg = this[offset] & 0x80
1946 if (neg)
1947 return (0xff - this[offset] + 1) * -1
1948 else
1949 return this[offset]
1950}
1951
1952function _readInt16 (buf, offset, littleEndian, noAssert) {
1953 if (!noAssert) {
1954 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1955 assert(offset !== undefined && offset !== null, 'missing offset')
1956 assert(offset + 1 < buf.length, 'Trying to read beyond buffer length')
1957 }
1958
1959 var len = buf.length
1960 if (offset >= len)
1961 return
1962
1963 var val = _readUInt16(buf, offset, littleEndian, true)
1964 var neg = val & 0x8000
1965 if (neg)
1966 return (0xffff - val + 1) * -1
1967 else
1968 return val
1969}
1970
1971Buffer.prototype.readInt16LE = function (offset, noAssert) {
1972 return _readInt16(this, offset, true, noAssert)
1973}
1974
1975Buffer.prototype.readInt16BE = function (offset, noAssert) {
1976 return _readInt16(this, offset, false, noAssert)
1977}
1978
1979function _readInt32 (buf, offset, littleEndian, noAssert) {
1980 if (!noAssert) {
1981 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
1982 assert(offset !== undefined && offset !== null, 'missing offset')
1983 assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
1984 }
1985
1986 var len = buf.length
1987 if (offset >= len)
1988 return
1989
1990 var val = _readUInt32(buf, offset, littleEndian, true)
1991 var neg = val & 0x80000000
1992 if (neg)
1993 return (0xffffffff - val + 1) * -1
1994 else
1995 return val
1996}
1997
1998Buffer.prototype.readInt32LE = function (offset, noAssert) {
1999 return _readInt32(this, offset, true, noAssert)
2000}
2001
2002Buffer.prototype.readInt32BE = function (offset, noAssert) {
2003 return _readInt32(this, offset, false, noAssert)
2004}
2005
2006function _readFloat (buf, offset, littleEndian, noAssert) {
2007 if (!noAssert) {
2008 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2009 assert(offset + 3 < buf.length, 'Trying to read beyond buffer length')
2010 }
2011
2012 return ieee754.read(buf, offset, littleEndian, 23, 4)
2013}
2014
2015Buffer.prototype.readFloatLE = function (offset, noAssert) {
2016 return _readFloat(this, offset, true, noAssert)
2017}
2018
2019Buffer.prototype.readFloatBE = function (offset, noAssert) {
2020 return _readFloat(this, offset, false, noAssert)
2021}
2022
2023function _readDouble (buf, offset, littleEndian, noAssert) {
2024 if (!noAssert) {
2025 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2026 assert(offset + 7 < buf.length, 'Trying to read beyond buffer length')
2027 }
2028
2029 return ieee754.read(buf, offset, littleEndian, 52, 8)
2030}
2031
2032Buffer.prototype.readDoubleLE = function (offset, noAssert) {
2033 return _readDouble(this, offset, true, noAssert)
2034}
2035
2036Buffer.prototype.readDoubleBE = function (offset, noAssert) {
2037 return _readDouble(this, offset, false, noAssert)
2038}
2039
2040Buffer.prototype.writeUInt8 = function (value, offset, noAssert) {
2041 if (!noAssert) {
2042 assert(value !== undefined && value !== null, 'missing value')
2043 assert(offset !== undefined && offset !== null, 'missing offset')
2044 assert(offset < this.length, 'trying to write beyond buffer length')
2045 verifuint(value, 0xff)
2046 }
2047
2048 if (offset >= this.length) return
2049
2050 this[offset] = value
2051}
2052
2053function _writeUInt16 (buf, value, offset, littleEndian, noAssert) {
2054 if (!noAssert) {
2055 assert(value !== undefined && value !== null, 'missing value')
2056 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2057 assert(offset !== undefined && offset !== null, 'missing offset')
2058 assert(offset + 1 < buf.length, 'trying to write beyond buffer length')
2059 verifuint(value, 0xffff)
2060 }
2061
2062 var len = buf.length
2063 if (offset >= len)
2064 return
2065
2066 for (var i = 0, j = Math.min(len - offset, 2); i < j; i++) {
2067 buf[offset + i] =
2068 (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
2069 (littleEndian ? i : 1 - i) * 8
2070 }
2071}
2072
2073Buffer.prototype.writeUInt16LE = function (value, offset, noAssert) {
2074 _writeUInt16(this, value, offset, true, noAssert)
2075}
2076
2077Buffer.prototype.writeUInt16BE = function (value, offset, noAssert) {
2078 _writeUInt16(this, value, offset, false, noAssert)
2079}
2080
2081function _writeUInt32 (buf, value, offset, littleEndian, noAssert) {
2082 if (!noAssert) {
2083 assert(value !== undefined && value !== null, 'missing value')
2084 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2085 assert(offset !== undefined && offset !== null, 'missing offset')
2086 assert(offset + 3 < buf.length, 'trying to write beyond buffer length')
2087 verifuint(value, 0xffffffff)
2088 }
2089
2090 var len = buf.length
2091 if (offset >= len)
2092 return
2093
2094 for (var i = 0, j = Math.min(len - offset, 4); i < j; i++) {
2095 buf[offset + i] =
2096 (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
2097 }
2098}
2099
2100Buffer.prototype.writeUInt32LE = function (value, offset, noAssert) {
2101 _writeUInt32(this, value, offset, true, noAssert)
2102}
2103
2104Buffer.prototype.writeUInt32BE = function (value, offset, noAssert) {
2105 _writeUInt32(this, value, offset, false, noAssert)
2106}
2107
2108Buffer.prototype.writeInt8 = function (value, offset, noAssert) {
2109 if (!noAssert) {
2110 assert(value !== undefined && value !== null, 'missing value')
2111 assert(offset !== undefined && offset !== null, 'missing offset')
2112 assert(offset < this.length, 'Trying to write beyond buffer length')
2113 verifsint(value, 0x7f, -0x80)
2114 }
2115
2116 if (offset >= this.length)
2117 return
2118
2119 if (value >= 0)
2120 this.writeUInt8(value, offset, noAssert)
2121 else
2122 this.writeUInt8(0xff + value + 1, offset, noAssert)
2123}
2124
2125function _writeInt16 (buf, value, offset, littleEndian, noAssert) {
2126 if (!noAssert) {
2127 assert(value !== undefined && value !== null, 'missing value')
2128 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2129 assert(offset !== undefined && offset !== null, 'missing offset')
2130 assert(offset + 1 < buf.length, 'Trying to write beyond buffer length')
2131 verifsint(value, 0x7fff, -0x8000)
2132 }
2133
2134 var len = buf.length
2135 if (offset >= len)
2136 return
2137
2138 if (value >= 0)
2139 _writeUInt16(buf, value, offset, littleEndian, noAssert)
2140 else
2141 _writeUInt16(buf, 0xffff + value + 1, offset, littleEndian, noAssert)
2142}
2143
2144Buffer.prototype.writeInt16LE = function (value, offset, noAssert) {
2145 _writeInt16(this, value, offset, true, noAssert)
2146}
2147
2148Buffer.prototype.writeInt16BE = function (value, offset, noAssert) {
2149 _writeInt16(this, value, offset, false, noAssert)
2150}
2151
2152function _writeInt32 (buf, value, offset, littleEndian, noAssert) {
2153 if (!noAssert) {
2154 assert(value !== undefined && value !== null, 'missing value')
2155 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2156 assert(offset !== undefined && offset !== null, 'missing offset')
2157 assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
2158 verifsint(value, 0x7fffffff, -0x80000000)
2159 }
2160
2161 var len = buf.length
2162 if (offset >= len)
2163 return
2164
2165 if (value >= 0)
2166 _writeUInt32(buf, value, offset, littleEndian, noAssert)
2167 else
2168 _writeUInt32(buf, 0xffffffff + value + 1, offset, littleEndian, noAssert)
2169}
2170
2171Buffer.prototype.writeInt32LE = function (value, offset, noAssert) {
2172 _writeInt32(this, value, offset, true, noAssert)
2173}
2174
2175Buffer.prototype.writeInt32BE = function (value, offset, noAssert) {
2176 _writeInt32(this, value, offset, false, noAssert)
2177}
2178
2179function _writeFloat (buf, value, offset, littleEndian, noAssert) {
2180 if (!noAssert) {
2181 assert(value !== undefined && value !== null, 'missing value')
2182 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2183 assert(offset !== undefined && offset !== null, 'missing offset')
2184 assert(offset + 3 < buf.length, 'Trying to write beyond buffer length')
2185 verifIEEE754(value, 3.4028234663852886e+38, -3.4028234663852886e+38)
2186 }
2187
2188 var len = buf.length
2189 if (offset >= len)
2190 return
2191
2192 ieee754.write(buf, value, offset, littleEndian, 23, 4)
2193}
2194
2195Buffer.prototype.writeFloatLE = function (value, offset, noAssert) {
2196 _writeFloat(this, value, offset, true, noAssert)
2197}
2198
2199Buffer.prototype.writeFloatBE = function (value, offset, noAssert) {
2200 _writeFloat(this, value, offset, false, noAssert)
2201}
2202
2203function _writeDouble (buf, value, offset, littleEndian, noAssert) {
2204 if (!noAssert) {
2205 assert(value !== undefined && value !== null, 'missing value')
2206 assert(typeof littleEndian === 'boolean', 'missing or invalid endian')
2207 assert(offset !== undefined && offset !== null, 'missing offset')
2208 assert(offset + 7 < buf.length,
2209 'Trying to write beyond buffer length')
2210 verifIEEE754(value, 1.7976931348623157E+308, -1.7976931348623157E+308)
2211 }
2212
2213 var len = buf.length
2214 if (offset >= len)
2215 return
2216
2217 ieee754.write(buf, value, offset, littleEndian, 52, 8)
2218}
2219
2220Buffer.prototype.writeDoubleLE = function (value, offset, noAssert) {
2221 _writeDouble(this, value, offset, true, noAssert)
2222}
2223
2224Buffer.prototype.writeDoubleBE = function (value, offset, noAssert) {
2225 _writeDouble(this, value, offset, false, noAssert)
2226}
2227
2228// fill(value, start=0, end=buffer.length)
2229Buffer.prototype.fill = function (value, start, end) {
2230 if (!value) value = 0
2231 if (!start) start = 0
2232 if (!end) end = this.length
2233
2234 if (typeof value === 'string') {
2235 value = value.charCodeAt(0)
2236 }
2237
2238 assert(typeof value === 'number' && !isNaN(value), 'value is not a number')
2239 assert(end >= start, 'end < start')
2240
2241 // Fill 0 bytes; we're done
2242 if (end === start) return
2243 if (this.length === 0) return
2244
2245 assert(start >= 0 && start < this.length, 'start out of bounds')
2246 assert(end >= 0 && end <= this.length, 'end out of bounds')
2247
2248 for (var i = start; i < end; i++) {
2249 this[i] = value
2250 }
2251}
2252
2253Buffer.prototype.inspect = function () {
2254 var out = []
2255 var len = this.length
2256 for (var i = 0; i < len; i++) {
2257 out[i] = toHex(this[i])
2258 if (i === exports.INSPECT_MAX_BYTES) {
2259 out[i + 1] = '...'
2260 break
2261 }
2262 }
2263 return '<Buffer ' + out.join(' ') + '>'
2264}
2265
2266/**
2267 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
2268 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
2269 */
2270Buffer.prototype.toArrayBuffer = function () {
2271 if (typeof Uint8Array !== 'undefined') {
2272 if (Buffer._useTypedArrays) {
2273 return (new Buffer(this)).buffer
2274 } else {
2275 var buf = new Uint8Array(this.length)
2276 for (var i = 0, len = buf.length; i < len; i += 1)
2277 buf[i] = this[i]
2278 return buf.buffer
2279 }
2280 } else {
2281 throw new Error('Buffer.toArrayBuffer not supported in this browser')
2282 }
2283}
2284
2285// HELPER FUNCTIONS
2286// ================
2287
2288function stringtrim (str) {
2289 if (str.trim) return str.trim()
2290 return str.replace(/^\s+|\s+$/g, '')
2291}
2292
2293var BP = Buffer.prototype
2294
2295/**
2296 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
2297 */
2298Buffer._augment = function (arr) {
2299 arr._isBuffer = true
2300
2301 // save reference to original Uint8Array get/set methods before overwriting
2302 arr._get = arr.get
2303 arr._set = arr.set
2304
2305 // deprecated, will be removed in node 0.13+
2306 arr.get = BP.get
2307 arr.set = BP.set
2308
2309 arr.write = BP.write
2310 arr.toString = BP.toString
2311 arr.toLocaleString = BP.toString
2312 arr.toJSON = BP.toJSON
2313 arr.copy = BP.copy
2314 arr.slice = BP.slice
2315 arr.readUInt8 = BP.readUInt8
2316 arr.readUInt16LE = BP.readUInt16LE
2317 arr.readUInt16BE = BP.readUInt16BE
2318 arr.readUInt32LE = BP.readUInt32LE
2319 arr.readUInt32BE = BP.readUInt32BE
2320 arr.readInt8 = BP.readInt8
2321 arr.readInt16LE = BP.readInt16LE
2322 arr.readInt16BE = BP.readInt16BE
2323 arr.readInt32LE = BP.readInt32LE
2324 arr.readInt32BE = BP.readInt32BE
2325 arr.readFloatLE = BP.readFloatLE
2326 arr.readFloatBE = BP.readFloatBE
2327 arr.readDoubleLE = BP.readDoubleLE
2328 arr.readDoubleBE = BP.readDoubleBE
2329 arr.writeUInt8 = BP.writeUInt8
2330 arr.writeUInt16LE = BP.writeUInt16LE
2331 arr.writeUInt16BE = BP.writeUInt16BE
2332 arr.writeUInt32LE = BP.writeUInt32LE
2333 arr.writeUInt32BE = BP.writeUInt32BE
2334 arr.writeInt8 = BP.writeInt8
2335 arr.writeInt16LE = BP.writeInt16LE
2336 arr.writeInt16BE = BP.writeInt16BE
2337 arr.writeInt32LE = BP.writeInt32LE
2338 arr.writeInt32BE = BP.writeInt32BE
2339 arr.writeFloatLE = BP.writeFloatLE
2340 arr.writeFloatBE = BP.writeFloatBE
2341 arr.writeDoubleLE = BP.writeDoubleLE
2342 arr.writeDoubleBE = BP.writeDoubleBE
2343 arr.fill = BP.fill
2344 arr.inspect = BP.inspect
2345 arr.toArrayBuffer = BP.toArrayBuffer
2346
2347 return arr
2348}
2349
2350// slice(start, end)
2351function clamp (index, len, defaultValue) {
2352 if (typeof index !== 'number') return defaultValue
2353 index = ~~index; // Coerce to integer.
2354 if (index >= len) return len
2355 if (index >= 0) return index
2356 index += len
2357 if (index >= 0) return index
2358 return 0
2359}
2360
2361function coerce (length) {
2362 // Coerce length to a number (possibly NaN), round up
2363 // in case it's fractional (e.g. 123.456) then do a
2364 // double negate to coerce a NaN to 0. Easy, right?
2365 length = ~~Math.ceil(+length)
2366 return length < 0 ? 0 : length
2367}
2368
2369function isArray (subject) {
2370 return (Array.isArray || function (subject) {
2371 return Object.prototype.toString.call(subject) === '[object Array]'
2372 })(subject)
2373}
2374
2375function isArrayish (subject) {
2376 return isArray(subject) || Buffer.isBuffer(subject) ||
2377 subject && typeof subject === 'object' &&
2378 typeof subject.length === 'number'
2379}
2380
2381function toHex (n) {
2382 if (n < 16) return '0' + n.toString(16)
2383 return n.toString(16)
2384}
2385
2386function utf8ToBytes (str) {
2387 var byteArray = []
2388 for (var i = 0; i < str.length; i++) {
2389 var b = str.charCodeAt(i)
2390 if (b <= 0x7F)
2391 byteArray.push(str.charCodeAt(i))
2392 else {
2393 var start = i
2394 if (b >= 0xD800 && b <= 0xDFFF) i++
2395 var h = encodeURIComponent(str.slice(start, i+1)).substr(1).split('%')
2396 for (var j = 0; j < h.length; j++)
2397 byteArray.push(parseInt(h[j], 16))
2398 }
2399 }
2400 return byteArray
2401}
2402
2403function asciiToBytes (str) {
2404 var byteArray = []
2405 for (var i = 0; i < str.length; i++) {
2406 // Node's code seems to be doing this and not & 0x7F..
2407 byteArray.push(str.charCodeAt(i) & 0xFF)
2408 }
2409 return byteArray
2410}
2411
2412function utf16leToBytes (str) {
2413 var c, hi, lo
2414 var byteArray = []
2415 for (var i = 0; i < str.length; i++) {
2416 c = str.charCodeAt(i)
2417 hi = c >> 8
2418 lo = c % 256
2419 byteArray.push(lo)
2420 byteArray.push(hi)
2421 }
2422
2423 return byteArray
2424}
2425
2426function base64ToBytes (str) {
2427 return base64.toByteArray(str)
2428}
2429
2430function blitBuffer (src, dst, offset, length) {
2431 var pos
2432 for (var i = 0; i < length; i++) {
2433 if ((i + offset >= dst.length) || (i >= src.length))
2434 break
2435 dst[i + offset] = src[i]
2436 }
2437 return i
2438}
2439
2440function decodeUtf8Char (str) {
2441 try {
2442 return decodeURIComponent(str)
2443 } catch (err) {
2444 return String.fromCharCode(0xFFFD) // UTF 8 invalid char
2445 }
2446}
2447
2448/*
2449 * We have to make sure that the value is a valid integer. This means that it
2450 * is non-negative. It has no fractional component and that it does not
2451 * exceed the maximum allowed value.
2452 */
2453function verifuint (value, max) {
2454 assert(typeof value === 'number', 'cannot write a non-number as a number')
2455 assert(value >= 0, 'specified a negative value for writing an unsigned value')
2456 assert(value <= max, 'value is larger than maximum value for type')
2457 assert(Math.floor(value) === value, 'value has a fractional component')
2458}
2459
2460function verifsint (value, max, min) {
2461 assert(typeof value === 'number', 'cannot write a non-number as a number')
2462 assert(value <= max, 'value larger than maximum allowed value')
2463 assert(value >= min, 'value smaller than minimum allowed value')
2464 assert(Math.floor(value) === value, 'value has a fractional component')
2465}
2466
2467function verifIEEE754 (value, max, min) {
2468 assert(typeof value === 'number', 'cannot write a non-number as a number')
2469 assert(value <= max, 'value larger than maximum allowed value')
2470 assert(value >= min, 'value smaller than minimum allowed value')
2471}
2472
2473function assert (test, message) {
2474 if (!test) throw new Error(message || 'Failed assertion')
2475}
2476
2477},{"base64-js":11,"ieee754":19}],13:[function(require,module,exports){
2478var Buffer = require('buffer').Buffer;
2479var intSize = 4;
2480var zeroBuffer = new Buffer(intSize); zeroBuffer.fill(0);
2481var chrsz = 8;
2482
2483function toArray(buf, bigEndian) {
2484 if ((buf.length % intSize) !== 0) {
2485 var len = buf.length + (intSize - (buf.length % intSize));
2486 buf = Buffer.concat([buf, zeroBuffer], len);
2487 }
2488
2489 var arr = [];
2490 var fn = bigEndian ? buf.readInt32BE : buf.readInt32LE;
2491 for (var i = 0; i < buf.length; i += intSize) {
2492 arr.push(fn.call(buf, i));
2493 }
2494 return arr;
2495}
2496
2497function toBuffer(arr, size, bigEndian) {
2498 var buf = new Buffer(size);
2499 var fn = bigEndian ? buf.writeInt32BE : buf.writeInt32LE;
2500 for (var i = 0; i < arr.length; i++) {
2501 fn.call(buf, arr[i], i * 4, true);
2502 }
2503 return buf;
2504}
2505
2506function hash(buf, fn, hashSize, bigEndian) {
2507 if (!Buffer.isBuffer(buf)) buf = new Buffer(buf);
2508 var arr = fn(toArray(buf, bigEndian), buf.length * chrsz);
2509 return toBuffer(arr, hashSize, bigEndian);
2510}
2511
2512module.exports = { hash: hash };
2513
2514},{"buffer":12}],14:[function(require,module,exports){
2515var Buffer = require('buffer').Buffer
2516var sha = require('./sha')
2517var sha256 = require('./sha256')
2518var rng = require('./rng')
2519var md5 = require('./md5')
2520
2521var algorithms = {
2522 sha1: sha,
2523 sha256: sha256,
2524 md5: md5
2525}
2526
2527var blocksize = 64
2528var zeroBuffer = new Buffer(blocksize); zeroBuffer.fill(0)
2529function hmac(fn, key, data) {
2530 if(!Buffer.isBuffer(key)) key = new Buffer(key)
2531 if(!Buffer.isBuffer(data)) data = new Buffer(data)
2532
2533 if(key.length > blocksize) {
2534 key = fn(key)
2535 } else if(key.length < blocksize) {
2536 key = Buffer.concat([key, zeroBuffer], blocksize)
2537 }
2538
2539 var ipad = new Buffer(blocksize), opad = new Buffer(blocksize)
2540 for(var i = 0; i < blocksize; i++) {
2541 ipad[i] = key[i] ^ 0x36
2542 opad[i] = key[i] ^ 0x5C
2543 }
2544
2545 var hash = fn(Buffer.concat([ipad, data]))
2546 return fn(Buffer.concat([opad, hash]))
2547}
2548
2549function hash(alg, key) {
2550 alg = alg || 'sha1'
2551 var fn = algorithms[alg]
2552 var bufs = []
2553 var length = 0
2554 if(!fn) error('algorithm:', alg, 'is not yet supported')
2555 return {
2556 update: function (data) {
2557 if(!Buffer.isBuffer(data)) data = new Buffer(data)
2558
2559 bufs.push(data)
2560 length += data.length
2561 return this
2562 },
2563 digest: function (enc) {
2564 var buf = Buffer.concat(bufs)
2565 var r = key ? hmac(fn, key, buf) : fn(buf)
2566 bufs = null
2567 return enc ? r.toString(enc) : r
2568 }
2569 }
2570}
2571
2572function error () {
2573 var m = [].slice.call(arguments).join(' ')
2574 throw new Error([
2575 m,
2576 'we accept pull requests',
2577 'http://github.com/dominictarr/crypto-browserify'
2578 ].join('\n'))
2579}
2580
2581exports.createHash = function (alg) { return hash(alg) }
2582exports.createHmac = function (alg, key) { return hash(alg, key) }
2583exports.randomBytes = function(size, callback) {
2584 if (callback && callback.call) {
2585 try {
2586 callback.call(this, undefined, new Buffer(rng(size)))
2587 } catch (err) { callback(err) }
2588 } else {
2589 return new Buffer(rng(size))
2590 }
2591}
2592
2593function each(a, f) {
2594 for(var i in a)
2595 f(a[i], i)
2596}
2597
2598// the least I can do is make error messages for the rest of the node.js/crypto api.
2599each(['createCredentials'
2600, 'createCipher'
2601, 'createCipheriv'
2602, 'createDecipher'
2603, 'createDecipheriv'
2604, 'createSign'
2605, 'createVerify'
2606, 'createDiffieHellman'
2607, 'pbkdf2'], function (name) {
2608 exports[name] = function () {
2609 error('sorry,', name, 'is not implemented yet')
2610 }
2611})
2612
2613},{"./md5":15,"./rng":16,"./sha":17,"./sha256":18,"buffer":12}],15:[function(require,module,exports){
2614/*
2615 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
2616 * Digest Algorithm, as defined in RFC 1321.
2617 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
2618 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
2619 * Distributed under the BSD License
2620 * See http://pajhome.org.uk/crypt/md5 for more info.
2621 */
2622
2623var helpers = require('./helpers');
2624
2625/*
2626 * Perform a simple self-test to see if the VM is working
2627 */
2628function md5_vm_test()
2629{
2630 return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
2631}
2632
2633/*
2634 * Calculate the MD5 of an array of little-endian words, and a bit length
2635 */
2636function core_md5(x, len)
2637{
2638 /* append padding */
2639 x[len >> 5] |= 0x80 << ((len) % 32);
2640 x[(((len + 64) >>> 9) << 4) + 14] = len;
2641
2642 var a = 1732584193;
2643 var b = -271733879;
2644 var c = -1732584194;
2645 var d = 271733878;
2646
2647 for(var i = 0; i < x.length; i += 16)
2648 {
2649 var olda = a;
2650 var oldb = b;
2651 var oldc = c;
2652 var oldd = d;
2653
2654 a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
2655 d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
2656 c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
2657 b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
2658 a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
2659 d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
2660 c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
2661 b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
2662 a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
2663 d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
2664 c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
2665 b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
2666 a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
2667 d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
2668 c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
2669 b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
2670
2671 a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
2672 d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
2673 c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
2674 b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
2675 a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
2676 d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
2677 c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
2678 b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
2679 a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
2680 d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
2681 c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
2682 b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
2683 a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
2684 d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
2685 c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
2686 b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
2687
2688 a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
2689 d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
2690 c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
2691 b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
2692 a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
2693 d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
2694 c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
2695 b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
2696 a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
2697 d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
2698 c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
2699 b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
2700 a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
2701 d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
2702 c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
2703 b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
2704
2705 a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
2706 d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
2707 c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
2708 b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
2709 a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
2710 d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
2711 c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
2712 b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
2713 a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
2714 d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
2715 c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
2716 b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
2717 a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
2718 d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
2719 c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
2720 b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
2721
2722 a = safe_add(a, olda);
2723 b = safe_add(b, oldb);
2724 c = safe_add(c, oldc);
2725 d = safe_add(d, oldd);
2726 }
2727 return Array(a, b, c, d);
2728
2729}
2730
2731/*
2732 * These functions implement the four basic operations the algorithm uses.
2733 */
2734function md5_cmn(q, a, b, x, s, t)
2735{
2736 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
2737}
2738function md5_ff(a, b, c, d, x, s, t)
2739{
2740 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
2741}
2742function md5_gg(a, b, c, d, x, s, t)
2743{
2744 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
2745}
2746function md5_hh(a, b, c, d, x, s, t)
2747{
2748 return md5_cmn(b ^ c ^ d, a, b, x, s, t);
2749}
2750function md5_ii(a, b, c, d, x, s, t)
2751{
2752 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
2753}
2754
2755/*
2756 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
2757 * to work around bugs in some JS interpreters.
2758 */
2759function safe_add(x, y)
2760{
2761 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
2762 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
2763 return (msw << 16) | (lsw & 0xFFFF);
2764}
2765
2766/*
2767 * Bitwise rotate a 32-bit number to the left.
2768 */
2769function bit_rol(num, cnt)
2770{
2771 return (num << cnt) | (num >>> (32 - cnt));
2772}
2773
2774module.exports = function md5(buf) {
2775 return helpers.hash(buf, core_md5, 16);
2776};
2777
2778},{"./helpers":13}],16:[function(require,module,exports){
2779// Original code adapted from Robert Kieffer.
2780// details at https://github.com/broofa/node-uuid
2781(function() {
2782 var _global = this;
2783
2784 var mathRNG, whatwgRNG;
2785
2786 // NOTE: Math.random() does not guarantee "cryptographic quality"
2787 mathRNG = function(size) {
2788 var bytes = new Array(size);
2789 var r;
2790
2791 for (var i = 0, r; i < size; i++) {
2792 if ((i & 0x03) == 0) r = Math.random() * 0x100000000;
2793 bytes[i] = r >>> ((i & 0x03) << 3) & 0xff;
2794 }
2795
2796 return bytes;
2797 }
2798
2799 if (_global.crypto && crypto.getRandomValues) {
2800 whatwgRNG = function(size) {
2801 var bytes = new Uint8Array(size);
2802 crypto.getRandomValues(bytes);
2803 return bytes;
2804 }
2805 }
2806
2807 module.exports = whatwgRNG || mathRNG;
2808
2809}())
2810
2811},{}],17:[function(require,module,exports){
2812/*
2813 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
2814 * in FIPS PUB 180-1
2815 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
2816 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
2817 * Distributed under the BSD License
2818 * See http://pajhome.org.uk/crypt/md5 for details.
2819 */
2820
2821var helpers = require('./helpers');
2822
2823/*
2824 * Calculate the SHA-1 of an array of big-endian words, and a bit length
2825 */
2826function core_sha1(x, len)
2827{
2828 /* append padding */
2829 x[len >> 5] |= 0x80 << (24 - len % 32);
2830 x[((len + 64 >> 9) << 4) + 15] = len;
2831
2832 var w = Array(80);
2833 var a = 1732584193;
2834 var b = -271733879;
2835 var c = -1732584194;
2836 var d = 271733878;
2837 var e = -1009589776;
2838
2839 for(var i = 0; i < x.length; i += 16)
2840 {
2841 var olda = a;
2842 var oldb = b;
2843 var oldc = c;
2844 var oldd = d;
2845 var olde = e;
2846
2847 for(var j = 0; j < 80; j++)
2848 {
2849 if(j < 16) w[j] = x[i + j];
2850 else w[j] = rol(w[j-3] ^ w[j-8] ^ w[j-14] ^ w[j-16], 1);
2851 var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
2852 safe_add(safe_add(e, w[j]), sha1_kt(j)));
2853 e = d;
2854 d = c;
2855 c = rol(b, 30);
2856 b = a;
2857 a = t;
2858 }
2859
2860 a = safe_add(a, olda);
2861 b = safe_add(b, oldb);
2862 c = safe_add(c, oldc);
2863 d = safe_add(d, oldd);
2864 e = safe_add(e, olde);
2865 }
2866 return Array(a, b, c, d, e);
2867
2868}
2869
2870/*
2871 * Perform the appropriate triplet combination function for the current
2872 * iteration
2873 */
2874function sha1_ft(t, b, c, d)
2875{
2876 if(t < 20) return (b & c) | ((~b) & d);
2877 if(t < 40) return b ^ c ^ d;
2878 if(t < 60) return (b & c) | (b & d) | (c & d);
2879 return b ^ c ^ d;
2880}
2881
2882/*
2883 * Determine the appropriate additive constant for the current iteration
2884 */
2885function sha1_kt(t)
2886{
2887 return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
2888 (t < 60) ? -1894007588 : -899497514;
2889}
2890
2891/*
2892 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
2893 * to work around bugs in some JS interpreters.
2894 */
2895function safe_add(x, y)
2896{
2897 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
2898 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
2899 return (msw << 16) | (lsw & 0xFFFF);
2900}
2901
2902/*
2903 * Bitwise rotate a 32-bit number to the left.
2904 */
2905function rol(num, cnt)
2906{
2907 return (num << cnt) | (num >>> (32 - cnt));
2908}
2909
2910module.exports = function sha1(buf) {
2911 return helpers.hash(buf, core_sha1, 20, true);
2912};
2913
2914},{"./helpers":13}],18:[function(require,module,exports){
2915
2916/**
2917 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
2918 * in FIPS 180-2
2919 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
2920 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
2921 *
2922 */
2923
2924var helpers = require('./helpers');
2925
2926var safe_add = function(x, y) {
2927 var lsw = (x & 0xFFFF) + (y & 0xFFFF);
2928 var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
2929 return (msw << 16) | (lsw & 0xFFFF);
2930};
2931
2932var S = function(X, n) {
2933 return (X >>> n) | (X << (32 - n));
2934};
2935
2936var R = function(X, n) {
2937 return (X >>> n);
2938};
2939
2940var Ch = function(x, y, z) {
2941 return ((x & y) ^ ((~x) & z));
2942};
2943
2944var Maj = function(x, y, z) {
2945 return ((x & y) ^ (x & z) ^ (y & z));
2946};
2947
2948var Sigma0256 = function(x) {
2949 return (S(x, 2) ^ S(x, 13) ^ S(x, 22));
2950};
2951
2952var Sigma1256 = function(x) {
2953 return (S(x, 6) ^ S(x, 11) ^ S(x, 25));
2954};
2955
2956var Gamma0256 = function(x) {
2957 return (S(x, 7) ^ S(x, 18) ^ R(x, 3));
2958};
2959
2960var Gamma1256 = function(x) {
2961 return (S(x, 17) ^ S(x, 19) ^ R(x, 10));
2962};
2963
2964var core_sha256 = function(m, l) {
2965 var K = new Array(0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2);
2966 var HASH = new Array(0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19);
2967 var W = new Array(64);
2968 var a, b, c, d, e, f, g, h, i, j;
2969 var T1, T2;
2970 /* append padding */
2971 m[l >> 5] |= 0x80 << (24 - l % 32);
2972 m[((l + 64 >> 9) << 4) + 15] = l;
2973 for (var i = 0; i < m.length; i += 16) {
2974 a = HASH[0]; b = HASH[1]; c = HASH[2]; d = HASH[3]; e = HASH[4]; f = HASH[5]; g = HASH[6]; h = HASH[7];
2975 for (var j = 0; j < 64; j++) {
2976 if (j < 16) {
2977 W[j] = m[j + i];
2978 } else {
2979 W[j] = safe_add(safe_add(safe_add(Gamma1256(W[j - 2]), W[j - 7]), Gamma0256(W[j - 15])), W[j - 16]);
2980 }
2981 T1 = safe_add(safe_add(safe_add(safe_add(h, Sigma1256(e)), Ch(e, f, g)), K[j]), W[j]);
2982 T2 = safe_add(Sigma0256(a), Maj(a, b, c));
2983 h = g; g = f; f = e; e = safe_add(d, T1); d = c; c = b; b = a; a = safe_add(T1, T2);
2984 }
2985 HASH[0] = safe_add(a, HASH[0]); HASH[1] = safe_add(b, HASH[1]); HASH[2] = safe_add(c, HASH[2]); HASH[3] = safe_add(d, HASH[3]);
2986 HASH[4] = safe_add(e, HASH[4]); HASH[5] = safe_add(f, HASH[5]); HASH[6] = safe_add(g, HASH[6]); HASH[7] = safe_add(h, HASH[7]);
2987 }
2988 return HASH;
2989};
2990
2991module.exports = function sha256(buf) {
2992 return helpers.hash(buf, core_sha256, 32, true);
2993};
2994
2995},{"./helpers":13}],19:[function(require,module,exports){
2996exports.read = function (buffer, offset, isLE, mLen, nBytes) {
2997 var e, m
2998 var eLen = nBytes * 8 - mLen - 1
2999 var eMax = (1 << eLen) - 1
3000 var eBias = eMax >> 1
3001 var nBits = -7
3002 var i = isLE ? (nBytes - 1) : 0
3003 var d = isLE ? -1 : 1
3004 var s = buffer[offset + i]
3005
3006 i += d
3007
3008 e = s & ((1 << (-nBits)) - 1)
3009 s >>= (-nBits)
3010 nBits += eLen
3011 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3012
3013 m = e & ((1 << (-nBits)) - 1)
3014 e >>= (-nBits)
3015 nBits += mLen
3016 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
3017
3018 if (e === 0) {
3019 e = 1 - eBias
3020 } else if (e === eMax) {
3021 return m ? NaN : ((s ? -1 : 1) * Infinity)
3022 } else {
3023 m = m + Math.pow(2, mLen)
3024 e = e - eBias
3025 }
3026 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
3027}
3028
3029exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
3030 var e, m, c
3031 var eLen = nBytes * 8 - mLen - 1
3032 var eMax = (1 << eLen) - 1
3033 var eBias = eMax >> 1
3034 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
3035 var i = isLE ? 0 : (nBytes - 1)
3036 var d = isLE ? 1 : -1
3037 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
3038
3039 value = Math.abs(value)
3040
3041 if (isNaN(value) || value === Infinity) {
3042 m = isNaN(value) ? 1 : 0
3043 e = eMax
3044 } else {
3045 e = Math.floor(Math.log(value) / Math.LN2)
3046 if (value * (c = Math.pow(2, -e)) < 1) {
3047 e--
3048 c *= 2
3049 }
3050 if (e + eBias >= 1) {
3051 value += rt / c
3052 } else {
3053 value += rt * Math.pow(2, 1 - eBias)
3054 }
3055 if (value * c >= 2) {
3056 e++
3057 c /= 2
3058 }
3059
3060 if (e + eBias >= eMax) {
3061 m = 0
3062 e = eMax
3063 } else if (e + eBias >= 1) {
3064 m = (value * c - 1) * Math.pow(2, mLen)
3065 e = e + eBias
3066 } else {
3067 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
3068 e = 0
3069 }
3070 }
3071
3072 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
3073
3074 e = (e << mLen) | m
3075 eLen += mLen
3076 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
3077
3078 buffer[offset + i - d] |= s * 128
3079}
3080
3081},{}]},{},[6])
\No newline at end of file