PageSourceSearch

https://www.hidro.ro/wp-content/plugins/leaftile/public/js/leaflet.shapefile/shp.js?ver=7.1.2

js hidro.ro collected 2026-10-02 06:05:21 UTC 532,706 bytes, 17,726 lines download raw bytes

1(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.shp = f()}})(function(){var define,module,exports;return (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);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.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'use strict';
3var Promise = require('lie');
4module.exports = binaryAjax;
5function binaryAjax(url){
6	return new Promise(function(resolve,reject){
7		var type = url.slice(-3);
8		var ajax = new XMLHttpRequest();
9		ajax.open('GET',url,true);
10		if(type !== 'prj'){
11			ajax.responseType='arraybuffer';
12		}
13		ajax.addEventListener('load', function (){
14			if(ajax.status>399){
15				if(type==='prj'){
16					return resolve(false);
17				}else{
18					return reject(new Error(ajax.status));
19				}
20			}
21			resolve(ajax.response);
22		}, false);
23		ajax.send();
24	});
25}
26},{"lie":51}],2:[function(require,module,exports){
27'use strict';
28function isClockWise(array){
29	var sum = 0;
30	var i = 1;
31	var len = array.length;
32	var prev,cur;
33	while(i<len){
34		prev = cur||array[0];
35		cur = array[i];
36		sum += ((cur[0]-prev[0])*(cur[1]+prev[1]));
37		i++;
38	}
39	return sum > 0;
40}
41function polyReduce(a,b){
42	if(isClockWise(b)||!a.length){
43		a.push([b]);
44	}else{
45		a[a.length-1].push(b);
46	}
47	return a;
48}
49ParseShp.prototype.parsePoint = function (data){
50	return {
51		'type': 'Point',
52		'coordinates': this.parseCoord(data,0)
53	};
54};
55ParseShp.prototype.parseZPoint = function (data){
56	var pointXY = this.parsePoint(data);
57	pointXY.coordinates.push(this.parseCoord(data,16));
58	return pointXY;
59};
60ParseShp.prototype.parsePointArray = function (data,offset,num){
61	var out = [];
62	var done = 0;
63	while(done<num){
64		out.push(this.parseCoord(data,offset));
65		offset += 16;
66		done++;
67	}
68	return out;
69};
70ParseShp.prototype.parseZPointArray = function (data,zOffset,num,coordinates){
71	var i = 0;
72	while(i<num){
73		coordinates[i].push(data.getFloat64(zOffset,true));
74		i++;
75		zOffset += 8;
76	}
77	return coordinates;
78};
79ParseShp.prototype.parseArrayGroup = function (data,offset,partOffset,num,tot){
80	var out = [];
81	var done = 0;
82	var curNum,nextNum=0,pointNumber;
83	while(done<num){
84		done++;
85		partOffset += 4;
86		curNum = nextNum;
87		if(done===num){
88			nextNum = tot;
89		}else{
90			nextNum = data.getInt32(partOffset,true);
91		}
92		pointNumber = nextNum - curNum;
93		if(!pointNumber){
94			continue;
95		}
96		out.push(this.parsePointArray(data,offset,pointNumber));
97		offset += (pointNumber<<4);
98	}
99	return out;
100};
101ParseShp.prototype.parseZArrayGroup = function(data,zOffset,num,coordinates){
102	var i = 0;
103	while(i<num){
104		coordinates[i] = this.parseZPointArray(data,zOffset,coordinates[i].length,coordinates[i]);
105		zOffset += (coordinates[i].length<<3);
106		i++;
107	}
108	return coordinates;
109};
110ParseShp.prototype.parseMultiPoint = function (data){
111	var out = {};
112	var mins = this.parseCoord(data,0);
113	var maxs = this.parseCoord(data,16);
114	out.bbox = [
115		mins[0],
116		mins[1],
117		maxs[0],
118		maxs[1]
119	];
120	var num = data.getInt32(32,true);
121	var offset = 36;
122	if(num===1){
123		out.type = 'Point';
124		out.coordinates = this.parseCoord(data,offset);
125	}else{
126		out.type = 'MultiPoint';
127		out.coordinates = this.parsePointArray(data,offset,num);
128	}
129	return out;
130};
131ParseShp.prototype.parseZMultiPoint = function(data){
132	var geoJson = this.parseMultiPoint(data);
133	var num;
134	if(geoJson.type === 'Point'){
135		geoJson.coordinates.push(data.getFloat64(72,true));
136		return geoJson;
137	}else{
138		num = geoJson.coordinates.length;
139	}
140	var zOffset = 56 + (num<<4);
141	geoJson.coordinates =  this.parseZPointArray(data,zOffset,num,geoJson.coordinates);
142	return geoJson;
143};
144ParseShp.prototype.parsePolyline = function (data){
145	var out = {};
146	var mins = this.parseCoord(data,0);
147	var maxs = this.parseCoord(data,16);
148	out.bbox = [
149		mins[0],
150		mins[1],
151		maxs[0],
152		maxs[1]
153	];
154	var numParts = data.getInt32(32,true);
155	var num = data.getInt32(36,true);
156	var offset,partOffset;
157	if(numParts === 1){
158		out.type = 'LineString';
159		offset = 44;
160		out.coordinates = this.parsePointArray(data,offset,num);
161	}else{
162		out.type = 'MultiLineString';
163		offset = 40 + (numParts<<2);
164		partOffset = 40;
165		out.coordinates = this.parseArrayGroup(data,offset,partOffset,numParts,num);
166	}
167	return out;
168};
169ParseShp.prototype.parseZPolyline = function(data){
170	var geoJson = this.parsePolyline(data);
171	var num = geoJson.coordinates.length;
172	var zOffset = 60 + (num<<4);
173	if(geoJson.type === 'LineString'){
174		geoJson.coordinates =  this.parseZPointArray(data,zOffset,num,geoJson.coordinates);
175		return geoJson;
176	}else{
177		geoJson.coordinates =  this.parseZArrayGroup(data,zOffset,num,geoJson.coordinates);
178		return geoJson;
179	}
180};
181ParseShp.prototype.polyFuncs = function (out){
182	if(out.type === 'LineString'){
183		out.type = 'Polygon';
184		out.coordinates = [out.coordinates];
185		return out;
186	}else{
187		out.coordinates = out.coordinates.reduce(polyReduce,[]);
188		if(out.coordinates.length === 1){
189			out.type = 'Polygon';
190			out.coordinates = out.coordinates[0];
191			return out;
192		}else{
193			out.type = 'MultiPolygon';
194			return out;
195		}
196	}
197};
198ParseShp.prototype.parsePolygon = function (data){
199	return this.polyFuncs(this.parsePolyline(data));
200};
201ParseShp.prototype.parseZPolygon = function(data){
202	return this.polyFuncs(this.parseZPolyline(data));
203};
204var shpFuncObj = {
205	1:'parsePoint',
206	3:'parsePolyline',
207	5:'parsePolygon',
208	8:'parseMultiPoint',
209	11:'parseZPoint',
210	13:'parseZPolyline',
211	15:'parseZPolygon',
212	18:'parseZMultiPoint'
213};
214
215
216
217function makeParseCoord(trans){
218	if(trans){
219		return function(data,offset){
220			return trans.inverse([data.getFloat64(offset,true),data.getFloat64(offset+8,true)]);
221		};
222	}else{
223		return function(data,offset){
224			return [data.getFloat64(offset,true),data.getFloat64(offset+8,true)];
225		};
226	}
227}
228function ParseShp(buffer,trans){
229	if(!(this instanceof ParseShp)){
230		return new ParseShp(buffer,trans);
231	}
232	this.buffer = buffer;
233	this.shpFuncs(trans);
234	this.rows = this.getRows();
235}
236ParseShp.prototype.shpFuncs = function (tran){
237	var num = this.getShpCode();
238	if(num>20){
239		num -= 20;
240	}
241	if(!(num in shpFuncObj)){
242		throw new Error('I don\'t know that shp type');
243	}
244	this.parseFunc = this[shpFuncObj[num]];
245	this.parseCoord = makeParseCoord(tran);
246};
247ParseShp.prototype.getShpCode = function(){
248	return this.parseHeader().shpCode;
249};
250ParseShp.prototype.parseHeader = function (){
251	var view = new DataView(this.buffer,0,100) ;
252	return {
253		length : view.getInt32(6<<2,false),
254		version : view.getInt32(7<<2,true),
255		shpCode : view.getInt32(8<<2,true),
256		bbox : [
257			view.getFloat64(9<<2,true),
258			view.getFloat64(11<<2,true),
259			view.getFloat64(13<<2,true),
260			view.getFloat64(13<<2,true)
261		]
262	};
263};
264ParseShp.prototype.getRows = function(){
265	var offset=100;
266	var len = this.buffer.byteLength;
267	var out = [];
268	var current;
269	while(offset<len){
270		current = this.getRow(offset);
271		offset += 8;
272		offset += current.len;
273		if(current.type){
274			out.push(this.parseFunc(current.data));
275		}
276	}
277	return out;
278};
279ParseShp.prototype.getRow = function(offset){
280	var view = new DataView(this.buffer,offset,12);
281	var len = view.getInt32(4,false) << 1;
282	var data = new DataView(this.buffer,offset+12,len - 4);
283	
284	return {
285		id:view.getInt32(0,false),
286		len:len,
287		data:data,
288		type:view.getInt32(8,true)
289	};
290};
291module.exports = function(buffer, trans){
292	return new ParseShp(buffer, trans).rows;
293};
294},{}],3:[function(require,module,exports){
295'use strict';
296module.exports = toArrayBuffer;
297function toArrayBuffer(buffer) {
298    var arrayBuffer = new ArrayBuffer(buffer.length);
299    var view = new Uint8Array(arrayBuffer);
300    var i = -1;
301    var len = buffer.length;
302    while (++i < len) {
303        view[i] = buffer[i];
304    }
305    return arrayBuffer;
306}
307},{}],4:[function(require,module,exports){
308'use strict';
309
310var JSZip = require('jszip');
311module.exports = function(buffer) {
312	var zip = new JSZip(buffer);
313	var files = zip.file(/.+/);
314	var out = {};
315	files.forEach(function(a) {
316		if (a.name.slice(-3).toLowerCase() === 'shp' || a.name.slice(-3).toLowerCase() === 'dbf') {
317			out[a.name] = a.asArrayBuffer();
318		}
319		else {
320			out[a.name] = a.asText();
321		}
322	});
323	return out;
324};
325
326},{"jszip":17}],5:[function(require,module,exports){
327/*!
328 * The buffer module from node.js, for the browser.
329 *
330 * @author   Feross Aboukhadijeh <[email protected]> <http://feross.org>
331 * @license  MIT
332 */
333
334var base64 = require('base64-js')
335var ieee754 = require('ieee754')
336var isArray = require('is-array')
337
338exports.Buffer = Buffer
339exports.SlowBuffer = SlowBuffer
340exports.INSPECT_MAX_BYTES = 50
341Buffer.poolSize = 8192 // not used by this implementation
342
343var rootParent = {}
344
345/**
346 * If `Buffer.TYPED_ARRAY_SUPPORT`:
347 *   === true    Use Uint8Array implementation (fastest)
348 *   === false   Use Object implementation (most compatible, even IE6)
349 *
350 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
351 * Opera 11.6+, iOS 4.2+.
352 *
353 * Due to various browser bugs, sometimes the Object implementation will be used even
354 * when the browser supports typed arrays.
355 *
356 * Note:
357 *
358 *   - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
359 *     See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
360 *
361 *   - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
362 *     on objects.
363 *
364 *   - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
365 *
366 *   - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
367 *     incorrect length in some situations.
368
369 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
370 * get the Object implementation, which is slower but behaves correctly.
371 */
372Buffer.TYPED_ARRAY_SUPPORT = (function () {
373  function Bar () {}
374  try {
375    var arr = new Uint8Array(1)
376    arr.foo = function () { return 42 }
377    arr.constructor = Bar
378    return arr.foo() === 42 && // typed array instances can be augmented
379        arr.constructor === Bar && // constructor can be set
380        typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
381        arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
382  } catch (e) {
383    return false
384  }
385})()
386
387function kMaxLength () {
388  return Buffer.TYPED_ARRAY_SUPPORT
389    ? 0x7fffffff
390    : 0x3fffffff
391}
392
393/**
394 * Class: Buffer
395 * =============
396 *
397 * The Buffer constructor returns instances of `Uint8Array` that are augmented
398 * with function properties for all the node `Buffer` API functions. We use
399 * `Uint8Array` so that square bracket notation works as expected -- it returns
400 * a single octet.
401 *
402 * By augmenting the instances, we can avoid modifying the `Uint8Array`
403 * prototype.
404 */
405function Buffer (arg) {
406  if (!(this instanceof Buffer)) {
407    // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
408    if (arguments.length > 1) return new Buffer(arg, arguments[1])
409    return new Buffer(arg)
410  }
411
412  this.length = 0
413  this.parent = undefined
414
415  // Common case.
416  if (typeof arg === 'number') {
417    return fromNumber(this, arg)
418  }
419
420  // Slightly less common case.
421  if (typeof arg === 'string') {
422    return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
423  }
424
425  // Unusual.
426  return fromObject(this, arg)
427}
428
429function fromNumber (that, length) {
430  that = allocate(that, length < 0 ? 0 : checked(length) | 0)
431  if (!Buffer.TYPED_ARRAY_SUPPORT) {
432    for (var i = 0; i < length; i++) {
433      that[i] = 0
434    }
435  }
436  return that
437}
438
439function fromString (that, string, encoding) {
440  if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
441
442  // Assumption: byteLength() return value is always < kMaxLength.
443  var length = byteLength(string, encoding) | 0
444  that = allocate(that, length)
445
446  that.write(string, encoding)
447  return that
448}
449
450function fromObject (that, object) {
451  if (Buffer.isBuffer(object)) return fromBuffer(that, object)
452
453  if (isArray(object)) return fromArray(that, object)
454
455  if (object == null) {
456    throw new TypeError('must start with number, buffer, array or string')
457  }
458
459  if (typeof ArrayBuffer !== 'undefined') {
460    if (object.buffer instanceof ArrayBuffer) {
461      return fromTypedArray(that, object)
462    }
463    if (object instanceof ArrayBuffer) {
464      return fromArrayBuffer(that, object)
465    }
466  }
467
468  if (object.length) return fromArrayLike(that, object)
469
470  return fromJsonObject(that, object)
471}
472
473function fromBuffer (that, buffer) {
474  var length = checked(buffer.length) | 0
475  that = allocate(that, length)
476  buffer.copy(that, 0, 0, length)
477  return that
478}
479
480function fromArray (that, array) {
481  var length = checked(array.length) | 0
482  that = allocate(that, length)
483  for (var i = 0; i < length; i += 1) {
484    that[i] = array[i] & 255
485  }
486  return that
487}
488
489// Duplicate of fromArray() to keep fromArray() monomorphic.
490function fromTypedArray (that, array) {
491  var length = checked(array.length) | 0
492  that = allocate(that, length)
493  // Truncating the elements is probably not what people expect from typed
494  // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
495  // of the old Buffer constructor.
496  for (var i = 0; i < length; i += 1) {
497    that[i] = array[i] & 255
498  }
499  return that
500}
501
502function fromArrayBuffer (that, array) {
503  if (Buffer.TYPED_ARRAY_SUPPORT) {
504    // Return an augmented `Uint8Array` instance, for best performance
505    array.byteLength
506    that = Buffer._augment(new Uint8Array(array))
507  } else {
508    // Fallback: Return an object instance of the Buffer class
509    that = fromTypedArray(that, new Uint8Array(array))
510  }
511  return that
512}
513
514function fromArrayLike (that, array) {
515  var length = checked(array.length) | 0
516  that = allocate(that, length)
517  for (var i = 0; i < length; i += 1) {
518    that[i] = array[i] & 255
519  }
520  return that
521}
522
523// Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
524// Returns a zero-length buffer for inputs that don't conform to the spec.
525function fromJsonObject (that, object) {
526  var array
527  var length = 0
528
529  if (object.type === 'Buffer' && isArray(object.data)) {
530    array = object.data
531    length = checked(array.length) | 0
532  }
533  that = allocate(that, length)
534
535  for (var i = 0; i < length; i += 1) {
536    that[i] = array[i] & 255
537  }
538  return that
539}
540
541function allocate (that, length) {
542  if (Buffer.TYPED_ARRAY_SUPPORT) {
543    // Return an augmented `Uint8Array` instance, for best performance
544    that = Buffer._augment(new Uint8Array(length))
545  } else {
546    // Fallback: Return an object instance of the Buffer class
547    that.length = length
548    that._isBuffer = true
549  }
550
551  var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
552  if (fromPool) that.parent = rootParent
553
554  return that
555}
556
557function checked (length) {
558  // Note: cannot use `length < kMaxLength` here because that fails when
559  // length is NaN (which is otherwise coerced to zero.)
560  if (length >= kMaxLength()) {
561    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
562                         'size: 0x' + kMaxLength().toString(16) + ' bytes')
563  }
564  return length | 0
565}
566
567function SlowBuffer (subject, encoding) {
568  if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
569
570  var buf = new Buffer(subject, encoding)
571  delete buf.parent
572  return buf
573}
574
575Buffer.isBuffer = function isBuffer (b) {
576  return !!(b != null && b._isBuffer)
577}
578
579Buffer.compare = function compare (a, b) {
580  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
581    throw new TypeError('Arguments must be Buffers')
582  }
583
584  if (a === b) return 0
585
586  var x = a.length
587  var y = b.length
588
589  var i = 0
590  var len = Math.min(x, y)
591  while (i < len) {
592    if (a[i] !== b[i]) break
593
594    ++i
595  }
596
597  if (i !== len) {
598    x = a[i]
599    y = b[i]
600  }
601
602  if (x < y) return -1
603  if (y < x) return 1
604  return 0
605}
606
607Buffer.isEncoding = function isEncoding (encoding) {
608  switch (String(encoding).toLowerCase()) {
609    case 'hex':
610    case 'utf8':
611    case 'utf-8':
612    case 'ascii':
613    case 'binary':
614    case 'base64':
615    case 'raw':
616    case 'ucs2':
617    case 'ucs-2':
618    case 'utf16le':
619    case 'utf-16le':
620      return true
621    default:
622      return false
623  }
624}
625
626Buffer.concat = function concat (list, length) {
627  if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
628
629  if (list.length === 0) {
630    return new Buffer(0)
631  }
632
633  var i
634  if (length === undefined) {
635    length = 0
636    for (i = 0; i < list.length; i++) {
637      length += list[i].length
638    }
639  }
640
641  var buf = new Buffer(length)
642  var pos = 0
643  for (i = 0; i < list.length; i++) {
644    var item = list[i]
645    item.copy(buf, pos)
646    pos += item.length
647  }
648  return buf
649}
650
651function byteLength (string, encoding) {
652  if (typeof string !== 'string') string = '' + string
653
654  var len = string.length
655  if (len === 0) return 0
656
657  // Use a for loop to avoid recursion
658  var loweredCase = false
659  for (;;) {
660    switch (encoding) {
661      case 'ascii':
662      case 'binary':
663      // Deprecated
664      case 'raw':
665      case 'raws':
666        return len
667      case 'utf8':
668      case 'utf-8':
669        return utf8ToBytes(string).length
670      case 'ucs2':
671      case 'ucs-2':
672      case 'utf16le':
673      case 'utf-16le':
674        return len * 2
675      case 'hex':
676        return len >>> 1
677      case 'base64':
678        return base64ToBytes(string).length
679      default:
680        if (loweredCase) return utf8ToBytes(string).length // assume utf8
681        encoding = ('' + encoding).toLowerCase()
682        loweredCase = true
683    }
684  }
685}
686Buffer.byteLength = byteLength
687
688// pre-set for values that may exist in the future
689Buffer.prototype.length = undefined
690Buffer.prototype.parent = undefined
691
692function slowToString (encoding, start, end) {
693  var loweredCase = false
694
695  start = start | 0
696  end = end === undefined || end === Infinity ? this.length : end | 0
697
698  if (!encoding) encoding = 'utf8'
699  if (start < 0) start = 0
700  if (end > this.length) end = this.length
701  if (end <= start) return ''
702
703  while (true) {
704    switch (encoding) {
705      case 'hex':
706        return hexSlice(this, start, end)
707
708      case 'utf8':
709      case 'utf-8':
710        return utf8Slice(this, start, end)
711
712      case 'ascii':
713        return asciiSlice(this, start, end)
714
715      case 'binary':
716        return binarySlice(this, start, end)
717
718      case 'base64':
719        return base64Slice(this, start, end)
720
721      case 'ucs2':
722      case 'ucs-2':
723      case 'utf16le':
724      case 'utf-16le':
725        return utf16leSlice(this, start, end)
726
727      default:
728        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
729        encoding = (encoding + '').toLowerCase()
730        loweredCase = true
731    }
732  }
733}
734
735Buffer.prototype.toString = function toString () {
736  var length = this.length | 0
737  if (length === 0) return ''
738  if (arguments.length === 0) return utf8Slice(this, 0, length)
739  return slowToString.apply(this, arguments)
740}
741
742Buffer.prototype.equals = function equals (b) {
743  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
744  if (this === b) return true
745  return Buffer.compare(this, b) === 0
746}
747
748Buffer.prototype.inspect = function inspect () {
749  var str = ''
750  var max = exports.INSPECT_MAX_BYTES
751  if (this.length > 0) {
752    str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
753    if (this.length > max) str += ' ... '
754  }
755  return '<Buffer ' + str + '>'
756}
757
758Buffer.prototype.compare = function compare (b) {
759  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
760  if (this === b) return 0
761  return Buffer.compare(this, b)
762}
763
764Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
765  if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
766  else if (byteOffset < -0x80000000) byteOffset = -0x80000000
767  byteOffset >>= 0
768
769  if (this.length === 0) return -1
770  if (byteOffset >= this.length) return -1
771
772  // Negative offsets start from the end of the buffer
773  if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
774
775  if (typeof val === 'string') {
776    if (val.length === 0) return -1 // special case: looking for empty string always fails
777    return String.prototype.indexOf.call(this, val, byteOffset)
778  }
779  if (Buffer.isBuffer(val)) {
780    return arrayIndexOf(this, val, byteOffset)
781  }
782  if (typeof val === 'number') {
783    if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
784      return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
785    }
786    return arrayIndexOf(this, [ val ], byteOffset)
787  }
788
789  function arrayIndexOf (arr, val, byteOffset) {
790    var foundIndex = -1
791    for (var i = 0; byteOffset + i < arr.length; i++) {
792      if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
793        if (foundIndex === -1) foundIndex = i
794        if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
795      } else {
796        foundIndex = -1
797      }
798    }
799    return -1
800  }
801
802  throw new TypeError('val must be string, number or Buffer')
803}
804
805// `get` is deprecated
806Buffer.prototype.get = function get (offset) {
807  console.log('.get() is deprecated. Access using array indexes instead.')
808  return this.readUInt8(offset)
809}
810
811// `set` is deprecated
812Buffer.prototype.set = function set (v, offset) {
813  console.log('.set() is deprecated. Access using array indexes instead.')
814  return this.writeUInt8(v, offset)
815}
816
817function hexWrite (buf, string, offset, length) {
818  offset = Number(offset) || 0
819  var remaining = buf.length - offset
820  if (!length) {
821    length = remaining
822  } else {
823    length = Number(length)
824    if (length > remaining) {
825      length = remaining
826    }
827  }
828
829  // must be an even number of digits
830  var strLen = string.length
831  if (strLen % 2 !== 0) throw new Error('Invalid hex string')
832
833  if (length > strLen / 2) {
834    length = strLen / 2
835  }
836  for (var i = 0; i < length; i++) {
837    var parsed = parseInt(string.substr(i * 2, 2), 16)
838    if (isNaN(parsed)) throw new Error('Invalid hex string')
839    buf[offset + i] = parsed
840  }
841  return i
842}
843
844function utf8Write (buf, string, offset, length) {
845  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
846}
847
848function asciiWrite (buf, string, offset, length) {
849  return blitBuffer(asciiToBytes(string), buf, offset, length)
850}
851
852function binaryWrite (buf, string, offset, length) {
853  return asciiWrite(buf, string, offset, length)
854}
855
856function base64Write (buf, string, offset, length) {
857  return blitBuffer(base64ToBytes(string), buf, offset, length)
858}
859
860function ucs2Write (buf, string, offset, length) {
861  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
862}
863
864Buffer.prototype.write = function write (string, offset, length, encoding) {
865  // Buffer#write(string)
866  if (offset === undefined) {
867    encoding = 'utf8'
868    length = this.length
869    offset = 0
870  // Buffer#write(string, encoding)
871  } else if (length === undefined && typeof offset === 'string') {
872    encoding = offset
873    length = this.length
874    offset = 0
875  // Buffer#write(string, offset[, length][, encoding])
876  } else if (isFinite(offset)) {
877    offset = offset | 0
878    if (isFinite(length)) {
879      length = length | 0
880      if (encoding === undefined) encoding = 'utf8'
881    } else {
882      encoding = length
883      length = undefined
884    }
885  // legacy write(string, encoding, offset, length) - remove in v0.13
886  } else {
887    var swap = encoding
888    encoding = offset
889    offset = length | 0
890    length = swap
891  }
892
893  var remaining = this.length - offset
894  if (length === undefined || length > remaining) length = remaining
895
896  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
897    throw new RangeError('attempt to write outside buffer bounds')
898  }
899
900  if (!encoding) encoding = 'utf8'
901
902  var loweredCase = false
903  for (;;) {
904    switch (encoding) {
905      case 'hex':
906        return hexWrite(this, string, offset, length)
907
908      case 'utf8':
909      case 'utf-8':
910        return utf8Write(this, string, offset, length)
911
912      case 'ascii':
913        return asciiWrite(this, string, offset, length)
914
915      case 'binary':
916        return binaryWrite(this, string, offset, length)
917
918      case 'base64':
919        // Warning: maxLength not taken into account in base64Write
920        return base64Write(this, string, offset, length)
921
922      case 'ucs2':
923      case 'ucs-2':
924      case 'utf16le':
925      case 'utf-16le':
926        return ucs2Write(this, string, offset, length)
927
928      default:
929        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
930        encoding = ('' + encoding).toLowerCase()
931        loweredCase = true
932    }
933  }
934}
935
936Buffer.prototype.toJSON = function toJSON () {
937  return {
938    type: 'Buffer',
939    data: Array.prototype.slice.call(this._arr || this, 0)
940  }
941}
942
943function base64Slice (buf, start, end) {
944  if (start === 0 && end === buf.length) {
945    return base64.fromByteArray(buf)
946  } else {
947    return base64.fromByteArray(buf.slice(start, end))
948  }
949}
950
951function utf8Slice (buf, start, end) {
952  end = Math.min(buf.length, end)
953  var firstByte
954  var secondByte
955  var thirdByte
956  var fourthByte
957  var bytesPerSequence
958  var tempCodePoint
959  var codePoint
960  var res = []
961  var i = start
962
963  for (; i < end; i += bytesPerSequence) {
964    firstByte = buf[i]
965    codePoint = 0xFFFD
966
967    if (firstByte > 0xEF) {
968      bytesPerSequence = 4
969    } else if (firstByte > 0xDF) {
970      bytesPerSequence = 3
971    } else if (firstByte > 0xBF) {
972      bytesPerSequence = 2
973    } else {
974      bytesPerSequence = 1
975    }
976
977    if (i + bytesPerSequence <= end) {
978      switch (bytesPerSequence) {
979        case 1:
980          if (firstByte < 0x80) {
981            codePoint = firstByte
982          }
983          break
984        case 2:
985          secondByte = buf[i + 1]
986          if ((secondByte & 0xC0) === 0x80) {
987            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
988            if (tempCodePoint > 0x7F) {
989              codePoint = tempCodePoint
990            }
991          }
992          break
993        case 3:
994          secondByte = buf[i + 1]
995          thirdByte = buf[i + 2]
996          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
997            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
998            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
999              codePoint = tempCodePoint
1000            }
1001          }
1002          break
1003        case 4:
1004          secondByte = buf[i + 1]
1005          thirdByte = buf[i + 2]
1006          fourthByte = buf[i + 3]
1007          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
1008            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
1009            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
1010              codePoint = tempCodePoint
1011            }
1012          }
1013      }
1014    }
1015
1016    if (codePoint === 0xFFFD) {
1017      // we generated an invalid codePoint so make sure to only advance by 1 byte
1018      bytesPerSequence = 1
1019    } else if (codePoint > 0xFFFF) {
1020      // encode to utf16 (surrogate pair dance)
1021      codePoint -= 0x10000
1022      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
1023      codePoint = 0xDC00 | codePoint & 0x3FF
1024    }
1025
1026    res.push(codePoint)
1027  }
1028
1029  return String.fromCharCode.apply(String, res)
1030}
1031
1032function asciiSlice (buf, start, end) {
1033  var ret = ''
1034  end = Math.min(buf.length, end)
1035
1036  for (var i = start; i < end; i++) {
1037    ret += String.fromCharCode(buf[i] & 0x7F)
1038  }
1039  return ret
1040}
1041
1042function binarySlice (buf, start, end) {
1043  var ret = ''
1044  end = Math.min(buf.length, end)
1045
1046  for (var i = start; i < end; i++) {
1047    ret += String.fromCharCode(buf[i])
1048  }
1049  return ret
1050}
1051
1052function hexSlice (buf, start, end) {
1053  var len = buf.length
1054
1055  if (!start || start < 0) start = 0
1056  if (!end || end < 0 || end > len) end = len
1057
1058  var out = ''
1059  for (var i = start; i < end; i++) {
1060    out += toHex(buf[i])
1061  }
1062  return out
1063}
1064
1065function utf16leSlice (buf, start, end) {
1066  var bytes = buf.slice(start, end)
1067  var res = ''
1068  for (var i = 0; i < bytes.length; i += 2) {
1069    res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
1070  }
1071  return res
1072}
1073
1074Buffer.prototype.slice = function slice (start, end) {
1075  var len = this.length
1076  start = ~~start
1077  end = end === undefined ? len : ~~end
1078
1079  if (start < 0) {
1080    start += len
1081    if (start < 0) start = 0
1082  } else if (start > len) {
1083    start = len
1084  }
1085
1086  if (end < 0) {
1087    end += len
1088    if (end < 0) end = 0
1089  } else if (end > len) {
1090    end = len
1091  }
1092
1093  if (end < start) end = start
1094
1095  var newBuf
1096  if (Buffer.TYPED_ARRAY_SUPPORT) {
1097    newBuf = Buffer._augment(this.subarray(start, end))
1098  } else {
1099    var sliceLen = end - start
1100    newBuf = new Buffer(sliceLen, undefined)
1101    for (var i = 0; i < sliceLen; i++) {
1102      newBuf[i] = this[i + start]
1103    }
1104  }
1105
1106  if (newBuf.length) newBuf.parent = this.parent || this
1107
1108  return newBuf
1109}
1110
1111/*
1112 * Need to make sure that buffer isn't trying to write out of bounds.
1113 */
vendor: 9,683 bytes, lines 1114-1442
1114function checkOffset (offset, ext, length) {
1115  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
1116  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
1117}
1118
1119Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
1120  offset = offset | 0
1121  byteLength = byteLength | 0
1122  if (!noAssert) checkOffset(offset, byteLength, this.length)
1123
1124  var val = this[offset]
1125  var mul = 1
1126  var i = 0
1127  while (++i < byteLength && (mul *= 0x100)) {
1128    val += this[offset + i] * mul
1129  }
1130
1131  return val
1132}
1133
1134Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
1135  offset = offset | 0
1136  byteLength = byteLength | 0
1137  if (!noAssert) {
1138    checkOffset(offset, byteLength, this.length)
1139  }
1140
1141  var val = this[offset + --byteLength]
1142  var mul = 1
1143  while (byteLength > 0 && (mul *= 0x100)) {
1144    val += this[offset + --byteLength] * mul
1145  }
1146
1147  return val
1148}
1149
1150Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
1151  if (!noAssert) checkOffset(offset, 1, this.length)
1152  return this[offset]
1153}
1154
1155Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
1156  if (!noAssert) checkOffset(offset, 2, this.length)
1157  return this[offset] | (this[offset + 1] << 8)
1158}
1159
1160Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
1161  if (!noAssert) checkOffset(offset, 2, this.length)
1162  return (this[offset] << 8) | this[offset + 1]
1163}
1164
1165Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
1166  if (!noAssert) checkOffset(offset, 4, this.length)
1167
1168  return ((this[offset]) |
1169      (this[offset + 1] << 8) |
1170      (this[offset + 2] << 16)) +
1171      (this[offset + 3] * 0x1000000)
1172}
1173
1174Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
1175  if (!noAssert) checkOffset(offset, 4, this.length)
1176
1177  return (this[offset] * 0x1000000) +
1178    ((this[offset + 1] << 16) |
1179    (this[offset + 2] << 8) |
1180    this[offset + 3])
1181}
1182
1183Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
1184  offset = offset | 0
1185  byteLength = byteLength | 0
1186  if (!noAssert) checkOffset(offset, byteLength, this.length)
1187
1188  var val = this[offset]
1189  var mul = 1
1190  var i = 0
1191  while (++i < byteLength && (mul *= 0x100)) {
1192    val += this[offset + i] * mul
1193  }
1194  mul *= 0x80
1195
1196  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1197
1198  return val
1199}
1200
1201Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
1202  offset = offset | 0
1203  byteLength = byteLength | 0
1204  if (!noAssert) checkOffset(offset, byteLength, this.length)
1205
1206  var i = byteLength
1207  var mul = 1
1208  var val = this[offset + --i]
1209  while (i > 0 && (mul *= 0x100)) {
1210    val += this[offset + --i] * mul
1211  }
1212  mul *= 0x80
1213
1214  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
1215
1216  return val
1217}
1218
1219Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
1220  if (!noAssert) checkOffset(offset, 1, this.length)
1221  if (!(this[offset] & 0x80)) return (this[offset])
1222  return ((0xff - this[offset] + 1) * -1)
1223}
1224
1225Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
1226  if (!noAssert) checkOffset(offset, 2, this.length)
1227  var val = this[offset] | (this[offset + 1] << 8)
1228  return (val & 0x8000) ? val | 0xFFFF0000 : val
1229}
1230
1231Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
1232  if (!noAssert) checkOffset(offset, 2, this.length)
1233  var val = this[offset + 1] | (this[offset] << 8)
1234  return (val & 0x8000) ? val | 0xFFFF0000 : val
1235}
1236
1237Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
1238  if (!noAssert) checkOffset(offset, 4, this.length)
1239
1240  return (this[offset]) |
1241    (this[offset + 1] << 8) |
1242    (this[offset + 2] << 16) |
1243    (this[offset + 3] << 24)
1244}
1245
1246Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
1247  if (!noAssert) checkOffset(offset, 4, this.length)
1248
1249  return (this[offset] << 24) |
1250    (this[offset + 1] << 16) |
1251    (this[offset + 2] << 8) |
1252    (this[offset + 3])
1253}
1254
1255Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
1256  if (!noAssert) checkOffset(offset, 4, this.length)
1257  return ieee754.read(this, offset, true, 23, 4)
1258}
1259
1260Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
1261  if (!noAssert) checkOffset(offset, 4, this.length)
1262  return ieee754.read(this, offset, false, 23, 4)
1263}
1264
1265Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
1266  if (!noAssert) checkOffset(offset, 8, this.length)
1267  return ieee754.read(this, offset, true, 52, 8)
1268}
1269
1270Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
1271  if (!noAssert) checkOffset(offset, 8, this.length)
1272  return ieee754.read(this, offset, false, 52, 8)
1273}
1274
1275function checkInt (buf, value, offset, ext, max, min) {
1276  if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
1277  if (value > max || value < min) throw new RangeError('value is out of bounds')
1278  if (offset + ext > buf.length) throw new RangeError('index out of range')
1279}
1280
1281Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
1282  value = +value
1283  offset = offset | 0
1284  byteLength = byteLength | 0
1285  if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
1286
1287  var mul = 1
1288  var i = 0
1289  this[offset] = value & 0xFF
1290  while (++i < byteLength && (mul *= 0x100)) {
1291    this[offset + i] = (value / mul) & 0xFF
1292  }
1293
1294  return offset + byteLength
1295}
1296
1297Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
1298  value = +value
1299  offset = offset | 0
1300  byteLength = byteLength | 0
1301  if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
1302
1303  var i = byteLength - 1
1304  var mul = 1
1305  this[offset + i] = value & 0xFF
1306  while (--i >= 0 && (mul *= 0x100)) {
1307    this[offset + i] = (value / mul) & 0xFF
1308  }
1309
1310  return offset + byteLength
1311}
1312
1313Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
1314  value = +value
1315  offset = offset | 0
1316  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
1317  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1318  this[offset] = value
1319  return offset + 1
1320}
1321
1322function objectWriteUInt16 (buf, value, offset, littleEndian) {
1323  if (value < 0) value = 0xffff + value + 1
1324  for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
1325    buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
1326      (littleEndian ? i : 1 - i) * 8
1327  }
1328}
1329
1330Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
1331  value = +value
1332  offset = offset | 0
1333  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1334  if (Buffer.TYPED_ARRAY_SUPPORT) {
1335    this[offset] = value
1336    this[offset + 1] = (value >>> 8)
1337  } else {
1338    objectWriteUInt16(this, value, offset, true)
1339  }
1340  return offset + 2
1341}
1342
1343Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
1344  value = +value
1345  offset = offset | 0
1346  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
1347  if (Buffer.TYPED_ARRAY_SUPPORT) {
1348    this[offset] = (value >>> 8)
1349    this[offset + 1] = value
1350  } else {
1351    objectWriteUInt16(this, value, offset, false)
1352  }
1353  return offset + 2
1354}
1355
1356function objectWriteUInt32 (buf, value, offset, littleEndian) {
1357  if (value < 0) value = 0xffffffff + value + 1
1358  for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
1359    buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
1360  }
1361}
1362
1363Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
1364  value = +value
1365  offset = offset | 0
1366  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1367  if (Buffer.TYPED_ARRAY_SUPPORT) {
1368    this[offset + 3] = (value >>> 24)
1369    this[offset + 2] = (value >>> 16)
1370    this[offset + 1] = (value >>> 8)
1371    this[offset] = value
1372  } else {
1373    objectWriteUInt32(this, value, offset, true)
1374  }
1375  return offset + 4
1376}
1377
1378Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
1379  value = +value
1380  offset = offset | 0
1381  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
1382  if (Buffer.TYPED_ARRAY_SUPPORT) {
1383    this[offset] = (value >>> 24)
1384    this[offset + 1] = (value >>> 16)
1385    this[offset + 2] = (value >>> 8)
1386    this[offset + 3] = value
1387  } else {
1388    objectWriteUInt32(this, value, offset, false)
1389  }
1390  return offset + 4
1391}
1392
1393Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
1394  value = +value
1395  offset = offset | 0
1396  if (!noAssert) {
1397    var limit = Math.pow(2, 8 * byteLength - 1)
1398
1399    checkInt(this, value, offset, byteLength, limit - 1, -limit)
1400  }
1401
1402  var i = 0
1403  var mul = 1
1404  var sub = value < 0 ? 1 : 0
1405  this[offset] = value & 0xFF
1406  while (++i < byteLength && (mul *= 0x100)) {
1407    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1408  }
1409
1410  return offset + byteLength
1411}
1412
1413Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
1414  value = +value
1415  offset = offset | 0
1416  if (!noAssert) {
1417    var limit = Math.pow(2, 8 * byteLength - 1)
1418
1419    checkInt(this, value, offset, byteLength, limit - 1, -limit)
1420  }
1421
1422  var i = byteLength - 1
1423  var mul = 1
1424  var sub = value < 0 ? 1 : 0
1425  this[offset + i] = value & 0xFF
1426  while (--i >= 0 && (mul *= 0x100)) {
1427    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
1428  }
1429
1430  return offset + byteLength
1431}
1432
1433Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
1434  value = +value
1435  offset = offset | 0
1436  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
1437  if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
1438  if (value < 0) value = 0xff + value + 1
1439  this[offset] = value
1440  return offset + 1
1441}
1442
vendor: 4,097 bytes, lines 1443-1566
1443Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
1444  value = +value
1445  offset = offset | 0
1446  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1447  if (Buffer.TYPED_ARRAY_SUPPORT) {
1448    this[offset] = value
1449    this[offset + 1] = (value >>> 8)
1450  } else {
1451    objectWriteUInt16(this, value, offset, true)
1452  }
1453  return offset + 2
1454}
1455
1456Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
1457  value = +value
1458  offset = offset | 0
1459  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
1460  if (Buffer.TYPED_ARRAY_SUPPORT) {
1461    this[offset] = (value >>> 8)
1462    this[offset + 1] = value
1463  } else {
1464    objectWriteUInt16(this, value, offset, false)
1465  }
1466  return offset + 2
1467}
1468
1469Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
1470  value = +value
1471  offset = offset | 0
1472  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1473  if (Buffer.TYPED_ARRAY_SUPPORT) {
1474    this[offset] = value
1475    this[offset + 1] = (value >>> 8)
1476    this[offset + 2] = (value >>> 16)
1477    this[offset + 3] = (value >>> 24)
1478  } else {
1479    objectWriteUInt32(this, value, offset, true)
1480  }
1481  return offset + 4
1482}
1483
1484Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
1485  value = +value
1486  offset = offset | 0
1487  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
1488  if (value < 0) value = 0xffffffff + value + 1
1489  if (Buffer.TYPED_ARRAY_SUPPORT) {
1490    this[offset] = (value >>> 24)
1491    this[offset + 1] = (value >>> 16)
1492    this[offset + 2] = (value >>> 8)
1493    this[offset + 3] = value
1494  } else {
1495    objectWriteUInt32(this, value, offset, false)
1496  }
1497  return offset + 4
1498}
1499
1500function checkIEEE754 (buf, value, offset, ext, max, min) {
1501  if (value > max || value < min) throw new RangeError('value is out of bounds')
1502  if (offset + ext > buf.length) throw new RangeError('index out of range')
1503  if (offset < 0) throw new RangeError('index out of range')
1504}
1505
1506function writeFloat (buf, value, offset, littleEndian, noAssert) {
1507  if (!noAssert) {
1508    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
1509  }
1510  ieee754.write(buf, value, offset, littleEndian, 23, 4)
1511  return offset + 4
1512}
1513
1514Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
1515  return writeFloat(this, value, offset, true, noAssert)
1516}
1517
1518Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
1519  return writeFloat(this, value, offset, false, noAssert)
1520}
1521
1522function writeDouble (buf, value, offset, littleEndian, noAssert) {
1523  if (!noAssert) {
1524    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
1525  }
1526  ieee754.write(buf, value, offset, littleEndian, 52, 8)
1527  return offset + 8
1528}
1529
1530Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
1531  return writeDouble(this, value, offset, true, noAssert)
1532}
1533
1534Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
1535  return writeDouble(this, value, offset, false, noAssert)
1536}
1537
1538// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
1539Buffer.prototype.copy = function copy (target, targetStart, start, end) {
1540  if (!start) start = 0
1541  if (!end && end !== 0) end = this.length
1542  if (targetStart >= target.length) targetStart = target.length
1543  if (!targetStart) targetStart = 0
1544  if (end > 0 && end < start) end = start
1545
1546  // Copy 0 bytes; we're done
1547  if (end === start) return 0
1548  if (target.length === 0 || this.length === 0) return 0
1549
1550  // Fatal error conditions
1551  if (targetStart < 0) {
1552    throw new RangeError('targetStart out of bounds')
1553  }
1554  if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
1555  if (end < 0) throw new RangeError('sourceEnd out of bounds')
1556
1557  // Are we oob?
1558  if (end > this.length) end = this.length
1559  if (target.length - targetStart < end - start) {
1560    end = target.length - targetStart + start
1561  }
1562
1563  var len = end - start
1564  var i
1565
1566  if (this === target && start < targetStart && targetStart < end) {
1567    // descending copy from end
1568    for (i = len - 1; i >= 0; i--) {
1569      target[i + targetStart] = this[i + start]
1570    }
1571  } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
1572    // ascending copy from start
1573    for (i = 0; i < len; i++) {
1574      target[i + targetStart] = this[i + start]
1575    }
1576  } else {
1577    target._set(this.subarray(start, start + len), targetStart)
1578  }
1579
1580  return len
1581}
1582
1583// fill(value, start=0, end=buffer.length)
1584Buffer.prototype.fill = function fill (value, start, end) {
1585  if (!value) value = 0
1586  if (!start) start = 0
1587  if (!end) end = this.length
1588
1589  if (end < start) throw new RangeError('end < start')
1590
1591  // Fill 0 bytes; we're done
1592  if (end === start) return
1593  if (this.length === 0) return
1594
1595  if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
1596  if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
1597
1598  var i
1599  if (typeof value === 'number') {
1600    for (i = start; i < end; i++) {
1601      this[i] = value
1602    }
1603  } else {
1604    var bytes = utf8ToBytes(value.toString())
1605    var len = bytes.length
1606    for (i = start; i < end; i++) {
1607      this[i] = bytes[i % len]
1608    }
1609  }
1610
1611  return this
1612}
1613
1614/**
1615 * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
1616 * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
1617 */
1618Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
1619  if (typeof Uint8Array !== 'undefined') {
1620    if (Buffer.TYPED_ARRAY_SUPPORT) {
1621      return (new Buffer(this)).buffer
1622    } else {
1623      var buf = new Uint8Array(this.length)
1624      for (var i = 0, len = buf.length; i < len; i += 1) {
1625        buf[i] = this[i]
1626      }
1627      return buf.buffer
1628    }
1629  } else {
1630    throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
1631  }
1632}
1633
1634// HELPER FUNCTIONS
1635// ================
1636
1637var BP = Buffer.prototype
1638
1639/**
1640 * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
1641 */
1642Buffer._augment = function _augment (arr) {
1643  arr.constructor = Buffer
1644  arr._isBuffer = true
1645
1646  // save reference to original Uint8Array set method before overwriting
1647  arr._set = arr.set
1648
1649  // deprecated
1650  arr.get = BP.get
1651  arr.set = BP.set
1652
1653  arr.write = BP.write
1654  arr.toString = BP.toString
1655  arr.toLocaleString = BP.toString
1656  arr.toJSON = BP.toJSON
1657  arr.equals = BP.equals
1658  arr.compare = BP.compare
1659  arr.indexOf = BP.indexOf
1660  arr.copy = BP.copy
1661  arr.slice = BP.slice
1662  arr.readUIntLE = BP.readUIntLE
1663  arr.readUIntBE = BP.readUIntBE
1664  arr.readUInt8 = BP.readUInt8
1665  arr.readUInt16LE = BP.readUInt16LE
1666  arr.readUInt16BE = BP.readUInt16BE
1667  arr.readUInt32LE = BP.readUInt32LE
1668  arr.readUInt32BE = BP.readUInt32BE
1669  arr.readIntLE = BP.readIntLE
1670  arr.readIntBE = BP.readIntBE
1671  arr.readInt8 = BP.readInt8
1672  arr.readInt16LE = BP.readInt16LE
1673  arr.readInt16BE = BP.readInt16BE
1674  arr.readInt32LE = BP.readInt32LE
1675  arr.readInt32BE = BP.readInt32BE
1676  arr.readFloatLE = BP.readFloatLE
1677  arr.readFloatBE = BP.readFloatBE
1678  arr.readDoubleLE = BP.readDoubleLE
1679  arr.readDoubleBE = BP.readDoubleBE
1680  arr.writeUInt8 = BP.writeUInt8
1681  arr.writeUIntLE = BP.writeUIntLE
1682  arr.writeUIntBE = BP.writeUIntBE
1683  arr.writeUInt16LE = BP.writeUInt16LE
1684  arr.writeUInt16BE = BP.writeUInt16BE
1685  arr.writeUInt32LE = BP.writeUInt32LE
1686  arr.writeUInt32BE = BP.writeUInt32BE
1687  arr.writeIntLE = BP.writeIntLE
1688  arr.writeIntBE = BP.writeIntBE
1689  arr.writeInt8 = BP.writeInt8
1690  arr.writeInt16LE = BP.writeInt16LE
1691  arr.writeInt16BE = BP.writeInt16BE
1692  arr.writeInt32LE = BP.writeInt32LE
1693  arr.writeInt32BE = BP.writeInt32BE
1694  arr.writeFloatLE = BP.writeFloatLE
1695  arr.writeFloatBE = BP.writeFloatBE
1696  arr.writeDoubleLE = BP.writeDoubleLE
1697  arr.writeDoubleBE = BP.writeDoubleBE
1698  arr.fill = BP.fill
1699  arr.inspect = BP.inspect
1700  arr.toArrayBuffer = BP.toArrayBuffer
1701
1702  return arr
1703}
1704
1705var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
1706
1707function base64clean (str) {
1708  // Node strips out invalid characters like \n and \t from the string, base64-js does not
1709  str = stringtrim(str).replace(INVALID_BASE64_RE, '')
1710  // Node converts strings with length < 2 to ''
1711  if (str.length < 2) return ''
1712  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
1713  while (str.length % 4 !== 0) {
1714    str = str + '='
1715  }
1716  return str
1717}
1718
1719function stringtrim (str) {
1720  if (str.trim) return str.trim()
1721  return str.replace(/^\s+|\s+$/g, '')
1722}
1723
1724function toHex (n) {
1725  if (n < 16) return '0' + n.toString(16)
1726  return n.toString(16)
1727}
1728
1729function utf8ToBytes (string, units) {
1730  units = units || Infinity
1731  var codePoint
1732  var length = string.length
1733  var leadSurrogate = null
1734  var bytes = []
1735
1736  for (var i = 0; i < length; i++) {
1737    codePoint = string.charCodeAt(i)
1738
1739    // is surrogate component
1740    if (codePoint > 0xD7FF && codePoint < 0xE000) {
1741      // last char was a lead
1742      if (!leadSurrogate) {
1743        // no lead yet
1744        if (codePoint > 0xDBFF) {
1745          // unexpected trail
1746          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1747          continue
1748
1749        } else if (i + 1 === length) {
1750          // unpaired lead
1751          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1752          continue
1753        }
1754
1755        // valid lead
1756        leadSurrogate = codePoint
1757
1758        continue
1759      }
1760
1761      // 2 leads in a row
1762      if (codePoint < 0xDC00) {
1763        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1764        leadSurrogate = codePoint
1765        continue
1766      }
1767
1768      // valid surrogate pair
1769      codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
1770
1771    } else if (leadSurrogate) {
1772      // valid bmp char, but last char was a lead
1773      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
1774    }
1775
1776    leadSurrogate = null
1777
1778    // encode utf8
1779    if (codePoint < 0x80) {
1780      if ((units -= 1) < 0) break
1781      bytes.push(codePoint)
1782    } else if (codePoint < 0x800) {
1783      if ((units -= 2) < 0) break
1784      bytes.push(
1785        codePoint >> 0x6 | 0xC0,
vendor: 22,435 bytes, lines 1786-2589
1786        codePoint & 0x3F | 0x80
1787      )
1788    } else if (codePoint < 0x10000) {
1789      if ((units -= 3) < 0) break
1790      bytes.push(
1791        codePoint >> 0xC | 0xE0,
1792        codePoint >> 0x6 & 0x3F | 0x80,
1793        codePoint & 0x3F | 0x80
1794      )
1795    } else if (codePoint < 0x110000) {
1796      if ((units -= 4) < 0) break
1797      bytes.push(
1798        codePoint >> 0x12 | 0xF0,
1799        codePoint >> 0xC & 0x3F | 0x80,
1800        codePoint >> 0x6 & 0x3F | 0x80,
1801        codePoint & 0x3F | 0x80
1802      )
1803    } else {
1804      throw new Error('Invalid code point')
1805    }
1806  }
1807
1808  return bytes
1809}
1810
1811function asciiToBytes (str) {
1812  var byteArray = []
1813  for (var i = 0; i < str.length; i++) {
1814    // Node's code seems to be doing this and not & 0x7F..
1815    byteArray.push(str.charCodeAt(i) & 0xFF)
1816  }
1817  return byteArray
1818}
1819
1820function utf16leToBytes (str, units) {
1821  var c, hi, lo
1822  var byteArray = []
1823  for (var i = 0; i < str.length; i++) {
1824    if ((units -= 2) < 0) break
1825
1826    c = str.charCodeAt(i)
1827    hi = c >> 8
1828    lo = c % 256
1829    byteArray.push(lo)
1830    byteArray.push(hi)
1831  }
1832
1833  return byteArray
1834}
1835
1836function base64ToBytes (str) {
1837  return base64.toByteArray(base64clean(str))
1838}
1839
1840function blitBuffer (src, dst, offset, length) {
1841  for (var i = 0; i < length; i++) {
1842    if ((i + offset >= dst.length) || (i >= src.length)) break
1843    dst[i + offset] = src[i]
1844  }
1845  return i
1846}
1847
1848},{"base64-js":6,"ieee754":7,"is-array":8}],6:[function(require,module,exports){
1849var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
1850
1851;(function (exports) {
1852	'use strict';
1853
1854  var Arr = (typeof Uint8Array !== 'undefined')
1855    ? Uint8Array
1856    : Array
1857
1858	var PLUS   = '+'.charCodeAt(0)
1859	var SLASH  = '/'.charCodeAt(0)
1860	var NUMBER = '0'.charCodeAt(0)
1861	var LOWER  = 'a'.charCodeAt(0)
1862	var UPPER  = 'A'.charCodeAt(0)
1863	var PLUS_URL_SAFE = '-'.charCodeAt(0)
1864	var SLASH_URL_SAFE = '_'.charCodeAt(0)
1865
1866	function decode (elt) {
1867		var code = elt.charCodeAt(0)
1868		if (code === PLUS ||
1869		    code === PLUS_URL_SAFE)
1870			return 62 // '+'
1871		if (code === SLASH ||
1872		    code === SLASH_URL_SAFE)
1873			return 63 // '/'
1874		if (code < NUMBER)
1875			return -1 //no match
1876		if (code < NUMBER + 10)
1877			return code - NUMBER + 26 + 26
1878		if (code < UPPER + 26)
1879			return code - UPPER
1880		if (code < LOWER + 26)
1881			return code - LOWER + 26
1882	}
1883
1884	function b64ToByteArray (b64) {
1885		var i, j, l, tmp, placeHolders, arr
1886
1887		if (b64.length % 4 > 0) {
1888			throw new Error('Invalid string. Length must be a multiple of 4')
1889		}
1890
1891		// the number of equal signs (place holders)
1892		// if there are two placeholders, than the two characters before it
1893		// represent one byte
1894		// if there is only one, then the three characters before it represent 2 bytes
1895		// this is just a cheap hack to not do indexOf twice
1896		var len = b64.length
1897		placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
1898
1899		// base64 is 4/3 + up to two characters of the original data
1900		arr = new Arr(b64.length * 3 / 4 - placeHolders)
1901
1902		// if there are placeholders, only get up to the last complete 4 chars
1903		l = placeHolders > 0 ? b64.length - 4 : b64.length
1904
1905		var L = 0
1906
1907		function push (v) {
1908			arr[L++] = v
1909		}
1910
1911		for (i = 0, j = 0; i < l; i += 4, j += 3) {
1912			tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
1913			push((tmp & 0xFF0000) >> 16)
1914			push((tmp & 0xFF00) >> 8)
1915			push(tmp & 0xFF)
1916		}
1917
1918		if (placeHolders === 2) {
1919			tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
1920			push(tmp & 0xFF)
1921		} else if (placeHolders === 1) {
1922			tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
1923			push((tmp >> 8) & 0xFF)
1924			push(tmp & 0xFF)
1925		}
1926
1927		return arr
1928	}
1929
1930	function uint8ToBase64 (uint8) {
1931		var i,
1932			extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
1933			output = "",
1934			temp, length
1935
1936		function encode (num) {
1937			return lookup.charAt(num)
1938		}
1939
1940		function tripletToBase64 (num) {
1941			return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
1942		}
1943
1944		// go through the array every three bytes, we'll deal with trailing stuff later
1945		for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
1946			temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
1947			output += tripletToBase64(temp)
1948		}
1949
1950		// pad the end with zeros, but make sure to not forget the extra bytes
1951		switch (extraBytes) {
1952			case 1:
1953				temp = uint8[uint8.length - 1]
1954				output += encode(temp >> 2)
1955				output += encode((temp << 4) & 0x3F)
1956				output += '=='
1957				break
1958			case 2:
1959				temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
1960				output += encode(temp >> 10)
1961				output += encode((temp >> 4) & 0x3F)
1962				output += encode((temp << 2) & 0x3F)
1963				output += '='
1964				break
1965		}
1966
1967		return output
1968	}
1969
1970	exports.toByteArray = b64ToByteArray
1971	exports.fromByteArray = uint8ToBase64
1972}(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
1973
1974},{}],7:[function(require,module,exports){
1975exports.read = function (buffer, offset, isLE, mLen, nBytes) {
1976  var e, m
1977  var eLen = nBytes * 8 - mLen - 1
1978  var eMax = (1 << eLen) - 1
1979  var eBias = eMax >> 1
1980  var nBits = -7
1981  var i = isLE ? (nBytes - 1) : 0
1982  var d = isLE ? -1 : 1
1983  var s = buffer[offset + i]
1984
1985  i += d
1986
1987  e = s & ((1 << (-nBits)) - 1)
1988  s >>= (-nBits)
1989  nBits += eLen
1990  for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
1991
1992  m = e & ((1 << (-nBits)) - 1)
1993  e >>= (-nBits)
1994  nBits += mLen
1995  for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
1996
1997  if (e === 0) {
1998    e = 1 - eBias
1999  } else if (e === eMax) {
2000    return m ? NaN : ((s ? -1 : 1) * Infinity)
2001  } else {
2002    m = m + Math.pow(2, mLen)
2003    e = e - eBias
2004  }
2005  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
2006}
2007
2008exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
2009  var e, m, c
2010  var eLen = nBytes * 8 - mLen - 1
2011  var eMax = (1 << eLen) - 1
2012  var eBias = eMax >> 1
2013  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
2014  var i = isLE ? 0 : (nBytes - 1)
2015  var d = isLE ? 1 : -1
2016  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
2017
2018  value = Math.abs(value)
2019
2020  if (isNaN(value) || value === Infinity) {
2021    m = isNaN(value) ? 1 : 0
2022    e = eMax
2023  } else {
2024    e = Math.floor(Math.log(value) / Math.LN2)
2025    if (value * (c = Math.pow(2, -e)) < 1) {
2026      e--
2027      c *= 2
2028    }
2029    if (e + eBias >= 1) {
2030      value += rt / c
2031    } else {
2032      value += rt * Math.pow(2, 1 - eBias)
2033    }
2034    if (value * c >= 2) {
2035      e++
2036      c /= 2
2037    }
2038
2039    if (e + eBias >= eMax) {
2040      m = 0
2041      e = eMax
2042    } else if (e + eBias >= 1) {
2043      m = (value * c - 1) * Math.pow(2, mLen)
2044      e = e + eBias
2045    } else {
2046      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
2047      e = 0
2048    }
2049  }
2050
2051  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
2052
2053  e = (e << mLen) | m
2054  eLen += mLen
2055  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
2056
2057  buffer[offset + i - d] |= s * 128
2058}
2059
2060},{}],8:[function(require,module,exports){
2061
2062/**
2063 * isArray
2064 */
2065
2066var isArray = Array.isArray;
2067
2068/**
2069 * toString
2070 */
2071
2072var str = Object.prototype.toString;
2073
2074/**
2075 * Whether or not the given `val`
2076 * is an array.
2077 *
2078 * example:
2079 *
2080 *        isArray([]);
2081 *        // > true
2082 *        isArray(arguments);
2083 *        // > false
2084 *        isArray('');
2085 *        // > false
2086 *
2087 * @param {mixed} val
2088 * @return {bool}
2089 */
2090
2091module.exports = isArray || function (val) {
2092  return !! val && '[object Array]' == str.call(val);
2093};
2094
2095},{}],9:[function(require,module,exports){
2096'use strict';
2097// private property
2098var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
2099
2100
2101// public method for encoding
2102exports.encode = function(input, utf8) {
2103    var output = "";
2104    var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
2105    var i = 0;
2106
2107    while (i < input.length) {
2108
2109        chr1 = input.charCodeAt(i++);
2110        chr2 = input.charCodeAt(i++);
2111        chr3 = input.charCodeAt(i++);
2112
2113        enc1 = chr1 >> 2;
2114        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
2115        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
2116        enc4 = chr3 & 63;
2117
2118        if (isNaN(chr2)) {
2119            enc3 = enc4 = 64;
2120        }
2121        else if (isNaN(chr3)) {
2122            enc4 = 64;
2123        }
2124
2125        output = output + _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
2126
2127    }
2128
2129    return output;
2130};
2131
2132// public method for decoding
2133exports.decode = function(input, utf8) {
2134    var output = "";
2135    var chr1, chr2, chr3;
2136    var enc1, enc2, enc3, enc4;
2137    var i = 0;
2138
2139    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
2140
2141    while (i < input.length) {
2142
2143        enc1 = _keyStr.indexOf(input.charAt(i++));
2144        enc2 = _keyStr.indexOf(input.charAt(i++));
2145        enc3 = _keyStr.indexOf(input.charAt(i++));
2146        enc4 = _keyStr.indexOf(input.charAt(i++));
2147
2148        chr1 = (enc1 << 2) | (enc2 >> 4);
2149        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
2150        chr3 = ((enc3 & 3) << 6) | enc4;
2151
2152        output = output + String.fromCharCode(chr1);
2153
2154        if (enc3 != 64) {
2155            output = output + String.fromCharCode(chr2);
2156        }
2157        if (enc4 != 64) {
2158            output = output + String.fromCharCode(chr3);
2159        }
2160
2161    }
2162
2163    return output;
2164
2165};
2166
2167},{}],10:[function(require,module,exports){
2168'use strict';
2169function CompressedObject() {
2170    this.compressedSize = 0;
2171    this.uncompressedSize = 0;
2172    this.crc32 = 0;
2173    this.compressionMethod = null;
2174    this.compressedContent = null;
2175}
2176
2177CompressedObject.prototype = {
2178    /**
2179     * Return the decompressed content in an unspecified format.
2180     * The format will depend on the decompressor.
2181     * @return {Object} the decompressed content.
2182     */
2183    getContent: function() {
2184        return null; // see implementation
2185    },
2186    /**
2187     * Return the compressed content in an unspecified format.
2188     * The format will depend on the compressed conten source.
2189     * @return {Object} the compressed content.
2190     */
2191    getCompressedContent: function() {
2192        return null; // see implementation
2193    }
2194};
2195module.exports = CompressedObject;
2196
2197},{}],11:[function(require,module,exports){
2198'use strict';
2199exports.STORE = {
2200    magic: "\x00\x00",
2201    compress: function(content, compressionOptions) {
2202        return content; // no compression
2203    },
2204    uncompress: function(content) {
2205        return content; // no compression
2206    },
2207    compressInputType: null,
2208    uncompressInputType: null
2209};
2210exports.DEFLATE = require('./flate');
2211
2212},{"./flate":16}],12:[function(require,module,exports){
2213'use strict';
2214
2215var utils = require('./utils');
2216
2217var table = [
2218    0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA,
2219    0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3,
2220    0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988,
2221    0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91,
2222    0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
2223    0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7,
2224    0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC,
2225    0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5,
2226    0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172,
2227    0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
2228    0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940,
2229    0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59,
2230    0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116,
2231    0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F,
2232    0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
2233    0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D,
2234    0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A,
2235    0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433,
2236    0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818,
2237    0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
2238    0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E,
2239    0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457,
2240    0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C,
2241    0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65,
2242    0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
2243    0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB,
2244    0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0,
2245    0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9,
2246    0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086,
2247    0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
2248    0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4,
2249    0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD,
2250    0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A,
2251    0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683,
2252    0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
2253    0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1,
2254    0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE,
2255    0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7,
2256    0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC,
2257    0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
2258    0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252,
2259    0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B,
2260    0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60,
2261    0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79,
2262    0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
2263    0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F,
2264    0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04,
2265    0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D,
2266    0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A,
2267    0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
2268    0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38,
2269    0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21,
2270    0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E,
2271    0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777,
2272    0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
2273    0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45,
2274    0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2,
2275    0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB,
2276    0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0,
2277    0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
2278    0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6,
2279    0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF,
2280    0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94,
2281    0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D
2282];
2283
2284/**
2285 *
2286 *  Javascript crc32
2287 *  http://www.webtoolkit.info/
2288 *
2289 */
2290module.exports = function crc32(input, crc) {
2291    if (typeof input === "undefined" || !input.length) {
2292        return 0;
2293    }
2294
2295    var isArray = utils.getTypeOf(input) !== "string";
2296
2297    if (typeof(crc) == "undefined") {
2298        crc = 0;
2299    }
2300    var x = 0;
2301    var y = 0;
2302    var b = 0;
2303
2304    crc = crc ^ (-1);
2305    for (var i = 0, iTop = input.length; i < iTop; i++) {
2306        b = isArray ? input[i] : input.charCodeAt(i);
2307        y = (crc ^ b) & 0xFF;
2308        x = table[y];
2309        crc = (crc >>> 8) ^ x;
2310    }
2311
2312    return crc ^ (-1);
2313};
2314// vim: set shiftwidth=4 softtabstop=4:
2315
2316},{"./utils":29}],13:[function(require,module,exports){
2317'use strict';
2318var utils = require('./utils');
2319
2320function DataReader(data) {
2321    this.data = null; // type : see implementation
2322    this.length = 0;
2323    this.index = 0;
2324}
2325DataReader.prototype = {
2326    /**
2327     * Check that the offset will not go too far.
2328     * @param {string} offset the additional offset to check.
2329     * @throws {Error} an Error if the offset is out of bounds.
2330     */
2331    checkOffset: function(offset) {
2332        this.checkIndex(this.index + offset);
2333    },
2334    /**
2335     * Check that the specifed index will not be too far.
2336     * @param {string} newIndex the index to check.
2337     * @throws {Error} an Error if the index is out of bounds.
2338     */
2339    checkIndex: function(newIndex) {
2340        if (this.length < newIndex || newIndex < 0) {
2341            throw new Error("End of data reached (data length = " + this.length + ", asked index = " + (newIndex) + "). Corrupted zip ?");
2342        }
2343    },
2344    /**
2345     * Change the index.
2346     * @param {number} newIndex The new index.
2347     * @throws {Error} if the new index is out of the data.
2348     */
2349    setIndex: function(newIndex) {
2350        this.checkIndex(newIndex);
2351        this.index = newIndex;
2352    },
2353    /**
2354     * Skip the next n bytes.
2355     * @param {number} n the number of bytes to skip.
2356     * @throws {Error} if the new index is out of the data.
2357     */
2358    skip: function(n) {
2359        this.setIndex(this.index + n);
2360    },
2361    /**
2362     * Get the byte at the specified index.
2363     * @param {number} i the index to use.
2364     * @return {number} a byte.
2365     */
2366    byteAt: function(i) {
2367        // see implementations
2368    },
2369    /**
2370     * Get the next number with a given byte size.
2371     * @param {number} size the number of bytes to read.
2372     * @return {number} the corresponding number.
2373     */
2374    readInt: function(size) {
2375        var result = 0,
2376            i;
2377        this.checkOffset(size);
2378        for (i = this.index + size - 1; i >= this.index; i--) {
2379            result = (result << 8) + this.byteAt(i);
2380        }
2381        this.index += size;
2382        return result;
2383    },
2384    /**
2385     * Get the next string with a given byte size.
2386     * @param {number} size the number of bytes to read.
2387     * @return {string} the corresponding string.
2388     */
2389    readString: function(size) {
2390        return utils.transformTo("string", this.readData(size));
2391    },
2392    /**
2393     * Get raw data without conversion, <size> bytes.
2394     * @param {number} size the number of bytes to read.
2395     * @return {Object} the raw data, implementation specific.
2396     */
2397    readData: function(size) {
2398        // see implementations
2399    },
2400    /**
2401     * Find the last occurence of a zip signature (4 bytes).
2402     * @param {string} sig the signature to find.
2403     * @return {number} the index of the last occurence, -1 if not found.
2404     */
2405    lastIndexOfSignature: function(sig) {
2406        // see implementations
2407    },
2408    /**
2409     * Get the next date.
2410     * @return {Date} the date.
2411     */
2412    readDate: function() {
2413        var dostime = this.readInt(4);
2414        return new Date(
2415        ((dostime >> 25) & 0x7f) + 1980, // year
2416        ((dostime >> 21) & 0x0f) - 1, // month
2417        (dostime >> 16) & 0x1f, // day
2418        (dostime >> 11) & 0x1f, // hour
2419        (dostime >> 5) & 0x3f, // minute
2420        (dostime & 0x1f) << 1); // second
2421    }
2422};
2423module.exports = DataReader;
2424
2425},{"./utils":29}],14:[function(require,module,exports){
2426'use strict';
2427exports.base64 = false;
2428exports.binary = false;
2429exports.dir = false;
2430exports.createFolders = false;
2431exports.date = null;
2432exports.compression = null;
2433exports.compressionOptions = null;
2434exports.comment = null;
2435exports.unixPermissions = null;
2436exports.dosPermissions = null;
2437
2438},{}],15:[function(require,module,exports){
2439'use strict';
2440var utils = require('./utils');
2441
2442/**
2443 * @deprecated
2444 * This function will be removed in a future version without replacement.
2445 */
2446exports.string2binary = function(str) {
2447    return utils.string2binary(str);
2448};
2449
2450/**
2451 * @deprecated
2452 * This function will be removed in a future version without replacement.
2453 */
2454exports.string2Uint8Array = function(str) {
2455    return utils.transformTo("uint8array", str);
2456};
2457
2458/**
2459 * @deprecated
2460 * This function will be removed in a future version without replacement.
2461 */
2462exports.uint8Array2String = function(array) {
2463    return utils.transformTo("string", array);
2464};
2465
2466/**
2467 * @deprecated
2468 * This function will be removed in a future version without replacement.
2469 */
2470exports.string2Blob = function(str) {
2471    var buffer = utils.transformTo("arraybuffer", str);
2472    return utils.arrayBuffer2Blob(buffer);
2473};
2474
2475/**
2476 * @deprecated
2477 * This function will be removed in a future version without replacement.
2478 */
2479exports.arrayBuffer2Blob = function(buffer) {
2480    return utils.arrayBuffer2Blob(buffer);
2481};
2482
2483/**
2484 * @deprecated
2485 * This function will be removed in a future version without replacement.
2486 */
2487exports.transformTo = function(outputType, input) {
2488    return utils.transformTo(outputType, input);
2489};
2490
2491/**
2492 * @deprecated
2493 * This function will be removed in a future version without replacement.
2494 */
2495exports.getTypeOf = function(input) {
2496    return utils.getTypeOf(input);
2497};
2498
2499/**
2500 * @deprecated
2501 * This function will be removed in a future version without replacement.
2502 */
2503exports.checkSupport = function(type) {
2504    return utils.checkSupport(type);
2505};
2506
2507/**
2508 * @deprecated
2509 * This value will be removed in a future version without replacement.
2510 */
2511exports.MAX_VALUE_16BITS = utils.MAX_VALUE_16BITS;
2512
2513/**
2514 * @deprecated
2515 * This value will be removed in a future version without replacement.
2516 */
2517exports.MAX_VALUE_32BITS = utils.MAX_VALUE_32BITS;
2518
2519
2520/**
2521 * @deprecated
2522 * This function will be removed in a future version without replacement.
2523 */
2524exports.pretty = function(str) {
2525    return utils.pretty(str);
2526};
2527
2528/**
2529 * @deprecated
2530 * This function will be removed in a future version without replacement.
2531 */
2532exports.findCompression = function(compressionMethod) {
2533    return utils.findCompression(compressionMethod);
2534};
2535
2536/**
2537 * @deprecated
2538 * This function will be removed in a future version without replacement.
2539 */
2540exports.isRegExp = function (object) {
2541    return utils.isRegExp(object);
2542};
2543
2544
2545},{"./utils":29}],16:[function(require,module,exports){
2546'use strict';
2547var USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');
2548
2549var pako = require("pako");
2550exports.uncompressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
2551exports.compressInputType = USE_TYPEDARRAY ? "uint8array" : "array";
2552
2553exports.magic = "\x08\x00";
2554exports.compress = function(input, compressionOptions) {
2555    return pako.deflateRaw(input, {
2556        level : compressionOptions.level || -1 // default compression
2557    });
2558};
2559exports.uncompress =  function(input) {
2560    return pako.inflateRaw(input);
2561};
2562
2563},{"pako":32}],17:[function(require,module,exports){
2564'use strict';
2565
2566var base64 = require('./base64');
2567
2568/**
2569Usage:
2570   zip = new JSZip();
2571   zip.file("hello.txt", "Hello, World!").file("tempfile", "nothing");
2572   zip.folder("images").file("smile.gif", base64Data, {base64: true});
2573   zip.file("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
2574   zip.remove("tempfile");
2575
2576   base64zip = zip.generate();
2577
2578**/
2579
2580/**
2581 * Representation a of zip file in js
2582 * @constructor
2583 * @param {String=|ArrayBuffer=|Uint8Array=} data the data to load, if any (optional).
2584 * @param {Object=} options the options for creating this objects (optional).
2585 */
2586function JSZip(data, options) {
2587    // if this constructor is used without `new`, it adds `new` before itself:
2588    if(!(this instanceof JSZip)) return new JSZip(data, options);
2589
vendor: 3,804 bytes, lines 2590-2723
2590    // object containing the files :
2591    // {
2592    //   "folder/" : {...},
2593    //   "folder/data.txt" : {...}
2594    // }
2595    this.files = {};
2596
2597    this.comment = null;
2598
2599    // Where we are in the hierarchy
2600    this.root = "";
2601    if (data) {
2602        this.load(data, options);
2603    }
2604    this.clone = function() {
2605        var newObj = new JSZip();
2606        for (var i in this) {
2607            if (typeof this[i] !== "function") {
2608                newObj[i] = this[i];
2609            }
2610        }
2611        return newObj;
2612    };
2613}
2614JSZip.prototype = require('./object');
2615JSZip.prototype.load = require('./load');
2616JSZip.support = require('./support');
2617JSZip.defaults = require('./defaults');
2618
2619/**
2620 * @deprecated
2621 * This namespace will be removed in a future version without replacement.
2622 */
2623JSZip.utils = require('./deprecatedPublicUtils');
2624
2625JSZip.base64 = {
2626    /**
2627     * @deprecated
2628     * This method will be removed in a future version without replacement.
2629     */
2630    encode : function(input) {
2631        return base64.encode(input);
2632    },
2633    /**
2634     * @deprecated
2635     * This method will be removed in a future version without replacement.
2636     */
2637    decode : function(input) {
2638        return base64.decode(input);
2639    }
2640};
2641JSZip.compressions = require('./compressions');
2642module.exports = JSZip;
2643
2644},{"./base64":9,"./compressions":11,"./defaults":14,"./deprecatedPublicUtils":15,"./load":18,"./object":21,"./support":25}],18:[function(require,module,exports){
2645'use strict';
2646var base64 = require('./base64');
2647var ZipEntries = require('./zipEntries');
2648module.exports = function(data, options) {
2649    var files, zipEntries, i, input;
2650    options = options || {};
2651    if (options.base64) {
2652        data = base64.decode(data);
2653    }
2654
2655    zipEntries = new ZipEntries(data, options);
2656    files = zipEntries.files;
2657    for (i = 0; i < files.length; i++) {
2658        input = files[i];
2659        this.file(input.fileName, input.decompressed, {
2660            binary: true,
2661            optimizedBinaryString: true,
2662            date: input.date,
2663            dir: input.dir,
2664            comment : input.fileComment.length ? input.fileComment : null,
2665            unixPermissions : input.unixPermissions,
2666            dosPermissions : input.dosPermissions,
2667            createFolders: options.createFolders
2668        });
2669    }
2670    if (zipEntries.zipComment.length) {
2671        this.comment = zipEntries.zipComment;
2672    }
2673
2674    return this;
2675};
2676
2677},{"./base64":9,"./zipEntries":30}],19:[function(require,module,exports){
2678(function (Buffer){
2679'use strict';
2680module.exports = function(data, encoding){
2681    return new Buffer(data, encoding);
2682};
2683module.exports.test = function(b){
2684    return Buffer.isBuffer(b);
2685};
2686
2687}).call(this,require("buffer").Buffer)
2688},{"buffer":5}],20:[function(require,module,exports){
2689'use strict';
2690var Uint8ArrayReader = require('./uint8ArrayReader');
2691
2692function NodeBufferReader(data) {
2693    this.data = data;
2694    this.length = this.data.length;
2695    this.index = 0;
2696}
2697NodeBufferReader.prototype = new Uint8ArrayReader();
2698
2699/**
2700 * @see DataReader.readData
2701 */
2702NodeBufferReader.prototype.readData = function(size) {
2703    this.checkOffset(size);
2704    var result = this.data.slice(this.index, this.index + size);
2705    this.index += size;
2706    return result;
2707};
2708module.exports = NodeBufferReader;
2709
2710},{"./uint8ArrayReader":26}],21:[function(require,module,exports){
2711'use strict';
2712var support = require('./support');
2713var utils = require('./utils');
2714var crc32 = require('./crc32');
2715var signature = require('./signature');
2716var defaults = require('./defaults');
2717var base64 = require('./base64');
2718var compressions = require('./compressions');
2719var CompressedObject = require('./compressedObject');
2720var nodeBuffer = require('./nodeBuffer');
2721var utf8 = require('./utf8');
2722var StringWriter = require('./stringWriter');
2723var Uint8ArrayWriter = require
vendor: 5,085 bytes, lines 2723-2887
2723('./uint8ArrayWriter');
2724
2725/**
2726 * Returns the raw data of a ZipObject, decompress the content if necessary.
2727 * @param {ZipObject} file the file to use.
2728 * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
2729 */
2730var getRawData = function(file) {
2731    if (file._data instanceof CompressedObject) {
2732        file._data = file._data.getContent();
2733        file.options.binary = true;
2734        file.options.base64 = false;
2735
2736        if (utils.getTypeOf(file._data) === "uint8array") {
2737            var copy = file._data;
2738            // when reading an arraybuffer, the CompressedObject mechanism will keep it and subarray() a Uint8Array.
2739            // if we request a file in the same format, we might get the same Uint8Array or its ArrayBuffer (the original zip file).
2740            file._data = new Uint8Array(copy.length);
2741            // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
2742            if (copy.length !== 0) {
2743                file._data.set(copy, 0);
2744            }
2745        }
2746    }
2747    return file._data;
2748};
2749
2750/**
2751 * Returns the data of a ZipObject in a binary form. If the content is an unicode string, encode it.
2752 * @param {ZipObject} file the file to use.
2753 * @return {String|ArrayBuffer|Uint8Array|Buffer} the data.
2754 */
2755var getBinaryData = function(file) {
2756    var result = getRawData(file),
2757        type = utils.getTypeOf(result);
2758    if (type === "string") {
2759        if (!file.options.binary) {
2760            // unicode text !
2761            // unicode string => binary string is a painful process, check if we can avoid it.
2762            if (support.nodebuffer) {
2763                return nodeBuffer(result, "utf-8");
2764            }
2765        }
2766        return file.asBinary();
2767    }
2768    return result;
2769};
2770
2771/**
2772 * Transform this._data into a string.
2773 * @param {function} filter a function String -> String, applied if not null on the result.
2774 * @return {String} the string representing this._data.
2775 */
2776var dataToString = function(asUTF8) {
2777    var result = getRawData(this);
2778    if (result === null || typeof result === "undefined") {
2779        return "";
2780    }
2781    // if the data is a base64 string, we decode it before checking the encoding !
2782    if (this.options.base64) {
2783        result = base64.decode(result);
2784    }
2785    if (asUTF8 && this.options.binary) {
2786        // JSZip.prototype.utf8decode supports arrays as input
2787        // skip to array => string step, utf8decode will do it.
2788        result = out.utf8decode(result);
2789    }
2790    else {
2791        // no utf8 transformation, do the array => string step.
2792        result = utils.transformTo("string", result);
2793    }
2794
2795    if (!asUTF8 && !this.options.binary) {
2796        result = utils.transformTo("string", out.utf8encode(result));
2797    }
2798    return result;
2799};
2800/**
2801 * A simple object representing a file in the zip file.
2802 * @constructor
2803 * @param {string} name the name of the file
2804 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data
2805 * @param {Object} options the options of the file
2806 */
2807var ZipObject = function(name, data, options) {
2808    this.name = name;
2809    this.dir = options.dir;
2810    this.date = options.date;
2811    this.comment = options.comment;
2812    this.unixPermissions = options.unixPermissions;
2813    this.dosPermissions = options.dosPermissions;
2814
2815    this._data = data;
2816    this.options = options;
2817
2818    /*
2819     * This object contains initial values for dir and date.
2820     * With them, we can check if the user changed the deprecated metadata in
2821     * `ZipObject#options` or not.
2822     */
2823    this._initialMetadata = {
2824      dir : options.dir,
2825      date : options.date
2826    };
2827};
2828
2829ZipObject.prototype = {
2830    /**
2831     * Return the content as UTF8 string.
2832     * @return {string} the UTF8 string.
2833     */
2834    asText: function() {
2835        return dataToString.call(this, true);
2836    },
2837    /**
2838     * Returns the binary content.
2839     * @return {string} the content as binary.
2840     */
2841    asBinary: function() {
2842        return dataToString.call(this, false);
2843    },
2844    /**
2845     * Returns the content as a nodejs Buffer.
2846     * @return {Buffer} the content as a Buffer.
2847     */
2848    asNodeBuffer: function() {
2849        var result = getBinaryData(this);
2850        return utils.transformTo("nodebuffer", result);
2851    },
2852    /**
2853     * Returns the content as an Uint8Array.
2854     * @return {Uint8Array} the content as an Uint8Array.
2855     */
2856    asUint8Array: function() {
2857        var result = getBinaryData(this);
2858        return utils.transformTo("uint8array", result);
2859    },
2860    /**
2861     * Returns the content as an ArrayBuffer.
2862     * @return {ArrayBuffer} the content as an ArrayBufer.
2863     */
2864    asArrayBuffer: function() {
2865        return this.asUint8Array().buffer;
2866    }
2867};
2868
2869/**
2870 * Transform an integer into a string in hexadecimal.
2871 * @private
2872 * @param {number} dec the number to convert.
2873 * @param {number} bytes the number of bytes to generate.
2874 * @returns {string} the result.
2875 */
2876var decToHex = function(dec, bytes) {
2877    var hex = "",
2878        i;
2879    for (i = 0; i < bytes; i++) {
2880        hex += String.fromCharCode(dec & 0xff);
2881        dec = dec >>> 8;
2882    }
2883    return hex;
2884};
2885
2886/**
2887 * 
vendor: 24,121 bytes, lines 2887-3595
2887Merge the objects passed as parameters into a new one.
2888 * @private
2889 * @param {...Object} var_args All objects to merge.
2890 * @return {Object} a new object with the data of the others.
2891 */
2892var extend = function() {
2893    var result = {}, i, attr;
2894    for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers
2895        for (attr in arguments[i]) {
2896            if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === "undefined") {
2897                result[attr] = arguments[i][attr];
2898            }
2899        }
2900    }
2901    return result;
2902};
2903
2904/**
2905 * Transforms the (incomplete) options from the user into the complete
2906 * set of options to create a file.
2907 * @private
2908 * @param {Object} o the options from the user.
2909 * @return {Object} the complete set of options.
2910 */
2911var prepareFileAttrs = function(o) {
2912    o = o || {};
2913    if (o.base64 === true && (o.binary === null || o.binary === undefined)) {
2914        o.binary = true;
2915    }
2916    o = extend(o, defaults);
2917    o.date = o.date || new Date();
2918    if (o.compression !== null) o.compression = o.compression.toUpperCase();
2919
2920    return o;
2921};
2922
2923/**
2924 * Add a file in the current folder.
2925 * @private
2926 * @param {string} name the name of the file
2927 * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file
2928 * @param {Object} o the options of the file
2929 * @return {Object} the new file.
2930 */
2931var fileAdd = function(name, data, o) {
2932    // be sure sub folders exist
2933    var dataType = utils.getTypeOf(data),
2934        parent;
2935
2936    o = prepareFileAttrs(o);
2937
2938    if (typeof o.unixPermissions === "string") {
2939        o.unixPermissions = parseInt(o.unixPermissions, 8);
2940    }
2941
2942    // UNX_IFDIR  0040000 see zipinfo.c
2943    if (o.unixPermissions && (o.unixPermissions & 0x4000)) {
2944        o.dir = true;
2945    }
2946    // Bit 4    Directory
2947    if (o.dosPermissions && (o.dosPermissions & 0x0010)) {
2948        o.dir = true;
2949    }
2950
2951    if (o.dir) {
2952        name = forceTrailingSlash(name);
2953    }
2954
2955    if (o.createFolders && (parent = parentFolder(name))) {
2956        folderAdd.call(this, parent, true);
2957    }
2958
2959    if (o.dir || data === null || typeof data === "undefined") {
2960        o.base64 = false;
2961        o.binary = false;
2962        data = null;
2963        dataType = null;
2964    }
2965    else if (dataType === "string") {
2966        if (o.binary && !o.base64) {
2967            // optimizedBinaryString == true means that the file has already been filtered with a 0xFF mask
2968            if (o.optimizedBinaryString !== true) {
2969                // this is a string, not in a base64 format.
2970                // Be sure that this is a correct "binary string"
2971                data = utils.string2binary(data);
2972            }
2973        }
2974    }
2975    else { // arraybuffer, uint8array, ...
2976        o.base64 = false;
2977        o.binary = true;
2978
2979        if (!dataType && !(data instanceof CompressedObject)) {
2980            throw new Error("The data of '" + name + "' is in an unsupported format !");
2981        }
2982
2983        // special case : it's way easier to work with Uint8Array than with ArrayBuffer
2984        if (dataType === "arraybuffer") {
2985            data = utils.transformTo("uint8array", data);
2986        }
2987    }
2988
2989    var object = new ZipObject(name, data, o);
2990    this.files[name] = object;
2991    return object;
2992};
2993
2994/**
2995 * Find the parent folder of the path.
2996 * @private
2997 * @param {string} path the path to use
2998 * @return {string} the parent folder, or ""
2999 */
3000var parentFolder = function (path) {
3001    if (path.slice(-1) == '/') {
3002        path = path.substring(0, path.length - 1);
3003    }
3004    var lastSlash = path.lastIndexOf('/');
3005    return (lastSlash > 0) ? path.substring(0, lastSlash) : "";
3006};
3007
3008
3009/**
3010 * Returns the path with a slash at the end.
3011 * @private
3012 * @param {String} path the path to check.
3013 * @return {String} the path with a trailing slash.
3014 */
3015var forceTrailingSlash = function(path) {
3016    // Check the name ends with a /
3017    if (path.slice(-1) != "/") {
3018        path += "/"; // IE doesn't like substr(-1)
3019    }
3020    return path;
3021};
3022/**
3023 * Add a (sub) folder in the current folder.
3024 * @private
3025 * @param {string} name the folder's name
3026 * @param {boolean=} [createFolders] If true, automatically create sub
3027 *  folders. Defaults to false.
3028 * @return {Object} the new folder.
3029 */
3030var folderAdd = function(name, createFolders) {
3031    createFolders = (typeof createFolders !== 'undefined') ? createFolders : false;
3032
3033    name = forceTrailingSlash(name);
3034
3035    // Does this folder already exist?
3036    if (!this.files[name]) {
3037        fileAdd.call(this, name, null, {
3038            dir: true,
3039            createFolders: createFolders
3040        });
3041    }
3042    return this.files[name];
3043};
3044
3045/**
3046 * Generate a JSZip.CompressedObject for a given zipOject.
3047 * @param {ZipObject} file the object to read.
3048 * @param {JSZip.compression} compression the compression to use.
3049 * @param {Object} compressionOptions the options to use when compressing.
3050 * @return {JSZip.CompressedObject} the compressed result.
3051 */
3052var generateCompressedObjectFrom = function(file, compression, compressionOptions) {
3053    var result = new CompressedObject(),
3054        content;
3055
3056    // the data has not been decompressed, we might reuse things !
3057    if (file._data instanceof CompressedObject) {
3058        result.uncompressedSize = file._data.uncompressedSize;
3059        result.crc32 = file._data.crc32;
3060
3061        if (result.uncompressedSize === 0 || file.dir) {
3062            compression = compressions['STORE'];
3063            result.compressedContent = "";
3064            result.crc32 = 0;
3065        }
3066        else if (file._data.compressionMethod === compression.magic) {
3067            result.compressedContent = file._data.getCompressedContent();
3068        }
3069        else {
3070            content = file._data.getContent();
3071            // need to decompress / recompress
3072            result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
3073        }
3074    }
3075    else {
3076        // have uncompressed data
3077        content = getBinaryData(file);
3078        if (!content || content.length === 0 || file.dir) {
3079            compression = compressions['STORE'];
3080            content = "";
3081        }
3082        result.uncompressedSize = content.length;
3083        result.crc32 = crc32(content);
3084        result.compressedContent = compression.compress(utils.transformTo(compression.compressInputType, content), compressionOptions);
3085    }
3086
3087    result.compressedSize = result.compressedContent.length;
3088    result.compressionMethod = compression.magic;
3089
3090    return result;
3091};
3092
3093
3094
3095
3096/**
3097 * Generate the UNIX part of the external file attributes.
3098 * @param {Object} unixPermissions the unix permissions or null.
3099 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
3100 * @return {Number} a 32 bit integer.
3101 *
3102 * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :
3103 *
3104 * TTTTsstrwxrwxrwx0000000000ADVSHR
3105 * ^^^^____________________________ file type, see zipinfo.c (UNX_*)
3106 *     ^^^_________________________ setuid, setgid, sticky
3107 *        ^^^^^^^^^________________ permissions
3108 *                 ^^^^^^^^^^______ not used ?
3109 *                           ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only
3110 */
3111var generateUnixExternalFileAttr = function (unixPermissions, isDir) {
3112
3113    var result = unixPermissions;
3114    if (!unixPermissions) {
3115        // I can't use octal values in strict mode, hence the hexa.
3116        //  040775 => 0x41fd
3117        // 0100664 => 0x81b4
3118        result = isDir ? 0x41fd : 0x81b4;
3119    }
3120
3121    return (result & 0xFFFF) << 16;
3122};
3123
3124/**
3125 * Generate the DOS part of the external file attributes.
3126 * @param {Object} dosPermissions the dos permissions or null.
3127 * @param {Boolean} isDir true if the entry is a directory, false otherwise.
3128 * @return {Number} a 32 bit integer.
3129 *
3130 * Bit 0     Read-Only
3131 * Bit 1     Hidden
3132 * Bit 2     System
3133 * Bit 3     Volume Label
3134 * Bit 4     Directory
3135 * Bit 5     Archive
3136 */
3137var generateDosExternalFileAttr = function (dosPermissions, isDir) {
3138
3139    // the dir flag is already set for compatibility
3140
3141    return (dosPermissions || 0)  & 0x3F;
3142};
3143
3144/**
3145 * Generate the various parts used in the construction of the final zip file.
3146 * @param {string} name the file name.
3147 * @param {ZipObject} file the file content.
3148 * @param {JSZip.CompressedObject} compressedObject the compressed object.
3149 * @param {number} offset the current offset from the start of the zip file.
3150 * @param {String} platform let's pretend we are this platform (change platform dependents fields)
3151 * @return {object} the zip parts.
3152 */
3153var generateZipParts = function(name, file, compressedObject, offset, platform) {
3154    var data = compressedObject.compressedContent,
3155        utfEncodedFileName = utils.transformTo("string", utf8.utf8encode(file.name)),
3156        comment = file.comment || "",
3157        utfEncodedComment = utils.transformTo("string", utf8.utf8encode(comment)),
3158        useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,
3159        useUTF8ForComment = utfEncodedComment.length !== comment.length,
3160        o = file.options,
3161        dosTime,
3162        dosDate,
3163        extraFields = "",
3164        unicodePathExtraField = "",
3165        unicodeCommentExtraField = "",
3166        dir, date;
3167
3168
3169    // handle the deprecated options.dir
3170    if (file._initialMetadata.dir !== file.dir) {
3171        dir = file.dir;
3172    } else {
3173        dir = o.dir;
3174    }
3175
3176    // handle the deprecated options.date
3177    if(file._initialMetadata.date !== file.date) {
3178        date = file.date;
3179    } else {
3180        date = o.date;
3181    }
3182
3183    var extFileAttr = 0;
3184    var versionMadeBy = 0;
3185    if (dir) {
3186        // dos or unix, we set the dos dir flag
3187        extFileAttr |= 0x00010;
3188    }
3189    if(platform === "UNIX") {
3190        versionMadeBy = 0x031E; // UNIX, version 3.0
3191        extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);
3192    } else { // DOS or other, fallback to DOS
3193        versionMadeBy = 0x0014; // DOS, version 2.0
3194        extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);
3195    }
3196
3197    // date
3198    // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
3199    // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
3200    // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
3201
3202    dosTime = date.getHours();
3203    dosTime = dosTime << 6;
3204    dosTime = dosTime | date.getMinutes();
3205    dosTime = dosTime << 5;
3206    dosTime = dosTime | date.getSeconds() / 2;
3207
3208    dosDate = date.getFullYear() - 1980;
3209    dosDate = dosDate << 4;
3210    dosDate = dosDate | (date.getMonth() + 1);
3211    dosDate = dosDate << 5;
3212    dosDate = dosDate | date.getDate();
3213
3214    if (useUTF8ForFileName) {
3215        // set the unicode path extra field. unzip needs at least one extra
3216        // field to correctly handle unicode path, so using the path is as good
3217        // as any other information. This could improve the situation with
3218        // other archive managers too.
3219        // This field is usually used without the utf8 flag, with a non
3220        // unicode path in the header (winrar, winzip). This helps (a bit)
3221        // with the messy Windows' default compressed folders feature but
3222        // breaks on p7zip which doesn't seek the unicode path extra field.
3223        // So for now, UTF-8 everywhere !
3224        unicodePathExtraField =
3225            // Version
3226            decToHex(1, 1) +
3227            // NameCRC32
3228            decToHex(crc32(utfEncodedFileName), 4) +
3229            // UnicodeName
3230            utfEncodedFileName;
3231
3232        extraFields +=
3233            // Info-ZIP Unicode Path Extra Field
3234            "\x75\x70" +
3235            // size
3236            decToHex(unicodePathExtraField.length, 2) +
3237            // content
3238            unicodePathExtraField;
3239    }
3240
3241    if(useUTF8ForComment) {
3242
3243        unicodeCommentExtraField =
3244            // Version
3245            decToHex(1, 1) +
3246            // CommentCRC32
3247            decToHex(this.crc32(utfEncodedComment), 4) +
3248            // UnicodeName
3249            utfEncodedComment;
3250
3251        extraFields +=
3252            // Info-ZIP Unicode Path Extra Field
3253            "\x75\x63" +
3254            // size
3255            decToHex(unicodeCommentExtraField.length, 2) +
3256            // content
3257            unicodeCommentExtraField;
3258    }
3259
3260    var header = "";
3261
3262    // version needed to extract
3263    header += "\x0A\x00";
3264    // general purpose bit flag
3265    // set bit 11 if utf8
3266    header += (useUTF8ForFileName || useUTF8ForComment) ? "\x00\x08" : "\x00\x00";
3267    // compression method
3268    header += compressedObject.compressionMethod;
3269    // last mod file time
3270    header += decToHex(dosTime, 2);
3271    // last mod file date
3272    header += decToHex(dosDate, 2);
3273    // crc-32
3274    header += decToHex(compressedObject.crc32, 4);
3275    // compressed size
3276    header += decToHex(compressedObject.compressedSize, 4);
3277    // uncompressed size
3278    header += decToHex(compressedObject.uncompressedSize, 4);
3279    // file name length
3280    header += decToHex(utfEncodedFileName.length, 2);
3281    // extra field length
3282    header += decToHex(extraFields.length, 2);
3283
3284
3285    var fileRecord = signature.LOCAL_FILE_HEADER + header + utfEncodedFileName + extraFields;
3286
3287    var dirRecord = signature.CENTRAL_FILE_HEADER +
3288    // version made by (00: DOS)
3289    decToHex(versionMadeBy, 2) +
3290    // file header (common to file and central directory)
3291    header +
3292    // file comment length
3293    decToHex(utfEncodedComment.length, 2) +
3294    // disk number start
3295    "\x00\x00" +
3296    // internal file attributes TODO
3297    "\x00\x00" +
3298    // external file attributes
3299    decToHex(extFileAttr, 4) +
3300    // relative offset of local header
3301    decToHex(offset, 4) +
3302    // file name
3303    utfEncodedFileName +
3304    // extra field
3305    extraFields +
3306    // file comment
3307    utfEncodedComment;
3308
3309    return {
3310        fileRecord: fileRecord,
3311        dirRecord: dirRecord,
3312        compressedObject: compressedObject
3313    };
3314};
3315
3316
3317// return the actual prototype of JSZip
3318var out = {
3319    /**
3320     * Read an existing zip and merge the data in the current JSZip object.
3321     * The implementation is in jszip-load.js, don't forget to include it.
3322     * @param {String|ArrayBuffer|Uint8Array|Buffer} stream  The stream to load
3323     * @param {Object} options Options for loading the stream.
3324     *  options.base64 : is the stream in base64 ? default : false
3325     * @return {JSZip} the current JSZip object
3326     */
3327    load: function(stream, options) {
3328        throw new Error("Load method is not defined. Is the file jszip-load.js included ?");
3329    },
3330
3331    /**
3332     * Filter nested files/folders with the specified function.
3333     * @param {Function} search the predicate to use :
3334     * function (relativePath, file) {...}
3335     * It takes 2 arguments : the relative path and the file.
3336     * @return {Array} An array of matching elements.
3337     */
3338    filter: function(search) {
3339        var result = [],
3340            filename, relativePath, file, fileClone;
3341        for (filename in this.files) {
3342            if (!this.files.hasOwnProperty(filename)) {
3343                continue;
3344            }
3345            file = this.files[filename];
3346            // return a new object, don't let the user mess with our internal objects :)
3347            fileClone = new ZipObject(file.name, file._data, extend(file.options));
3348            relativePath = filename.slice(this.root.length, filename.length);
3349            if (filename.slice(0, this.root.length) === this.root && // the file is in the current root
3350            search(relativePath, fileClone)) { // and the file matches the function
3351                result.push(fileClone);
3352            }
3353        }
3354        return result;
3355    },
3356
3357    /**
3358     * Add a file to the zip file, or search a file.
3359     * @param   {string|RegExp} name The name of the file to add (if data is defined),
3360     * the name of the file to find (if no data) or a regex to match files.
3361     * @param   {String|ArrayBuffer|Uint8Array|Buffer} data  The file data, either raw or base64 encoded
3362     * @param   {Object} o     File options
3363     * @return  {JSZip|Object|Array} this JSZip object (when adding a file),
3364     * a file (when searching by string) or an array of files (when searching by regex).
3365     */
3366    file: function(name, data, o) {
3367        if (arguments.length === 1) {
3368            if (utils.isRegExp(name)) {
3369                var regexp = name;
3370                return this.filter(function(relativePath, file) {
3371                    return !file.dir && regexp.test(relativePath);
3372                });
3373            }
3374            else { // text
3375                return this.filter(function(relativePath, file) {
3376                    return !file.dir && relativePath === name;
3377                })[0] || null;
3378            }
3379        }
3380        else { // more than one argument : we have data !
3381            name = this.root + name;
3382            fileAdd.call(this, name, data, o);
3383        }
3384        return this;
3385    },
3386
3387    /**
3388     * Add a directory to the zip file, or search.
3389     * @param   {String|RegExp} arg The name of the directory to add, or a regex to search folders.
3390     * @return  {JSZip} an object with the new directory as the root, or an array containing matching folders.
3391     */
3392    folder: function(arg) {
3393        if (!arg) {
3394            return this;
3395        }
3396
3397        if (utils.isRegExp(arg)) {
3398            return this.filter(function(relativePath, file) {
3399                return file.dir && arg.test(relativePath);
3400            });
3401        }
3402
3403        // else, name is a new folder
3404        var name = this.root + arg;
3405        var newFolder = folderAdd.call(this, name);
3406
3407        // Allow chaining by returning a new object with this folder as the root
3408        var ret = this.clone();
3409        ret.root = newFolder.name;
3410        return ret;
3411    },
3412
3413    /**
3414     * Delete a file, or a directory and all sub-files, from the zip
3415     * @param {string} name the name of the file to delete
3416     * @return {JSZip} this JSZip object
3417     */
3418    remove: function(name) {
3419        name = this.root + name;
3420        var file = this.files[name];
3421        if (!file) {
3422            // Look for any folders
3423            if (name.slice(-1) != "/") {
3424                name += "/";
3425            }
3426            file = this.files[name];
3427        }
3428
3429        if (file && !file.dir) {
3430            // file
3431            delete this.files[name];
3432        } else {
3433            // maybe a folder, delete recursively
3434            var kids = this.filter(function(relativePath, file) {
3435                return file.name.slice(0, name.length) === name;
3436            });
3437            for (var i = 0; i < kids.length; i++) {
3438                delete this.files[kids[i].name];
3439            }
3440        }
3441
3442        return this;
3443    },
3444
3445    /**
3446     * Generate the complete zip file
3447     * @param {Object} options the options to generate the zip file :
3448     * - base64, (deprecated, use type instead) true to generate base64.
3449     * - compression, "STORE" by default.
3450     * - type, "base64" by default. Values are : string, base64, uint8array, arraybuffer, blob.
3451     * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file
3452     */
3453    generate: function(options) {
3454        options = extend(options || {}, {
3455            base64: true,
3456            compression: "STORE",
3457            compressionOptions : null,
3458            type: "base64",
3459            platform: "DOS",
3460            comment: null,
3461            mimeType: 'application/zip'
3462        });
3463
3464        utils.checkSupport(options.type);
3465
3466        // accept nodejs `process.platform`
3467        if(
3468          options.platform === 'darwin' ||
3469          options.platform === 'freebsd' ||
3470          options.platform === 'linux' ||
3471          options.platform === 'sunos'
3472        ) {
3473          options.platform = "UNIX";
3474        }
3475        if (options.platform === 'win32') {
3476          options.platform = "DOS";
3477        }
3478
3479        var zipData = [],
3480            localDirLength = 0,
3481            centralDirLength = 0,
3482            writer, i,
3483            utfEncodedComment = utils.transformTo("string", this.utf8encode(options.comment || this.comment || ""));
3484
3485        // first, generate all the zip parts.
3486        for (var name in this.files) {
3487            if (!this.files.hasOwnProperty(name)) {
3488                continue;
3489            }
3490            var file = this.files[name];
3491
3492            var compressionName = file.options.compression || options.compression.toUpperCase();
3493            var compression = compressions[compressionName];
3494            if (!compression) {
3495                throw new Error(compressionName + " is not a valid compression method !");
3496            }
3497            var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};
3498
3499            var compressedObject = generateCompressedObjectFrom.call(this, file, compression, compressionOptions);
3500
3501            var zipPart = generateZipParts.call(this, name, file, compressedObject, localDirLength, options.platform);
3502            localDirLength += zipPart.fileRecord.length + compressedObject.compressedSize;
3503            centralDirLength += zipPart.dirRecord.length;
3504            zipData.push(zipPart);
3505        }
3506
3507        var dirEnd = "";
3508
3509        // end of central dir signature
3510        dirEnd = signature.CENTRAL_DIRECTORY_END +
3511        // number of this disk
3512        "\x00\x00" +
3513        // number of the disk with the start of the central directory
3514        "\x00\x00" +
3515        // total number of entries in the central directory on this disk
3516        decToHex(zipData.length, 2) +
3517        // total number of entries in the central directory
3518        decToHex(zipData.length, 2) +
3519        // size of the central directory   4 bytes
3520        decToHex(centralDirLength, 4) +
3521        // offset of start of central directory with respect to the starting disk number
3522        decToHex(localDirLength, 4) +
3523        // .ZIP file comment length
3524        decToHex(utfEncodedComment.length, 2) +
3525        // .ZIP file comment
3526        utfEncodedComment;
3527
3528
3529        // we have all the parts (and the total length)
3530        // time to create a writer !
3531        var typeName = options.type.toLowerCase();
3532        if(typeName==="uint8array"||typeName==="arraybuffer"||typeName==="blob"||typeName==="nodebuffer") {
3533            writer = new Uint8ArrayWriter(localDirLength + centralDirLength + dirEnd.length);
3534        }else{
3535            writer = new StringWriter(localDirLength + centralDirLength + dirEnd.length);
3536        }
3537
3538        for (i = 0; i < zipData.length; i++) {
3539            writer.append(zipData[i].fileRecord);
3540            writer.append(zipData[i].compressedObject.compressedContent);
3541        }
3542        for (i = 0; i < zipData.length; i++) {
3543            writer.append(zipData[i].dirRecord);
3544        }
3545
3546        writer.append(dirEnd);
3547
3548        var zip = writer.finalize();
3549
3550
3551
3552        switch(options.type.toLowerCase()) {
3553            // case "zip is an Uint8Array"
3554            case "uint8array" :
3555            case "arraybuffer" :
3556            case "nodebuffer" :
3557               return utils.transformTo(options.type.toLowerCase(), zip);
3558            case "blob" :
3559               return utils.arrayBuffer2Blob(utils.transformTo("arraybuffer", zip), options.mimeType);
3560            // case "zip is a string"
3561            case "base64" :
3562               return (options.base64) ? base64.encode(zip) : zip;
3563            default : // case "string" :
3564               return zip;
3565         }
3566
3567    },
3568
3569    /**
3570     * @deprecated
3571     * This method will be removed in a future version without replacement.
3572     */
3573    crc32: function (input, crc) {
3574        return crc32(input, crc);
3575    },
3576
3577    /**
3578     * @deprecated
3579     * This method will be removed in a future version without replacement.
3580     */
3581    utf8encode: function (string) {
3582        return utils.transformTo("string", utf8.utf8encode(string));
3583    },
3584
3585    /**
3586     * @deprecated
3587     * This method will be removed in a future version without replacement.
3588     */
3589    utf8decode: function (input) {
3590        return utf8.utf8decode(input);
3591    }
3592};
3593module.exports = out;
3594
3595},{"./base64":9,"./compressedObject":10,"./compressions":11,"./crc32":12,"./defaults":14,"./nodeBuffer":19,"./signature":22,"./stringWriter"
vendor: 11,172 bytes, lines 3595-3977
3595:24,"./support":25,"./uint8ArrayWriter":27,"./utf8":28,"./utils":29}],22:[function(require,module,exports){
3596'use strict';
3597exports.LOCAL_FILE_HEADER = "PK\x03\x04";
3598exports.CENTRAL_FILE_HEADER = "PK\x01\x02";
3599exports.CENTRAL_DIRECTORY_END = "PK\x05\x06";
3600exports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = "PK\x06\x07";
3601exports.ZIP64_CENTRAL_DIRECTORY_END = "PK\x06\x06";
3602exports.DATA_DESCRIPTOR = "PK\x07\x08";
3603
3604},{}],23:[function(require,module,exports){
3605'use strict';
3606var DataReader = require('./dataReader');
3607var utils = require('./utils');
3608
3609function StringReader(data, optimizedBinaryString) {
3610    this.data = data;
3611    if (!optimizedBinaryString) {
3612        this.data = utils.string2binary(this.data);
3613    }
3614    this.length = this.data.length;
3615    this.index = 0;
3616}
3617StringReader.prototype = new DataReader();
3618/**
3619 * @see DataReader.byteAt
3620 */
3621StringReader.prototype.byteAt = function(i) {
3622    return this.data.charCodeAt(i);
3623};
3624/**
3625 * @see DataReader.lastIndexOfSignature
3626 */
3627StringReader.prototype.lastIndexOfSignature = function(sig) {
3628    return this.data.lastIndexOf(sig);
3629};
3630/**
3631 * @see DataReader.readData
3632 */
3633StringReader.prototype.readData = function(size) {
3634    this.checkOffset(size);
3635    // this will work because the constructor applied the "& 0xff" mask.
3636    var result = this.data.slice(this.index, this.index + size);
3637    this.index += size;
3638    return result;
3639};
3640module.exports = StringReader;
3641
3642},{"./dataReader":13,"./utils":29}],24:[function(require,module,exports){
3643'use strict';
3644
3645var utils = require('./utils');
3646
3647/**
3648 * An object to write any content to a string.
3649 * @constructor
3650 */
3651var StringWriter = function() {
3652    this.data = [];
3653};
3654StringWriter.prototype = {
3655    /**
3656     * Append any content to the current string.
3657     * @param {Object} input the content to add.
3658     */
3659    append: function(input) {
3660        input = utils.transformTo("string", input);
3661        this.data.push(input);
3662    },
3663    /**
3664     * Finalize the construction an return the result.
3665     * @return {string} the generated string.
3666     */
3667    finalize: function() {
3668        return this.data.join("");
3669    }
3670};
3671
3672module.exports = StringWriter;
3673
3674},{"./utils":29}],25:[function(require,module,exports){
3675(function (Buffer){
3676'use strict';
3677exports.base64 = true;
3678exports.array = true;
3679exports.string = true;
3680exports.arraybuffer = typeof ArrayBuffer !== "undefined" && typeof Uint8Array !== "undefined";
3681// contains true if JSZip can read/generate nodejs Buffer, false otherwise.
3682// Browserify will provide a Buffer implementation for browsers, which is
3683// an augmented Uint8Array (i.e., can be used as either Buffer or U8).
3684exports.nodebuffer = typeof Buffer !== "undefined";
3685// contains true if JSZip can read/generate Uint8Array, false otherwise.
3686exports.uint8array = typeof Uint8Array !== "undefined";
3687
3688if (typeof ArrayBuffer === "undefined") {
3689    exports.blob = false;
3690}
3691else {
3692    var buffer = new ArrayBuffer(0);
3693    try {
3694        exports.blob = new Blob([buffer], {
3695            type: "application/zip"
3696        }).size === 0;
3697    }
3698    catch (e) {
3699        try {
3700            var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
3701            var builder = new Builder();
3702            builder.append(buffer);
3703            exports.blob = builder.getBlob('application/zip').size === 0;
3704        }
3705        catch (e) {
3706            exports.blob = false;
3707        }
3708    }
3709}
3710
3711}).call(this,require("buffer").Buffer)
3712},{"buffer":5}],26:[function(require,module,exports){
3713'use strict';
3714var DataReader = require('./dataReader');
3715
3716function Uint8ArrayReader(data) {
3717    if (data) {
3718        this.data = data;
3719        this.length = this.data.length;
3720        this.index = 0;
3721    }
3722}
3723Uint8ArrayReader.prototype = new DataReader();
3724/**
3725 * @see DataReader.byteAt
3726 */
3727Uint8ArrayReader.prototype.byteAt = function(i) {
3728    return this.data[i];
3729};
3730/**
3731 * @see DataReader.lastIndexOfSignature
3732 */
3733Uint8ArrayReader.prototype.lastIndexOfSignature = function(sig) {
3734    var sig0 = sig.charCodeAt(0),
3735        sig1 = sig.charCodeAt(1),
3736        sig2 = sig.charCodeAt(2),
3737        sig3 = sig.charCodeAt(3);
3738    for (var i = this.length - 4; i >= 0; --i) {
3739        if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {
3740            return i;
3741        }
3742    }
3743
3744    return -1;
3745};
3746/**
3747 * @see DataReader.readData
3748 */
3749Uint8ArrayReader.prototype.readData = function(size) {
3750    this.checkOffset(size);
3751    if(size === 0) {
3752        // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].
3753        return new Uint8Array(0);
3754    }
3755    var result = this.data.subarray(this.index, this.index + size);
3756    this.index += size;
3757    return result;
3758};
3759module.exports = Uint8ArrayReader;
3760
3761},{"./dataReader":13}],27:[function(require,module,exports){
3762'use strict';
3763
3764var utils = require('./utils');
3765
3766/**
3767 * An object to write any content to an Uint8Array.
3768 * @constructor
3769 * @param {number} length The length of the array.
3770 */
3771var Uint8ArrayWriter = function(length) {
3772    this.data = new Uint8Array(length);
3773    this.index = 0;
3774};
3775Uint8ArrayWriter.prototype = {
3776    /**
3777     * Append any content to the current array.
3778     * @param {Object} input the content to add.
3779     */
3780    append: function(input) {
3781        if (input.length !== 0) {
3782            // with an empty Uint8Array, Opera fails with a "Offset larger than array size"
3783            input = utils.transformTo("uint8array", input);
3784            this.data.set(input, this.index);
3785            this.index += input.length;
3786        }
3787    },
3788    /**
3789     * Finalize the construction an return the result.
3790     * @return {Uint8Array} the generated array.
3791     */
3792    finalize: function() {
3793        return this.data;
3794    }
3795};
3796
3797module.exports = Uint8ArrayWriter;
3798
3799},{"./utils":29}],28:[function(require,module,exports){
3800'use strict';
3801
3802var utils = require('./utils');
3803var support = require('./support');
3804var nodeBuffer = require('./nodeBuffer');
3805
3806/**
3807 * The following functions come from pako, from pako/lib/utils/strings
3808 * released under the MIT license, see pako https://github.com/nodeca/pako/
3809 */
3810
3811// Table with utf8 lengths (calculated by first byte of sequence)
3812// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
3813// because max possible codepoint is 0x10ffff
3814var _utf8len = new Array(256);
3815for (var i=0; i<256; i++) {
3816  _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
3817}
3818_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
3819
3820// convert string to array (typed, when possible)
3821var string2buf = function (str) {
3822    var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
3823
3824    // count binary size
3825    for (m_pos = 0; m_pos < str_len; m_pos++) {
3826        c = str.charCodeAt(m_pos);
3827        if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
3828            c2 = str.charCodeAt(m_pos+1);
3829            if ((c2 & 0xfc00) === 0xdc00) {
3830                c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
3831                m_pos++;
3832            }
3833        }
3834        buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
3835    }
3836
3837    // allocate buffer
3838    if (support.uint8array) {
3839        buf = new Uint8Array(buf_len);
3840    } else {
3841        buf = new Array(buf_len);
3842    }
3843
3844    // convert
3845    for (i=0, m_pos = 0; i < buf_len; m_pos++) {
3846        c = str.charCodeAt(m_pos);
3847        if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
3848            c2 = str.charCodeAt(m_pos+1);
3849            if ((c2 & 0xfc00) === 0xdc00) {
3850                c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
3851                m_pos++;
3852            }
3853        }
3854        if (c < 0x80) {
3855            /* one byte */
3856            buf[i++] = c;
3857        } else if (c < 0x800) {
3858            /* two bytes */
3859            buf[i++] = 0xC0 | (c >>> 6);
3860            buf[i++] = 0x80 | (c & 0x3f);
3861        } else if (c < 0x10000) {
3862            /* three bytes */
3863            buf[i++] = 0xE0 | (c >>> 12);
3864            buf[i++] = 0x80 | (c >>> 6 & 0x3f);
3865            buf[i++] = 0x80 | (c & 0x3f);
3866        } else {
3867            /* four bytes */
3868            buf[i++] = 0xf0 | (c >>> 18);
3869            buf[i++] = 0x80 | (c >>> 12 & 0x3f);
3870            buf[i++] = 0x80 | (c >>> 6 & 0x3f);
3871            buf[i++] = 0x80 | (c & 0x3f);
3872        }
3873    }
3874
3875    return buf;
3876};
3877
3878// Calculate max possible position in utf8 buffer,
3879// that will not break sequence. If that's not possible
3880// - (very small limits) return max size as is.
3881//
3882// buf[] - utf8 bytes array
3883// max   - length limit (mandatory);
3884var utf8border = function(buf, max) {
3885    var pos;
3886
3887    max = max || buf.length;
3888    if (max > buf.length) { max = buf.length; }
3889
3890    // go back from last position, until start of sequence found
3891    pos = max-1;
3892    while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
3893
3894    // Fuckup - very small and broken sequence,
3895    // return max, because we should return something anyway.
3896    if (pos < 0) { return max; }
3897
3898    // If we came to start of buffer - that means vuffer is too small,
3899    // return max too.
3900    if (pos === 0) { return max; }
3901
3902    return (pos + _utf8len[buf[pos]] > max) ? pos : max;
3903};
3904
3905// convert array to string
3906var buf2string = function (buf) {
3907    var str, i, out, c, c_len;
3908    var len = buf.length;
3909
3910    // Reserve max possible length (2 words per char)
3911    // NB: by unknown reasons, Array is significantly faster for
3912    //     String.fromCharCode.apply than Uint16Array.
3913    var utf16buf = new Array(len*2);
3914
3915    for (out=0, i=0; i<len;) {
3916        c = buf[i++];
3917        // quick process ascii
3918        if (c < 0x80) { utf16buf[out++] = c; continue; }
3919
3920        c_len = _utf8len[c];
3921        // skip 5 & 6 byte codes
3922        if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
3923
3924        // apply mask on first byte
3925        c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
3926        // join the rest
3927        while (c_len > 1 && i < len) {
3928            c = (c << 6) | (buf[i++] & 0x3f);
3929            c_len--;
3930        }
3931
3932        // terminated by end of string?
3933        if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
3934
3935        if (c < 0x10000) {
3936            utf16buf[out++] = c;
3937        } else {
3938            c -= 0x10000;
3939            utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
3940            utf16buf[out++] = 0xdc00 | (c & 0x3ff);
3941        }
3942    }
3943
3944    // shrinkBuf(utf16buf, out)
3945    if (utf16buf.length !== out) {
3946        if(utf16buf.subarray) {
3947            utf16buf = utf16buf.subarray(0, out);
3948        } else {
3949            utf16buf.length = out;
3950        }
3951    }
3952
3953    // return String.fromCharCode.apply(null, utf16buf);
3954    return utils.applyFromCharCode(utf16buf);
3955};
3956
3957
3958// That's all for the pako functions.
3959
3960
3961/**
3962 * Transform a javascript string into an array (typed if possible) of bytes,
3963 * UTF-8 encoded.
3964 * @param {String} str the string to encode
3965 * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.
3966 */
3967exports.utf8encode = function utf8encode(str) {
3968    if (support.nodebuffer) {
3969        return nodeBuffer(str, "utf-8");
3970    }
3971
3972    return string2buf(str);
3973};
3974
3975
3976/**
3977 * Transform a bytes array (or a representation) representing an UTF-8 encoded
vendor: 2,225 bytes, lines 3978-4042
3978 * string into a javascript string.
3979 * @param {Array|Uint8Array|Buffer} buf the data de decode
3980 * @return {String} the decoded string.
3981 */
3982exports.utf8decode = function utf8decode(buf) {
3983    if (support.nodebuffer) {
3984        return utils.transformTo("nodebuffer", buf).toString("utf-8");
3985    }
3986
3987    buf = utils.transformTo(support.uint8array ? "uint8array" : "array", buf);
3988
3989    // return buf2string(buf);
3990    // Chrome prefers to work with "small" chunks of data
3991    // for the method buf2string.
3992    // Firefox and Chrome has their own shortcut, IE doesn't seem to really care.
3993    var result = [], k = 0, len = buf.length, chunk = 65536;
3994    while (k < len) {
3995        var nextBoundary = utf8border(buf, Math.min(k + chunk, len));
3996        if (support.uint8array) {
3997            result.push(buf2string(buf.subarray(k, nextBoundary)));
3998        } else {
3999            result.push(buf2string(buf.slice(k, nextBoundary)));
4000        }
4001        k = nextBoundary;
4002    }
4003    return result.join("");
4004
4005};
4006// vim: set shiftwidth=4 softtabstop=4:
4007
4008},{"./nodeBuffer":19,"./support":25,"./utils":29}],29:[function(require,module,exports){
4009'use strict';
4010var support = require('./support');
4011var compressions = require('./compressions');
4012var nodeBuffer = require('./nodeBuffer');
4013/**
4014 * Convert a string to a "binary string" : a string containing only char codes between 0 and 255.
4015 * @param {string} str the string to transform.
4016 * @return {String} the binary string.
4017 */
4018exports.string2binary = function(str) {
4019    var result = "";
4020    for (var i = 0; i < str.length; i++) {
4021        result += String.fromCharCode(str.charCodeAt(i) & 0xff);
4022    }
4023    return result;
4024};
4025exports.arrayBuffer2Blob = function(buffer, mimeType) {
4026    exports.checkSupport("blob");
4027	mimeType = mimeType || 'application/zip';
4028
4029    try {
4030        // Blob constructor
4031        return new Blob([buffer], {
4032            type: mimeType
4033        });
4034    }
4035    catch (e) {
4036
4037        try {
4038            // deprecated, browser only, old way
4039            var Builder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
4040            var builder = new Builder();
4041            builder.append(buffer);
4042            return builder.getBlob(mimeType
vendor: 8,686 bytes, lines 4042-4336
4042);
4043        }
4044        catch (e) {
4045
4046            // well, fuck ?!
4047            throw new Error("Bug : can't construct the Blob.");
4048        }
4049    }
4050
4051
4052};
4053/**
4054 * The identity function.
4055 * @param {Object} input the input.
4056 * @return {Object} the same input.
4057 */
4058function identity(input) {
4059    return input;
4060}
4061
4062/**
4063 * Fill in an array with a string.
4064 * @param {String} str the string to use.
4065 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).
4066 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.
4067 */
4068function stringToArrayLike(str, array) {
4069    for (var i = 0; i < str.length; ++i) {
4070        array[i] = str.charCodeAt(i) & 0xFF;
4071    }
4072    return array;
4073}
4074
4075/**
4076 * Transform an array-like object to a string.
4077 * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.
4078 * @return {String} the result.
4079 */
4080function arrayLikeToString(array) {
4081    // Performances notes :
4082    // --------------------
4083    // String.fromCharCode.apply(null, array) is the fastest, see
4084    // see http://jsperf.com/converting-a-uint8array-to-a-string/2
4085    // but the stack is limited (and we can get huge arrays !).
4086    //
4087    // result += String.fromCharCode(array[i]); generate too many strings !
4088    //
4089    // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2
4090    var chunk = 65536;
4091    var result = [],
4092        len = array.length,
4093        type = exports.getTypeOf(array),
4094        k = 0,
4095        canUseApply = true;
4096      try {
4097         switch(type) {
4098            case "uint8array":
4099               String.fromCharCode.apply(null, new Uint8Array(0));
4100               break;
4101            case "nodebuffer":
4102               String.fromCharCode.apply(null, nodeBuffer(0));
4103               break;
4104         }
4105      } catch(e) {
4106         canUseApply = false;
4107      }
4108
4109      // no apply : slow and painful algorithm
4110      // default browser on android 4.*
4111      if (!canUseApply) {
4112         var resultStr = "";
4113         for(var i = 0; i < array.length;i++) {
4114            resultStr += String.fromCharCode(array[i]);
4115         }
4116    return resultStr;
4117    }
4118    while (k < len && chunk > 1) {
4119        try {
4120            if (type === "array" || type === "nodebuffer") {
4121                result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));
4122            }
4123            else {
4124                result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));
4125            }
4126            k += chunk;
4127        }
4128        catch (e) {
4129            chunk = Math.floor(chunk / 2);
4130        }
4131    }
4132    return result.join("");
4133}
4134
4135exports.applyFromCharCode = arrayLikeToString;
4136
4137
4138/**
4139 * Copy the data from an array-like to an other array-like.
4140 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.
4141 * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.
4142 * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.
4143 */
4144function arrayLikeToArrayLike(arrayFrom, arrayTo) {
4145    for (var i = 0; i < arrayFrom.length; i++) {
4146        arrayTo[i] = arrayFrom[i];
4147    }
4148    return arrayTo;
4149}
4150
4151// a matrix containing functions to transform everything into everything.
4152var transform = {};
4153
4154// string to ?
4155transform["string"] = {
4156    "string": identity,
4157    "array": function(input) {
4158        return stringToArrayLike(input, new Array(input.length));
4159    },
4160    "arraybuffer": function(input) {
4161        return transform["string"]["uint8array"](input).buffer;
4162    },
4163    "uint8array": function(input) {
4164        return stringToArrayLike(input, new Uint8Array(input.length));
4165    },
4166    "nodebuffer": function(input) {
4167        return stringToArrayLike(input, nodeBuffer(input.length));
4168    }
4169};
4170
4171// array to ?
4172transform["array"] = {
4173    "string": arrayLikeToString,
4174    "array": identity,
4175    "arraybuffer": function(input) {
4176        return (new Uint8Array(input)).buffer;
4177    },
4178    "uint8array": function(input) {
4179        return new Uint8Array(input);
4180    },
4181    "nodebuffer": function(input) {
4182        return nodeBuffer(input);
4183    }
4184};
4185
4186// arraybuffer to ?
4187transform["arraybuffer"] = {
4188    "string": function(input) {
4189        return arrayLikeToString(new Uint8Array(input));
4190    },
4191    "array": function(input) {
4192        return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));
4193    },
4194    "arraybuffer": identity,
4195    "uint8array": function(input) {
4196        return new Uint8Array(input);
4197    },
4198    "nodebuffer": function(input) {
4199        return nodeBuffer(new Uint8Array(input));
4200    }
4201};
4202
4203// uint8array to ?
4204transform["uint8array"] = {
4205    "string": arrayLikeToString,
4206    "array": function(input) {
4207        return arrayLikeToArrayLike(input, new Array(input.length));
4208    },
4209    "arraybuffer": function(input) {
4210        return input.buffer;
4211    },
4212    "uint8array": identity,
4213    "nodebuffer": function(input) {
4214        return nodeBuffer(input);
4215    }
4216};
4217
4218// nodebuffer to ?
4219transform["nodebuffer"] = {
4220    "string": arrayLikeToString,
4221    "array": function(input) {
4222        return arrayLikeToArrayLike(input, new Array(input.length));
4223    },
4224    "arraybuffer": function(input) {
4225        return transform["nodebuffer"]["uint8array"](input).buffer;
4226    },
4227    "uint8array": function(input) {
4228        return arrayLikeToArrayLike(input, new Uint8Array(input.length));
4229    },
4230    "nodebuffer": identity
4231};
4232
4233/**
4234 * Transform an input into any type.
4235 * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.
4236 * If no output type is specified, the unmodified input will be returned.
4237 * @param {String} outputType the output type.
4238 * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.
4239 * @throws {Error} an Error if the browser doesn't support the requested output type.
4240 */
4241exports.transformTo = function(outputType, input) {
4242    if (!input) {
4243        // undefined, null, etc
4244        // an empty string won't harm.
4245        input = "";
4246    }
4247    if (!outputType) {
4248        return input;
4249    }
4250    exports.checkSupport(outputType);
4251    var inputType = exports.getTypeOf(input);
4252    var result = transform[inputType][outputType](input);
4253    return result;
4254};
4255
4256/**
4257 * Return the type of the input.
4258 * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.
4259 * @param {Object} input the input to identify.
4260 * @return {String} the (lowercase) type of the input.
4261 */
4262exports.getTypeOf = function(input) {
4263    if (typeof input === "string") {
4264        return "string";
4265    }
4266    if (Object.prototype.toString.call(input) === "[object Array]") {
4267        return "array";
4268    }
4269    if (support.nodebuffer && nodeBuffer.test(input)) {
4270        return "nodebuffer";
4271    }
4272    if (support.uint8array && input instanceof Uint8Array) {
4273        return "uint8array";
4274    }
4275    if (support.arraybuffer && input instanceof ArrayBuffer) {
4276        return "arraybuffer";
4277    }
4278};
4279
4280/**
4281 * Throw an exception if the type is not supported.
4282 * @param {String} type the type to check.
4283 * @throws {Error} an Error if the browser doesn't support the requested type.
4284 */
4285exports.checkSupport = function(type) {
4286    var supported = support[type.toLowerCase()];
4287    if (!supported) {
4288        throw new Error(type + " is not supported by this browser");
4289    }
4290};
4291exports.MAX_VALUE_16BITS = 65535;
4292exports.MAX_VALUE_32BITS = -1; // well, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF" is parsed as -1
4293
4294/**
4295 * Prettify a string read as binary.
4296 * @param {string} str the string to prettify.
4297 * @return {string} a pretty string.
4298 */
4299exports.pretty = function(str) {
4300    var res = '',
4301        code, i;
4302    for (i = 0; i < (str || "").length; i++) {
4303        code = str.charCodeAt(i);
4304        res += '\\x' + (code < 16 ? "0" : "") + code.toString(16).toUpperCase();
4305    }
4306    return res;
4307};
4308
4309/**
4310 * Find a compression registered in JSZip.
4311 * @param {string} compressionMethod the method magic to find.
4312 * @return {Object|null} the JSZip compression object, null if none found.
4313 */
4314exports.findCompression = function(compressionMethod) {
4315    for (var method in compressions) {
4316        if (!compressions.hasOwnProperty(method)) {
4317            continue;
4318        }
4319        if (compressions[method].magic === compressionMethod) {
4320            return compressions[method];
4321        }
4322    }
4323    return null;
4324};
4325/**
4326* Cross-window, cross-Node-context regular expression detection
4327* @param  {Object}  object Anything
4328* @return {Boolean}        true if the object is a regular expression,
4329* false otherwise
4330*/
4331exports.isRegExp = function (object) {
4332    return Object.prototype.toString.call(object) === "[object RegExp]";
4333};
4334
4335
4336},{"./compressions":
vendor: 5,850 bytes, lines 4336-4481
433611,"./nodeBuffer":19,"./support":25}],30:[function(require,module,exports){
4337'use strict';
4338var StringReader = require('./stringReader');
4339var NodeBufferReader = require('./nodeBufferReader');
4340var Uint8ArrayReader = require('./uint8ArrayReader');
4341var utils = require('./utils');
4342var sig = require('./signature');
4343var ZipEntry = require('./zipEntry');
4344var support = require('./support');
4345var jszipProto = require('./object');
4346//  class ZipEntries {{{
4347/**
4348 * All the entries in the zip file.
4349 * @constructor
4350 * @param {String|ArrayBuffer|Uint8Array} data the binary stream to load.
4351 * @param {Object} loadOptions Options for loading the stream.
4352 */
4353function ZipEntries(data, loadOptions) {
4354    this.files = [];
4355    this.loadOptions = loadOptions;
4356    if (data) {
4357        this.load(data);
4358    }
4359}
4360ZipEntries.prototype = {
4361    /**
4362     * Check that the reader is on the speficied signature.
4363     * @param {string} expectedSignature the expected signature.
4364     * @throws {Error} if it is an other signature.
4365     */
4366    checkSignature: function(expectedSignature) {
4367        var signature = this.reader.readString(4);
4368        if (signature !== expectedSignature) {
4369            throw new Error("Corrupted zip or bug : unexpected signature " + "(" + utils.pretty(signature) + ", expected " + utils.pretty(expectedSignature) + ")");
4370        }
4371    },
4372    /**
4373     * Read the end of the central directory.
4374     */
4375    readBlockEndOfCentral: function() {
4376        this.diskNumber = this.reader.readInt(2);
4377        this.diskWithCentralDirStart = this.reader.readInt(2);
4378        this.centralDirRecordsOnThisDisk = this.reader.readInt(2);
4379        this.centralDirRecords = this.reader.readInt(2);
4380        this.centralDirSize = this.reader.readInt(4);
4381        this.centralDirOffset = this.reader.readInt(4);
4382
4383        this.zipCommentLength = this.reader.readInt(2);
4384        // warning : the encoding depends of the system locale
4385        // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.
4386        // On a windows machine, this field is encoded with the localized windows code page.
4387        this.zipComment = this.reader.readString(this.zipCommentLength);
4388        // To get consistent behavior with the generation part, we will assume that
4389        // this is utf8 encoded.
4390        this.zipComment = jszipProto.utf8decode(this.zipComment);
4391    },
4392    /**
4393     * Read the end of the Zip 64 central directory.
4394     * Not merged with the method readEndOfCentral :
4395     * The end of central can coexist with its Zip64 brother,
4396     * I don't want to read the wrong number of bytes !
4397     */
4398    readBlockZip64EndOfCentral: function() {
4399        this.zip64EndOfCentralSize = this.reader.readInt(8);
4400        this.versionMadeBy = this.reader.readString(2);
4401        this.versionNeeded = this.reader.readInt(2);
4402        this.diskNumber = this.reader.readInt(4);
4403        this.diskWithCentralDirStart = this.reader.readInt(4);
4404        this.centralDirRecordsOnThisDisk = this.reader.readInt(8);
4405        this.centralDirRecords = this.reader.readInt(8);
4406        this.centralDirSize = this.reader.readInt(8);
4407        this.centralDirOffset = this.reader.readInt(8);
4408
4409        this.zip64ExtensibleData = {};
4410        var extraDataSize = this.zip64EndOfCentralSize - 44,
4411            index = 0,
4412            extraFieldId,
4413            extraFieldLength,
4414            extraFieldValue;
4415        while (index < extraDataSize) {
4416            extraFieldId = this.reader.readInt(2);
4417            extraFieldLength = this.reader.readInt(4);
4418            extraFieldValue = this.reader.readString(extraFieldLength);
4419            this.zip64ExtensibleData[extraFieldId] = {
4420                id: extraFieldId,
4421                length: extraFieldLength,
4422                value: extraFieldValue
4423            };
4424        }
4425    },
4426    /**
4427     * Read the end of the Zip 64 central directory locator.
4428     */
4429    readBlockZip64EndOfCentralLocator: function() {
4430        this.diskWithZip64CentralDirStart = this.reader.readInt(4);
4431        this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);
4432        this.disksCount = this.reader.readInt(4);
4433        if (this.disksCount > 1) {
4434            throw new Error("Multi-volumes zip are not supported");
4435        }
4436    },
4437    /**
4438     * Read the local files, based on the offset read in the central part.
4439     */
4440    readLocalFiles: function() {
4441        var i, file;
4442        for (i = 0; i < this.files.length; i++) {
4443            file = this.files[i];
4444            this.reader.setIndex(file.localHeaderOffset);
4445            this.checkSignature(sig.LOCAL_FILE_HEADER);
4446            file.readLocalPart(this.reader);
4447            file.handleUTF8();
4448            file.processAttributes();
4449        }
4450    },
4451    /**
4452     * Read the central directory.
4453     */
4454    readCentralDir: function() {
4455        var file;
4456
4457        this.reader.setIndex(this.centralDirOffset);
4458        while (this.reader.readString(4) === sig.CENTRAL_FILE_HEADER) {
4459            file = new ZipEntry({
4460                zip64: this.zip64
4461            }, this.loadOptions);
4462            file.readCentralPart(this.reader);
4463            this.files.push(file);
4464        }
4465    },
4466    /**
4467     * Read the end of central directory.
4468     */
4469    readEndOfCentral: function() {
4470        var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);
4471        if (offset === -1) {
4472            // Check if the content is a truncated zip or complete garbage.
4473            // A "LOCAL_FILE_HEADER" is not required at the beginning (auto
4474            // extractible zip for example) but it can give a good hint.
4475            // If an ajax request was used without responseType, we will also
4476            // get unreadable data.
4477            var isGarbage = true;
4478            try {
4479                this.reader.setIndex(0);
4480                this.checkSignature(sig.LOCAL_FILE_HEADER);
4481                isGarbage = false;
vendor: 8,072 bytes, lines 4482-4658
4482            } catch (e) {}
4483
4484            if (isGarbage) {
4485                throw new Error("Can't find end of central directory : is this a zip file ? " +
4486                                "If it is, see http://stuk.github.io/jszip/documentation/howto/read_zip.html");
4487            } else {
4488                throw new Error("Corrupted zip : can't find end of central directory");
4489            }
4490        }
4491        this.reader.setIndex(offset);
4492        this.checkSignature(sig.CENTRAL_DIRECTORY_END);
4493        this.readBlockEndOfCentral();
4494
4495
4496        /* extract from the zip spec :
4497            4)  If one of the fields in the end of central directory
4498                record is too small to hold required data, the field
4499                should be set to -1 (0xFFFF or 0xFFFFFFFF) and the
4500                ZIP64 format record should be created.
4501            5)  The end of central directory record and the
4502                Zip64 end of central directory locator record must
4503                reside on the same disk when splitting or spanning
4504                an archive.
4505         */
4506        if (this.diskNumber === utils.MAX_VALUE_16BITS || this.diskWithCentralDirStart === utils.MAX_VALUE_16BITS || this.centralDirRecordsOnThisDisk === utils.MAX_VALUE_16BITS || this.centralDirRecords === utils.MAX_VALUE_16BITS || this.centralDirSize === utils.MAX_VALUE_32BITS || this.centralDirOffset === utils.MAX_VALUE_32BITS) {
4507            this.zip64 = true;
4508
4509            /*
4510            Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from
4511            the zip file can fit into a 32bits integer. This cannot be solved : Javascript represents
4512            all numbers as 64-bit double precision IEEE 754 floating point numbers.
4513            So, we have 53bits for integers and bitwise operations treat everything as 32bits.
4514            see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators
4515            and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5
4516            */
4517
4518            // should look for a zip64 EOCD locator
4519            offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
4520            if (offset === -1) {
4521                throw new Error("Corrupted zip : can't find the ZIP64 end of central directory locator");
4522            }
4523            this.reader.setIndex(offset);
4524            this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);
4525            this.readBlockZip64EndOfCentralLocator();
4526
4527            // now the zip64 EOCD record
4528            this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);
4529            this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);
4530            this.readBlockZip64EndOfCentral();
4531        }
4532    },
4533    prepareReader: function(data) {
4534        var type = utils.getTypeOf(data);
4535        if (type === "string" && !support.uint8array) {
4536            this.reader = new StringReader(data, this.loadOptions.optimizedBinaryString);
4537        }
4538        else if (type === "nodebuffer") {
4539            this.reader = new NodeBufferReader(data);
4540        }
4541        else {
4542            this.reader = new Uint8ArrayReader(utils.transformTo("uint8array", data));
4543        }
4544    },
4545    /**
4546     * Read a zip file and create ZipEntries.
4547     * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.
4548     */
4549    load: function(data) {
4550        this.prepareReader(data);
4551        this.readEndOfCentral();
4552        this.readCentralDir();
4553        this.readLocalFiles();
4554    }
4555};
4556// }}} end of ZipEntries
4557module.exports = ZipEntries;
4558
4559},{"./nodeBufferReader":20,"./object":21,"./signature":22,"./stringReader":23,"./support":25,"./uint8ArrayReader":26,"./utils":29,"./zipEntry":31}],31:[function(require,module,exports){
4560'use strict';
4561var StringReader = require('./stringReader');
4562var utils = require('./utils');
4563var CompressedObject = require('./compressedObject');
4564var jszipProto = require('./object');
4565
4566var MADE_BY_DOS = 0x00;
4567var MADE_BY_UNIX = 0x03;
4568
4569// class ZipEntry {{{
4570/**
4571 * An entry in the zip file.
4572 * @constructor
4573 * @param {Object} options Options of the current file.
4574 * @param {Object} loadOptions Options for loading the stream.
4575 */
4576function ZipEntry(options, loadOptions) {
4577    this.options = options;
4578    this.loadOptions = loadOptions;
4579}
4580ZipEntry.prototype = {
4581    /**
4582     * say if the file is encrypted.
4583     * @return {boolean} true if the file is encrypted, false otherwise.
4584     */
4585    isEncrypted: function() {
4586        // bit 1 is set
4587        return (this.bitFlag & 0x0001) === 0x0001;
4588    },
4589    /**
4590     * say if the file has utf-8 filename/comment.
4591     * @return {boolean} true if the filename/comment is in utf-8, false otherwise.
4592     */
4593    useUTF8: function() {
4594        // bit 11 is set
4595        return (this.bitFlag & 0x0800) === 0x0800;
4596    },
4597    /**
4598     * Prepare the function used to generate the compressed content from this ZipFile.
4599     * @param {DataReader} reader the reader to use.
4600     * @param {number} from the offset from where we should read the data.
4601     * @param {number} length the length of the data to read.
4602     * @return {Function} the callback to get the compressed content (the type depends of the DataReader class).
4603     */
4604    prepareCompressedContent: function(reader, from, length) {
4605        return function() {
4606            var previousIndex = reader.index;
4607            reader.setIndex(from);
4608            var compressedFileData = reader.readData(length);
4609            reader.setIndex(previousIndex);
4610
4611            return compressedFileData;
4612        };
4613    },
4614    /**
4615     * Prepare the function used to generate the uncompressed content from this ZipFile.
4616     * @param {DataReader} reader the reader to use.
4617     * @param {number} from the offset from where we should read the data.
4618     * @param {number} length the length of the data to read.
4619     * @param {JSZip.compression} compression the compression used on this file.
4620     * @param {number} uncompressedSize the uncompressed size to expect.
4621     * @return {Function} the callback to get the uncompressed content (the type depends of the DataReader class).
4622     */
4623    prepareContent: function(reader, from, length, compression, uncompressedSize) {
4624        return function() {
4625
4626            var compressedFileData = utils.transformTo(compression.uncompressInputType, this.getCompressedContent());
4627            var uncompressedFileData = compression.uncompress(compressedFileData);
4628
4629            if (uncompressedFileData.length !== uncompressedSize) {
4630                throw new Error("Bug : uncompressed data size mismatch");
4631            }
4632
4633            return uncompressedFileData;
4634        };
4635    },
4636    /**
4637     * Read the local part of a zip file and add the info in this object.
4638     * @param {DataReader} reader the reader to use.
4639     */
4640    readLocalPart: function(reader) {
4641        var compression, localExtraFieldsLength;
4642
4643        // we already know everything from the central dir !
4644        // If the central dir data are false, we are doomed.
4645        // On the bright side, the local part is scary  : zip64, data descriptors, both, etc.
4646        // The less data we get here, the more reliable this should be.
4647        // Let's skip the whole header and dash to the data !
4648        reader.skip(22);
4649        // in some zip created on windows, the filename stored in the central dir contains \ instead of /.
4650        // Strangely, the filename here is OK.
4651        // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes
4652        // or APPNOTE#4.4.17.1, "All slashes MUST be forward slashes '/'") but there are a lot of bad zip generators...
4653        // Search "unzip mismatching "local" filename continuing with "central" filename version" on
4654        // the internet.
4655        //
4656        // I think I see the logic here : the central directory is used to display
4657        // content and the local directory is used to extract the files. Mixing / and \
4658        // may be used to display \ to windows users and use / when extracting the files.
vendor: 10,204 bytes, lines 4659-4944
4659        // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394
4660        this.fileNameLength = reader.readInt(2);
4661        localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir
4662        this.fileName = reader.readString(this.fileNameLength);
4663        reader.skip(localExtraFieldsLength);
4664
4665        if (this.compressedSize == -1 || this.uncompressedSize == -1) {
4666            throw new Error("Bug or corrupted zip : didn't get enough informations from the central directory " + "(compressedSize == -1 || uncompressedSize == -1)");
4667        }
4668
4669        compression = utils.findCompression(this.compressionMethod);
4670        if (compression === null) { // no compression found
4671            throw new Error("Corrupted zip : compression " + utils.pretty(this.compressionMethod) + " unknown (inner file : " + this.fileName + ")");
4672        }
4673        this.decompressed = new CompressedObject();
4674        this.decompressed.compressedSize = this.compressedSize;
4675        this.decompressed.uncompressedSize = this.uncompressedSize;
4676        this.decompressed.crc32 = this.crc32;
4677        this.decompressed.compressionMethod = this.compressionMethod;
4678        this.decompressed.getCompressedContent = this.prepareCompressedContent(reader, reader.index, this.compressedSize, compression);
4679        this.decompressed.getContent = this.prepareContent(reader, reader.index, this.compressedSize, compression, this.uncompressedSize);
4680
4681        // we need to compute the crc32...
4682        if (this.loadOptions.checkCRC32) {
4683            this.decompressed = utils.transformTo("string", this.decompressed.getContent());
4684            if (jszipProto.crc32(this.decompressed) !== this.crc32) {
4685                throw new Error("Corrupted zip : CRC32 mismatch");
4686            }
4687        }
4688    },
4689
4690    /**
4691     * Read the central part of a zip file and add the info in this object.
4692     * @param {DataReader} reader the reader to use.
4693     */
4694    readCentralPart: function(reader) {
4695        this.versionMadeBy = reader.readInt(2);
4696        this.versionNeeded = reader.readInt(2);
4697        this.bitFlag = reader.readInt(2);
4698        this.compressionMethod = reader.readString(2);
4699        this.date = reader.readDate();
4700        this.crc32 = reader.readInt(4);
4701        this.compressedSize = reader.readInt(4);
4702        this.uncompressedSize = reader.readInt(4);
4703        this.fileNameLength = reader.readInt(2);
4704        this.extraFieldsLength = reader.readInt(2);
4705        this.fileCommentLength = reader.readInt(2);
4706        this.diskNumberStart = reader.readInt(2);
4707        this.internalFileAttributes = reader.readInt(2);
4708        this.externalFileAttributes = reader.readInt(4);
4709        this.localHeaderOffset = reader.readInt(4);
4710
4711        if (this.isEncrypted()) {
4712            throw new Error("Encrypted zip are not supported");
4713        }
4714
4715        this.fileName = reader.readString(this.fileNameLength);
4716        this.readExtraFields(reader);
4717        this.parseZIP64ExtraField(reader);
4718        this.fileComment = reader.readString(this.fileCommentLength);
4719    },
4720
4721    /**
4722     * Parse the external file attributes and get the unix/dos permissions.
4723     */
4724    processAttributes: function () {
4725        this.unixPermissions = null;
4726        this.dosPermissions = null;
4727        var madeBy = this.versionMadeBy >> 8;
4728
4729        // Check if we have the DOS directory flag set.
4730        // We look for it in the DOS and UNIX permissions
4731        // but some unknown platform could set it as a compatibility flag.
4732        this.dir = this.externalFileAttributes & 0x0010 ? true : false;
4733
4734        if(madeBy === MADE_BY_DOS) {
4735            // first 6 bits (0 to 5)
4736            this.dosPermissions = this.externalFileAttributes & 0x3F;
4737        }
4738
4739        if(madeBy === MADE_BY_UNIX) {
4740            this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;
4741            // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);
4742        }
4743
4744        // fail safe : if the name ends with a / it probably means a folder
4745        if (!this.dir && this.fileName.slice(-1) === '/') {
4746            this.dir = true;
4747        }
4748    },
4749
4750    /**
4751     * Parse the ZIP64 extra field and merge the info in the current ZipEntry.
4752     * @param {DataReader} reader the reader to use.
4753     */
4754    parseZIP64ExtraField: function(reader) {
4755
4756        if (!this.extraFields[0x0001]) {
4757            return;
4758        }
4759
4760        // should be something, preparing the extra reader
4761        var extraReader = new StringReader(this.extraFields[0x0001].value);
4762
4763        // I really hope that these 64bits integer can fit in 32 bits integer, because js
4764        // won't let us have more.
4765        if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {
4766            this.uncompressedSize = extraReader.readInt(8);
4767        }
4768        if (this.compressedSize === utils.MAX_VALUE_32BITS) {
4769            this.compressedSize = extraReader.readInt(8);
4770        }
4771        if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {
4772            this.localHeaderOffset = extraReader.readInt(8);
4773        }
4774        if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {
4775            this.diskNumberStart = extraReader.readInt(4);
4776        }
4777    },
4778    /**
4779     * Read the central part of a zip file and add the info in this object.
4780     * @param {DataReader} reader the reader to use.
4781     */
4782    readExtraFields: function(reader) {
4783        var start = reader.index,
4784            extraFieldId,
4785            extraFieldLength,
4786            extraFieldValue;
4787
4788        this.extraFields = this.extraFields || {};
4789
4790        while (reader.index < start + this.extraFieldsLength) {
4791            extraFieldId = reader.readInt(2);
4792            extraFieldLength = reader.readInt(2);
4793            extraFieldValue = reader.readString(extraFieldLength);
4794
4795            this.extraFields[extraFieldId] = {
4796                id: extraFieldId,
4797                length: extraFieldLength,
4798                value: extraFieldValue
4799            };
4800        }
4801    },
4802    /**
4803     * Apply an UTF8 transformation if needed.
4804     */
4805    handleUTF8: function() {
4806        if (this.useUTF8()) {
4807            this.fileName = jszipProto.utf8decode(this.fileName);
4808            this.fileComment = jszipProto.utf8decode(this.fileComment);
4809        } else {
4810            var upath = this.findExtraFieldUnicodePath();
4811            if (upath !== null) {
4812                this.fileName = upath;
4813            }
4814            var ucomment = this.findExtraFieldUnicodeComment();
4815            if (ucomment !== null) {
4816                this.fileComment = ucomment;
4817            }
4818        }
4819    },
4820
4821    /**
4822     * Find the unicode path declared in the extra field, if any.
4823     * @return {String} the unicode path, null otherwise.
4824     */
4825    findExtraFieldUnicodePath: function() {
4826        var upathField = this.extraFields[0x7075];
4827        if (upathField) {
4828            var extraReader = new StringReader(upathField.value);
4829
4830            // wrong version
4831            if (extraReader.readInt(1) !== 1) {
4832                return null;
4833            }
4834
4835            // the crc of the filename changed, this field is out of date.
4836            if (jszipProto.crc32(this.fileName) !== extraReader.readInt(4)) {
4837                return null;
4838            }
4839
4840            return jszipProto.utf8decode(extraReader.readString(upathField.length - 5));
4841        }
4842        return null;
4843    },
4844
4845    /**
4846     * Find the unicode comment declared in the extra field, if any.
4847     * @return {String} the unicode comment, null otherwise.
4848     */
4849    findExtraFieldUnicodeComment: function() {
4850        var ucommentField = this.extraFields[0x6375];
4851        if (ucommentField) {
4852            var extraReader = new StringReader(ucommentField.value);
4853
4854            // wrong version
4855            if (extraReader.readInt(1) !== 1) {
4856                return null;
4857            }
4858
4859            // the crc of the comment changed, this field is out of date.
4860            if (jszipProto.crc32(this.fileComment) !== extraReader.readInt(4)) {
4861                return null;
4862            }
4863
4864            return jszipProto.utf8decode(extraReader.readString(ucommentField.length - 5));
4865        }
4866        return null;
4867    }
4868};
4869module.exports = ZipEntry;
4870
4871},{"./compressedObject":10,"./object":21,"./stringReader":23,"./utils":29}],32:[function(require,module,exports){
4872// Top level file is just a mixin of submodules & constants
4873'use strict';
4874
4875var assign    = require('./lib/utils/common').assign;
4876
4877var deflate   = require('./lib/deflate');
4878var inflate   = require('./lib/inflate');
4879var constants = require('./lib/zlib/constants');
4880
4881var pako = {};
4882
4883assign(pako, deflate, inflate, constants);
4884
4885module.exports = pako;
4886
4887},{"./lib/deflate":33,"./lib/inflate":34,"./lib/utils/common":35,"./lib/zlib/constants":38}],33:[function(require,module,exports){
4888'use strict';
4889
4890
4891var zlib_deflate = require('./zlib/deflate.js');
4892var utils = require('./utils/common');
4893var strings = require('./utils/strings');
4894var msg = require('./zlib/messages');
4895var zstream = require('./zlib/zstream');
4896
4897var toString = Object.prototype.toString;
4898
4899/* Public constants ==========================================================*/
4900/* ===========================================================================*/
4901
4902var Z_NO_FLUSH      = 0;
4903var Z_FINISH        = 4;
4904
4905var Z_OK            = 0;
4906var Z_STREAM_END    = 1;
4907var Z_SYNC_FLUSH    = 2;
4908
4909var Z_DEFAULT_COMPRESSION = -1;
4910
4911var Z_DEFAULT_STRATEGY    = 0;
4912
4913var Z_DEFLATED  = 8;
4914
4915/* ===========================================================================*/
4916
4917
4918/**
4919 * class Deflate
4920 *
4921 * Generic JS-style wrapper for zlib calls. If you don't need
4922 * streaming behaviour - use more simple functions: [[deflate]],
4923 * [[deflateRaw]] and [[gzip]].
4924 **/
4925
4926/* internal
4927 * Deflate.chunks -> Array
4928 *
4929 * Chunks of output data, if [[Deflate#onData]] not overriden.
4930 **/
4931
4932/**
4933 * Deflate.result -> Uint8Array|Array
4934 *
4935 * Compressed result, generated by default [[Deflate#onData]]
4936 * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
4937 * (call [[Deflate#push]] with `Z_FINISH` / `true` param)  or if you
4938 * push a chunk with explicit flush (call [[Deflate#push]] with
4939 * `Z_SYNC_FLUSH` param).
4940 **/
4941
4942/**
4943 * Deflate.err -> Number
4944 *
vendor: 5,101 bytes, lines 4945-5116
4945 * Error code after deflate finished. 0 (Z_OK) on success.
4946 * You will not need it in real life, because deflate errors
4947 * are possible only on wrong options or bad `onData` / `onEnd`
4948 * custom handlers.
4949 **/
4950
4951/**
4952 * Deflate.msg -> String
4953 *
4954 * Error message, if [[Deflate.err]] != 0
4955 **/
4956
4957
4958/**
4959 * new Deflate(options)
4960 * - options (Object): zlib deflate options.
4961 *
4962 * Creates new deflator instance with specified params. Throws exception
4963 * on bad params. Supported options:
4964 *
4965 * - `level`
4966 * - `windowBits`
4967 * - `memLevel`
4968 * - `strategy`
4969 *
4970 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
4971 * for more information on these.
4972 *
4973 * Additional options, for internal needs:
4974 *
4975 * - `chunkSize` - size of generated data chunks (16K by default)
4976 * - `raw` (Boolean) - do raw deflate
4977 * - `gzip` (Boolean) - create gzip wrapper
4978 * - `to` (String) - if equal to 'string', then result will be "binary string"
4979 *    (each char code [0..255])
4980 * - `header` (Object) - custom header for gzip
4981 *   - `text` (Boolean) - true if compressed data believed to be text
4982 *   - `time` (Number) - modification time, unix timestamp
4983 *   - `os` (Number) - operation system code
4984 *   - `extra` (Array) - array of bytes with extra data (max 65536)
4985 *   - `name` (String) - file name (binary string)
4986 *   - `comment` (String) - comment (binary string)
4987 *   - `hcrc` (Boolean) - true if header crc should be added
4988 *
4989 * ##### Example:
4990 *
4991 * ```javascript
4992 * var pako = require('pako')
4993 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
4994 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
4995 *
4996 * var deflate = new pako.Deflate({ level: 3});
4997 *
4998 * deflate.push(chunk1, false);
4999 * deflate.push(chunk2, true);  // true -> last chunk
5000 *
5001 * if (deflate.err) { throw new Error(deflate.err); }
5002 *
5003 * console.log(deflate.result);
5004 * ```
5005 **/
5006var Deflate = function(options) {
5007
5008  this.options = utils.assign({
5009    level: Z_DEFAULT_COMPRESSION,
5010    method: Z_DEFLATED,
5011    chunkSize: 16384,
5012    windowBits: 15,
5013    memLevel: 8,
5014    strategy: Z_DEFAULT_STRATEGY,
5015    to: ''
5016  }, options || {});
5017
5018  var opt = this.options;
5019
5020  if (opt.raw && (opt.windowBits > 0)) {
5021    opt.windowBits = -opt.windowBits;
5022  }
5023
5024  else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
5025    opt.windowBits += 16;
5026  }
5027
5028  this.err    = 0;      // error code, if happens (0 = Z_OK)
5029  this.msg    = '';     // error message
5030  this.ended  = false;  // used to avoid multiple onEnd() calls
5031  this.chunks = [];     // chunks of compressed data
5032
5033  this.strm = new zstream();
5034  this.strm.avail_out = 0;
5035
5036  var status = zlib_deflate.deflateInit2(
5037    this.strm,
5038    opt.level,
5039    opt.method,
5040    opt.windowBits,
5041    opt.memLevel,
5042    opt.strategy
5043  );
5044
5045  if (status !== Z_OK) {
5046    throw new Error(msg[status]);
5047  }
5048
5049  if (opt.header) {
5050    zlib_deflate.deflateSetHeader(this.strm, opt.header);
5051  }
5052};
5053
5054/**
5055 * Deflate#push(data[, mode]) -> Boolean
5056 * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
5057 *   converted to utf8 byte sequence.
5058 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
5059 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
5060 *
5061 * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
5062 * new compressed chunks. Returns `true` on success. The last data block must have
5063 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
5064 * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
5065 * can use mode Z_SYNC_FLUSH, keeping the compression context.
5066 *
5067 * On fail call [[Deflate#onEnd]] with error code and return false.
5068 *
5069 * We strongly recommend to use `Uint8Array` on input for best speed (output
5070 * array format is detected automatically). Also, don't skip last param and always
5071 * use the same type in your code (boolean or number). That will improve JS speed.
5072 *
5073 * For regular `Array`-s make sure all elements are [0..255].
5074 *
5075 * ##### Example
5076 *
5077 * ```javascript
5078 * push(chunk, false); // push one of data chunks
5079 * ...
5080 * push(chunk, true);  // push last chunk
5081 * ```
5082 **/
5083Deflate.prototype.push = function(data, mode) {
5084  var strm = this.strm;
5085  var chunkSize = this.options.chunkSize;
5086  var status, _mode;
5087
5088  if (this.ended) { return false; }
5089
5090  _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
5091
5092  // Convert data if needed
5093  if (typeof data === 'string') {
5094    // If we need to compress text, change encoding to utf8.
5095    strm.input = strings.string2buf(data);
5096  } else if (toString.call(data) === '[object ArrayBuffer]') {
5097    strm.input = new Uint8Array(data);
5098  } else {
5099    strm.input = data;
5100  }
5101
5102  strm.next_in = 0;
5103  strm.avail_in = strm.input.length;
5104
5105  do {
5106    if (strm.avail_out === 0) {
5107      strm.output = new utils.Buf8(chunkSize);
5108      strm.next_out = 0;
5109      strm.avail_out = chunkSize;
5110    }
5111    status = zlib_deflate.deflate(strm, _mode);    /* no bad return value */
5112
5113    if (status !== Z_STREAM_END && status !== Z_OK) {
5114      this.onEnd(status);
5115      this.ended = true;
5116      return false;
vendor: 8,044 bytes, lines 5117-5413
5117    }
5118    if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
5119      if (this.options.to === 'string') {
5120        this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
5121      } else {
5122        this.onData(utils.shrinkBuf(strm.output, strm.next_out));
5123      }
5124    }
5125  } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
5126
5127  // Finalize on the last chunk.
5128  if (_mode === Z_FINISH) {
5129    status = zlib_deflate.deflateEnd(this.strm);
5130    this.onEnd(status);
5131    this.ended = true;
5132    return status === Z_OK;
5133  }
5134
5135  // callback interim results if Z_SYNC_FLUSH.
5136  if (_mode === Z_SYNC_FLUSH) {
5137    this.onEnd(Z_OK);
5138    strm.avail_out = 0;
5139    return true;
5140  }
5141
5142  return true;
5143};
5144
5145
5146/**
5147 * Deflate#onData(chunk) -> Void
5148 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
5149 *   on js engine support. When string output requested, each chunk
5150 *   will be string.
5151 *
5152 * By default, stores data blocks in `chunks[]` property and glue
5153 * those in `onEnd`. Override this handler, if you need another behaviour.
5154 **/
5155Deflate.prototype.onData = function(chunk) {
5156  this.chunks.push(chunk);
5157};
5158
5159
5160/**
5161 * Deflate#onEnd(status) -> Void
5162 * - status (Number): deflate status. 0 (Z_OK) on success,
5163 *   other if not.
5164 *
5165 * Called once after you tell deflate that the input stream is
5166 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
5167 * or if an error happened. By default - join collected chunks,
5168 * free memory and fill `results` / `err` properties.
5169 **/
5170Deflate.prototype.onEnd = function(status) {
5171  // On success - join
5172  if (status === Z_OK) {
5173    if (this.options.to === 'string') {
5174      this.result = this.chunks.join('');
5175    } else {
5176      this.result = utils.flattenChunks(this.chunks);
5177    }
5178  }
5179  this.chunks = [];
5180  this.err = status;
5181  this.msg = this.strm.msg;
5182};
5183
5184
5185/**
5186 * deflate(data[, options]) -> Uint8Array|Array|String
5187 * - data (Uint8Array|Array|String): input data to compress.
5188 * - options (Object): zlib deflate options.
5189 *
5190 * Compress `data` with deflate alrorythm and `options`.
5191 *
5192 * Supported options are:
5193 *
5194 * - level
5195 * - windowBits
5196 * - memLevel
5197 * - strategy
5198 *
5199 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5200 * for more information on these.
5201 *
5202 * Sugar (options):
5203 *
5204 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
5205 *   negative windowBits implicitly.
5206 * - `to` (String) - if equal to 'string', then result will be "binary string"
5207 *    (each char code [0..255])
5208 *
5209 * ##### Example:
5210 *
5211 * ```javascript
5212 * var pako = require('pako')
5213 *   , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
5214 *
5215 * console.log(pako.deflate(data));
5216 * ```
5217 **/
5218function deflate(input, options) {
5219  var deflator = new Deflate(options);
5220
5221  deflator.push(input, true);
5222
5223  // That will never happens, if you don't cheat with options :)
5224  if (deflator.err) { throw deflator.msg; }
5225
5226  return deflator.result;
5227}
5228
5229
5230/**
5231 * deflateRaw(data[, options]) -> Uint8Array|Array|String
5232 * - data (Uint8Array|Array|String): input data to compress.
5233 * - options (Object): zlib deflate options.
5234 *
5235 * The same as [[deflate]], but creates raw data, without wrapper
5236 * (header and adler32 crc).
5237 **/
5238function deflateRaw(input, options) {
5239  options = options || {};
5240  options.raw = true;
5241  return deflate(input, options);
5242}
5243
5244
5245/**
5246 * gzip(data[, options]) -> Uint8Array|Array|String
5247 * - data (Uint8Array|Array|String): input data to compress.
5248 * - options (Object): zlib deflate options.
5249 *
5250 * The same as [[deflate]], but create gzip wrapper instead of
5251 * deflate one.
5252 **/
5253function gzip(input, options) {
5254  options = options || {};
5255  options.gzip = true;
5256  return deflate(input, options);
5257}
5258
5259
5260exports.Deflate = Deflate;
5261exports.deflate = deflate;
5262exports.deflateRaw = deflateRaw;
5263exports.gzip = gzip;
5264
5265},{"./utils/common":35,"./utils/strings":36,"./zlib/deflate.js":40,"./zlib/messages":45,"./zlib/zstream":47}],34:[function(require,module,exports){
5266'use strict';
5267
5268
5269var zlib_inflate = require('./zlib/inflate.js');
5270var utils = require('./utils/common');
5271var strings = require('./utils/strings');
5272var c = require('./zlib/constants');
5273var msg = require('./zlib/messages');
5274var zstream = require('./zlib/zstream');
5275var gzheader = require('./zlib/gzheader');
5276
5277var toString = Object.prototype.toString;
5278
5279/**
5280 * class Inflate
5281 *
5282 * Generic JS-style wrapper for zlib calls. If you don't need
5283 * streaming behaviour - use more simple functions: [[inflate]]
5284 * and [[inflateRaw]].
5285 **/
5286
5287/* internal
5288 * inflate.chunks -> Array
5289 *
5290 * Chunks of output data, if [[Inflate#onData]] not overriden.
5291 **/
5292
5293/**
5294 * Inflate.result -> Uint8Array|Array|String
5295 *
5296 * Uncompressed result, generated by default [[Inflate#onData]]
5297 * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
5298 * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
5299 * push a chunk with explicit flush (call [[Inflate#push]] with
5300 * `Z_SYNC_FLUSH` param).
5301 **/
5302
5303/**
5304 * Inflate.err -> Number
5305 *
5306 * Error code after inflate finished. 0 (Z_OK) on success.
5307 * Should be checked if broken data possible.
5308 **/
5309
5310/**
5311 * Inflate.msg -> String
5312 *
5313 * Error message, if [[Inflate.err]] != 0
5314 **/
5315
5316
5317/**
5318 * new Inflate(options)
5319 * - options (Object): zlib inflate options.
5320 *
5321 * Creates new inflator instance with specified params. Throws exception
5322 * on bad params. Supported options:
5323 *
5324 * - `windowBits`
5325 *
5326 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5327 * for more information on these.
5328 *
5329 * Additional options, for internal needs:
5330 *
5331 * - `chunkSize` - size of generated data chunks (16K by default)
5332 * - `raw` (Boolean) - do raw inflate
5333 * - `to` (String) - if equal to 'string', then result will be converted
5334 *   from utf8 to utf16 (javascript) string. When string output requested,
5335 *   chunk length can differ from `chunkSize`, depending on content.
5336 *
5337 * By default, when no options set, autodetect deflate/gzip data format via
5338 * wrapper header.
5339 *
5340 * ##### Example:
5341 *
5342 * ```javascript
5343 * var pako = require('pako')
5344 *   , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
5345 *   , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
5346 *
5347 * var inflate = new pako.Inflate({ level: 3});
5348 *
5349 * inflate.push(chunk1, false);
5350 * inflate.push(chunk2, true);  // true -> last chunk
5351 *
5352 * if (inflate.err) { throw new Error(inflate.err); }
5353 *
5354 * console.log(inflate.result);
5355 * ```
5356 **/
5357var Inflate = function(options) {
5358
5359  this.options = utils.assign({
5360    chunkSize: 16384,
5361    windowBits: 0,
5362    to: ''
5363  }, options || {});
5364
5365  var opt = this.options;
5366
5367  // Force window size for `raw` data, if not set directly,
5368  // because we have no header for autodetect.
5369  if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
5370    opt.windowBits = -opt.windowBits;
5371    if (opt.windowBits === 0) { opt.windowBits = -15; }
5372  }
5373
5374  // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
5375  if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
5376      !(options && options.windowBits)) {
5377    opt.windowBits += 32;
5378  }
5379
5380  // Gzip header has no info about windows size, we can do autodetect only
5381  // for deflate. So, if window size not set, force it to max when gzip possible
5382  if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
5383    // bit 3 (16) -> gzipped data
5384    // bit 4 (32) -> autodetect gzip/deflate
5385    if ((opt.windowBits & 15) === 0) {
5386      opt.windowBits |= 15;
5387    }
5388  }
5389
5390  this.err    = 0;      // error code, if happens (0 = Z_OK)
5391  this.msg    = '';     // error message
5392  this.ended  = false;  // used to avoid multiple onEnd() calls
5393  this.chunks = [];     // chunks of compressed data
5394
5395  this.strm   = new zstream();
5396  this.strm.avail_out = 0;
5397
5398  var status  = zlib_inflate.inflateInit2(
5399    this.strm,
5400    opt.windowBits
5401  );
5402
5403  if (status !== c.Z_OK) {
5404    throw new Error(msg[status]);
5405  }
5406
5407  this.header = new gzheader();
5408
5409  zlib_inflate.inflateGetHeader(this.strm, this.header);
5410};
5411
5412/**
5413 * Inflate#push(data[, mode]) -> Boolean
5414 * - data (Uint8Array|Array|ArrayBuffer|String): input data
5415 * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
5416 *   See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
5417 *
5418 * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
5419 * new output chunks. Returns `true` on success. The last data block must have
5420 * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
5421 * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
5422 * can use mode Z_SYNC_FLUSH, keeping the decompression context.
5423 *
5424 * On fail call [[Inflate#onEnd]] with error code and return false.
5425 *
5426 * We strongly recommend to use `Uint8Array` on input for best speed (output
5427 * format is detected automatically). Also, don't skip last param and always
5428 * use the same type in your code (boolean or number). That will improve JS speed.
5429 *
5430 * For regular `Array`-s make sure all elements are [0..255].
5431 *
5432 * ##### Example
5433 *
5434 * ```javascript
5435 * push(chunk, false); // push one of data chunks
5436 * ...
5437 * push(chunk, true);  // push last chunk
5438 * ```
5439 **/
5440Inflate.prototype.push = function(data, mode) {
5441  var strm = this.strm;
5442  var chunkSize = this.options.chunkSize;
5443  var status, _mode;
5444  var next_out_utf8, tail, utf8str;
5445
5446  if (this.ended) { return false; }
5447  _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
5448
5449  // Convert data if needed
5450  if (typeof data === 'string') {
5451    // Only binary strings can be decompressed on practice
5452    strm.input = strings.binstring2buf(data);
5453  } else if (toString.call(data) === '[object ArrayBuffer]') {
5454    strm.input = new Uint8Array(data);
5455  } else {
5456    strm.input = data;
5457  }
5458
5459  strm.next_in = 0;
5460  strm.avail_in = strm.input.length;
5461
5462  do {
5463    if (strm.avail_out === 0) {
5464      strm.output = new utils.Buf8(chunkSize);
5465      strm.next_out = 0;
5466      strm.avail_out = chunkSize;
5467    }
5468
5469    status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH);    /* no bad return value */
5470
5471    if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
5472      this.onEnd(status);
5473      this.ended = true;
5474      return false;
5475    }
5476
5477    if (strm.next_out) {
5478      if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
5479
5480        if (this.options.to === 'string') {
5481
5482          next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
5483
5484          tail = strm.next_out - next_out_utf8;
5485          utf8str = strings.buf2string(strm.output, next_out_utf8);
5486
5487          // move tail
5488          strm.next_out = tail;
5489          strm.avail_out = chunkSize - tail;
5490          if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
5491
5492          this.onData(utf8str);
5493
5494        } else {
5495          this.onData(utils.shrinkBuf(strm.output, strm.next_out));
5496        }
5497      }
5498    }
5499  } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
5500
5501  if (status === c.Z_STREAM_END) {
5502    _mode = c.Z_FINISH;
5503  }
5504
5505  // Finalize on the last chunk.
5506  if (_mode === c.Z_FINISH) {
5507    status = zlib_inflate.inflateEnd(this.strm);
5508    this.onEnd(status);
5509    this.ended = true;
5510    return status === c.Z_OK;
5511  }
5512
5513  // callback interim results if Z_SYNC_FLUSH.
5514  if (_mode === c.Z_SYNC_FLUSH) {
5515    this.onEnd(c.Z_OK);
5516    strm.avail_out = 0;
5517    return true;
5518  }
5519
5520  return true;
5521};
5522
5523
5524/**
5525 * Inflate#onData(chunk) -> Void
5526 * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
5527 *   on js engine support. When string output requested, each chunk
5528 *   will be string.
5529 *
5530 * By default, stores data blocks in `chunks[]` property and glue
5531 * those in `onEnd`. Override this handler, if you need another behaviour.
5532 **/
5533Inflate.prototype.onData = function(chunk) {
5534  this.chunks.push(chunk);
5535};
5536
5537
5538/**
5539 * Inflate#onEnd(status) -> Void
5540 * - status (Number): inflate status. 0 (Z_OK) on success,
5541 *   other if not.
5542 *
5543 * Called either after you tell inflate that the input stream is
5544 * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
5545 * or if an error happened. By default - join collected chunks,
5546 * free memory and fill `results` / `err` properties.
5547 **/
5548Inflate.prototype.onEnd = function(status) {
5549  // On success - join
5550  if (status === c.Z_OK) {
5551    if (this.options.to === 'string') {
5552      // Glue & convert here, until we teach pako to send
5553      // utf8 alligned strings to onData
5554      this.result = this.chunks.join('');
5555    } else {
5556      this.result = utils.flattenChunks(this.chunks);
5557    }
5558  }
5559  this.chunks = [];
5560  this.err = status;
5561  this.msg = this.strm.msg;
5562};
5563
5564
5565/**
5566 * inflate(data[, options]) -> Uint8Array|Array|String
5567 * - data (Uint8Array|Array|String): input data to decompress.
5568 * - options (Object): zlib inflate options.
5569 *
5570 * Decompress `data` with inflate/ungzip and `options`. Autodetect
5571 * format via wrapper header by default. That's why we don't provide
5572 * separate `ungzip` method.
5573 *
5574 * Supported options are:
5575 *
5576 * - windowBits
5577 *
5578 * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
5579 * for more information.
5580 *
5581 * Sugar (options):
5582 *
5583 * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to 
vendor: 10,636 bytes, lines 5583-5992
5583specify
5584 *   negative windowBits implicitly.
5585 * - `to` (String) - if equal to 'string', then result will be converted
5586 *   from utf8 to utf16 (javascript) string. When string output requested,
5587 *   chunk length can differ from `chunkSize`, depending on content.
5588 *
5589 *
5590 * ##### Example:
5591 *
5592 * ```javascript
5593 * var pako = require('pako')
5594 *   , input = pako.deflate([1,2,3,4,5,6,7,8,9])
5595 *   , output;
5596 *
5597 * try {
5598 *   output = pako.inflate(input);
5599 * } catch (err)
5600 *   console.log(err);
5601 * }
5602 * ```
5603 **/
5604function inflate(input, options) {
5605  var inflator = new Inflate(options);
5606
5607  inflator.push(input, true);
5608
5609  // That will never happens, if you don't cheat with options :)
5610  if (inflator.err) { throw inflator.msg; }
5611
5612  return inflator.result;
5613}
5614
5615
5616/**
5617 * inflateRaw(data[, options]) -> Uint8Array|Array|String
5618 * - data (Uint8Array|Array|String): input data to decompress.
5619 * - options (Object): zlib inflate options.
5620 *
5621 * The same as [[inflate]], but creates raw data, without wrapper
5622 * (header and adler32 crc).
5623 **/
5624function inflateRaw(input, options) {
5625  options = options || {};
5626  options.raw = true;
5627  return inflate(input, options);
5628}
5629
5630
5631/**
5632 * ungzip(data[, options]) -> Uint8Array|Array|String
5633 * - data (Uint8Array|Array|String): input data to decompress.
5634 * - options (Object): zlib inflate options.
5635 *
5636 * Just shortcut to [[inflate]], because it autodetects format
5637 * by header.content. Done for convenience.
5638 **/
5639
5640
5641exports.Inflate = Inflate;
5642exports.inflate = inflate;
5643exports.inflateRaw = inflateRaw;
5644exports.ungzip  = inflate;
5645
5646},{"./utils/common":35,"./utils/strings":36,"./zlib/constants":38,"./zlib/gzheader":41,"./zlib/inflate.js":43,"./zlib/messages":45,"./zlib/zstream":47}],35:[function(require,module,exports){
5647'use strict';
5648
5649
5650var TYPED_OK =  (typeof Uint8Array !== 'undefined') &&
5651                (typeof Uint16Array !== 'undefined') &&
5652                (typeof Int32Array !== 'undefined');
5653
5654
5655exports.assign = function (obj /*from1, from2, from3, ...*/) {
5656  var sources = Array.prototype.slice.call(arguments, 1);
5657  while (sources.length) {
5658    var source = sources.shift();
5659    if (!source) { continue; }
5660
5661    if (typeof source !== 'object') {
5662      throw new TypeError(source + 'must be non-object');
5663    }
5664
5665    for (var p in source) {
5666      if (source.hasOwnProperty(p)) {
5667        obj[p] = source[p];
5668      }
5669    }
5670  }
5671
5672  return obj;
5673};
5674
5675
5676// reduce buffer size, avoiding mem copy
5677exports.shrinkBuf = function (buf, size) {
5678  if (buf.length === size) { return buf; }
5679  if (buf.subarray) { return buf.subarray(0, size); }
5680  buf.length = size;
5681  return buf;
5682};
5683
5684
5685var fnTyped = {
5686  arraySet: function (dest, src, src_offs, len, dest_offs) {
5687    if (src.subarray && dest.subarray) {
5688      dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
5689      return;
5690    }
5691    // Fallback to ordinary array
5692    for (var i=0; i<len; i++) {
5693      dest[dest_offs + i] = src[src_offs + i];
5694    }
5695  },
5696  // Join array of chunks to single array.
5697  flattenChunks: function(chunks) {
5698    var i, l, len, pos, chunk, result;
5699
5700    // calculate data length
5701    len = 0;
5702    for (i=0, l=chunks.length; i<l; i++) {
5703      len += chunks[i].length;
5704    }
5705
5706    // join chunks
5707    result = new Uint8Array(len);
5708    pos = 0;
5709    for (i=0, l=chunks.length; i<l; i++) {
5710      chunk = chunks[i];
5711      result.set(chunk, pos);
5712      pos += chunk.length;
5713    }
5714
5715    return result;
5716  }
5717};
5718
5719var fnUntyped = {
5720  arraySet: function (dest, src, src_offs, len, dest_offs) {
5721    for (var i=0; i<len; i++) {
5722      dest[dest_offs + i] = src[src_offs + i];
5723    }
5724  },
5725  // Join array of chunks to single array.
5726  flattenChunks: function(chunks) {
5727    return [].concat.apply([], chunks);
5728  }
5729};
5730
5731
5732// Enable/Disable typed arrays use, for testing
5733//
5734exports.setTyped = function (on) {
5735  if (on) {
5736    exports.Buf8  = Uint8Array;
5737    exports.Buf16 = Uint16Array;
5738    exports.Buf32 = Int32Array;
5739    exports.assign(exports, fnTyped);
5740  } else {
5741    exports.Buf8  = Array;
5742    exports.Buf16 = Array;
5743    exports.Buf32 = Array;
5744    exports.assign(exports, fnUntyped);
5745  }
5746};
5747
5748exports.setTyped(TYPED_OK);
5749
5750},{}],36:[function(require,module,exports){
5751// String encode/decode helpers
5752'use strict';
5753
5754
5755var utils = require('./common');
5756
5757
5758// Quick check if we can use fast array to bin string conversion
5759//
5760// - apply(Array) can fail on Android 2.2
5761// - apply(Uint8Array) can fail on iOS 5.1 Safary
5762//
5763var STR_APPLY_OK = true;
5764var STR_APPLY_UIA_OK = true;
5765
5766try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
5767try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
5768
5769
5770// Table with utf8 lengths (calculated by first byte of sequence)
5771// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
5772// because max possible codepoint is 0x10ffff
5773var _utf8len = new utils.Buf8(256);
5774for (var q=0; q<256; q++) {
5775  _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
5776}
5777_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
5778
5779
5780// convert string to array (typed, when possible)
5781exports.string2buf = function (str) {
5782  var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
5783
5784  // count binary size
5785  for (m_pos = 0; m_pos < str_len; m_pos++) {
5786    c = str.charCodeAt(m_pos);
5787    if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
5788      c2 = str.charCodeAt(m_pos+1);
5789      if ((c2 & 0xfc00) === 0xdc00) {
5790        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
5791        m_pos++;
5792      }
5793    }
5794    buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
5795  }
5796
5797  // allocate buffer
5798  buf = new utils.Buf8(buf_len);
5799
5800  // convert
5801  for (i=0, m_pos = 0; i < buf_len; m_pos++) {
5802    c = str.charCodeAt(m_pos);
5803    if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
5804      c2 = str.charCodeAt(m_pos+1);
5805      if ((c2 & 0xfc00) === 0xdc00) {
5806        c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
5807        m_pos++;
5808      }
5809    }
5810    if (c < 0x80) {
5811      /* one byte */
5812      buf[i++] = c;
5813    } else if (c < 0x800) {
5814      /* two bytes */
5815      buf[i++] = 0xC0 | (c >>> 6);
5816      buf[i++] = 0x80 | (c & 0x3f);
5817    } else if (c < 0x10000) {
5818      /* three bytes */
5819      buf[i++] = 0xE0 | (c >>> 12);
5820      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
5821      buf[i++] = 0x80 | (c & 0x3f);
5822    } else {
5823      /* four bytes */
5824      buf[i++] = 0xf0 | (c >>> 18);
5825      buf[i++] = 0x80 | (c >>> 12 & 0x3f);
5826      buf[i++] = 0x80 | (c >>> 6 & 0x3f);
5827      buf[i++] = 0x80 | (c & 0x3f);
5828    }
5829  }
5830
5831  return buf;
5832};
5833
5834// Helper (used in 2 places)
5835function buf2binstring(buf, len) {
5836  // use fallback for big arrays to avoid stack overflow
5837  if (len < 65537) {
5838    if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
5839      return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
5840    }
5841  }
5842
5843  var result = '';
5844  for (var i=0; i < len; i++) {
5845    result += String.fromCharCode(buf[i]);
5846  }
5847  return result;
5848}
5849
5850
5851// Convert byte array to binary string
5852exports.buf2binstring = function(buf) {
5853  return buf2binstring(buf, buf.length);
5854};
5855
5856
5857// Convert binary string (typed, when possible)
5858exports.binstring2buf = function(str) {
5859  var buf = new utils.Buf8(str.length);
5860  for (var i=0, len=buf.length; i < len; i++) {
5861    buf[i] = str.charCodeAt(i);
5862  }
5863  return buf;
5864};
5865
5866
5867// convert array to string
5868exports.buf2string = function (buf, max) {
5869  var i, out, c, c_len;
5870  var len = max || buf.length;
5871
5872  // Reserve max possible length (2 words per char)
5873  // NB: by unknown reasons, Array is significantly faster for
5874  //     String.fromCharCode.apply than Uint16Array.
5875  var utf16buf = new Array(len*2);
5876
5877  for (out=0, i=0; i<len;) {
5878    c = buf[i++];
5879    // quick process ascii
5880    if (c < 0x80) { utf16buf[out++] = c; continue; }
5881
5882    c_len = _utf8len[c];
5883    // skip 5 & 6 byte codes
5884    if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
5885
5886    // apply mask on first byte
5887    c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
5888    // join the rest
5889    while (c_len > 1 && i < len) {
5890      c = (c << 6) | (buf[i++] & 0x3f);
5891      c_len--;
5892    }
5893
5894    // terminated by end of string?
5895    if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
5896
5897    if (c < 0x10000) {
5898      utf16buf[out++] = c;
5899    } else {
5900      c -= 0x10000;
5901      utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
5902      utf16buf[out++] = 0xdc00 | (c & 0x3ff);
5903    }
5904  }
5905
5906  return buf2binstring(utf16buf, out);
5907};
5908
5909
5910// Calculate max possible position in utf8 buffer,
5911// that will not break sequence. If that's not possible
5912// - (very small limits) return max size as is.
5913//
5914// buf[] - utf8 bytes array
5915// max   - length limit (mandatory);
5916exports.utf8border = function(buf, max) {
5917  var pos;
5918
5919  max = max || buf.length;
5920  if (max > buf.length) { max = buf.length; }
5921
5922  // go back from last position, until start of sequence found
5923  pos = max-1;
5924  while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
5925
5926  // Fuckup - very small and broken sequence,
5927  // return max, because we should return something anyway.
5928  if (pos < 0) { return max; }
5929
5930  // If we came to start of buffer - that means vuffer is too small,
5931  // return max too.
5932  if (pos === 0) { return max; }
5933
5934  return (pos + _utf8len[buf[pos]] > max) ? pos : max;
5935};
5936
5937},{"./common":35}],37:[function(require,module,exports){
5938'use strict';
5939
5940// Note: adler32 takes 12% for level 0 and 2% for level 6.
5941// It doesn't worth to make additional optimizationa as in original.
5942// Small size is preferable.
5943
5944function adler32(adler, buf, len, pos) {
5945  var s1 = (adler & 0xffff) |0,
5946      s2 = ((adler >>> 16) & 0xffff) |0,
5947      n = 0;
5948
5949  while (len !== 0) {
5950    // Set limit ~ twice less than 5552, to keep
5951    // s2 in 31-bits, because we force signed ints.
5952    // in other case %= will fail.
5953    n = len > 2000 ? 2000 : len;
5954    len -= n;
5955
5956    do {
5957      s1 = (s1 + buf[pos++]) |0;
5958      s2 = (s2 + s1) |0;
5959    } while (--n);
5960
5961    s1 %= 65521;
5962    s2 %= 65521;
5963  }
5964
5965  return (s1 | (s2 << 16)) |0;
5966}
5967
5968
5969module.exports = adler32;
5970
5971},{}],38:[function(require,module,exports){
5972module.exports = {
5973
5974  /* Allowed flush values; see deflate() and inflate() below for details */
5975  Z_NO_FLUSH:         0,
5976  Z_PARTIAL_FLUSH:    1,
5977  Z_SYNC_FLUSH:       2,
5978  Z_FULL_FLUSH:       3,
5979  Z_FINISH:           4,
5980  Z_BLOCK:            5,
5981  Z_TREES:            6,
5982
5983  /* Return codes for the compression/decompression functions. Negative values
5984  * are errors, positive values are used for special but normal events.
5985  */
5986  Z_OK:               0,
5987  Z_STREAM_END:       1,
5988  Z_NEED_DICT:        2,
5989  Z_ERRNO:           -1,
5990  Z_STREAM_ERROR:    -2,
5991  Z_DATA_ERROR:      -3,
5992  //Z_MEM_ERROR:     -4,
vendor: 1,796 bytes, lines 5993-6070
5993  Z_BUF_ERROR:       -5,
5994  //Z_VERSION_ERROR: -6,
5995
5996  /* compression levels */
5997  Z_NO_COMPRESSION:         0,
5998  Z_BEST_SPEED:             1,
5999  Z_BEST_COMPRESSION:       9,
6000  Z_DEFAULT_COMPRESSION:   -1,
6001
6002
6003  Z_FILTERED:               1,
6004  Z_HUFFMAN_ONLY:           2,
6005  Z_RLE:                    3,
6006  Z_FIXED:                  4,
6007  Z_DEFAULT_STRATEGY:       0,
6008
6009  /* Possible values of the data_type field (though see inflate()) */
6010  Z_BINARY:                 0,
6011  Z_TEXT:                   1,
6012  //Z_ASCII:                1, // = Z_TEXT (deprecated)
6013  Z_UNKNOWN:                2,
6014
6015  /* The deflate compression method */
6016  Z_DEFLATED:               8
6017  //Z_NULL:                 null // Use -1 or null inline, depending on var type
6018};
6019
6020},{}],39:[function(require,module,exports){
6021'use strict';
6022
6023// Note: we can't get significant speed boost here.
6024// So write code to minimize size - no pregenerated tables
6025// and array tools dependencies.
6026
6027
6028// Use ordinary array, since untyped makes no boost here
6029function makeTable() {
6030  var c, table = [];
6031
6032  for (var n =0; n < 256; n++) {
6033    c = n;
6034    for (var k =0; k < 8; k++) {
6035      c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
6036    }
6037    table[n] = c;
6038  }
6039
6040  return table;
6041}
6042
6043// Create table on load. Just 255 signed longs. Not a problem.
6044var crcTable = makeTable();
6045
6046
6047function crc32(crc, buf, len, pos) {
6048  var t = crcTable,
6049      end = pos + len;
6050
6051  crc = crc ^ (-1);
6052
6053  for (var i = pos; i < end; i++) {
6054    crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
6055  }
6056
6057  return (crc ^ (-1)); // >>> 0;
6058}
6059
6060
6061module.exports = crc32;
6062
6063},{}],40:[function(require,module,exports){
6064'use strict';
6065
6066var utils   = require('../utils/common');
6067var trees   = require('./trees');
6068var adler32 = require('./adler32');
6069var crc32   = require('./crc32');
6070var msg   = require
vendor: 41,751 bytes, lines 6070-7283
6070('./messages');
6071
6072/* Public constants ==========================================================*/
6073/* ===========================================================================*/
6074
6075
6076/* Allowed flush values; see deflate() and inflate() below for details */
6077var Z_NO_FLUSH      = 0;
6078var Z_PARTIAL_FLUSH = 1;
6079//var Z_SYNC_FLUSH    = 2;
6080var Z_FULL_FLUSH    = 3;
6081var Z_FINISH        = 4;
6082var Z_BLOCK         = 5;
6083//var Z_TREES         = 6;
6084
6085
6086/* Return codes for the compression/decompression functions. Negative values
6087 * are errors, positive values are used for special but normal events.
6088 */
6089var Z_OK            = 0;
6090var Z_STREAM_END    = 1;
6091//var Z_NEED_DICT     = 2;
6092//var Z_ERRNO         = -1;
6093var Z_STREAM_ERROR  = -2;
6094var Z_DATA_ERROR    = -3;
6095//var Z_MEM_ERROR     = -4;
6096var Z_BUF_ERROR     = -5;
6097//var Z_VERSION_ERROR = -6;
6098
6099
6100/* compression levels */
6101//var Z_NO_COMPRESSION      = 0;
6102//var Z_BEST_SPEED          = 1;
6103//var Z_BEST_COMPRESSION    = 9;
6104var Z_DEFAULT_COMPRESSION = -1;
6105
6106
6107var Z_FILTERED            = 1;
6108var Z_HUFFMAN_ONLY        = 2;
6109var Z_RLE                 = 3;
6110var Z_FIXED               = 4;
6111var Z_DEFAULT_STRATEGY    = 0;
6112
6113/* Possible values of the data_type field (though see inflate()) */
6114//var Z_BINARY              = 0;
6115//var Z_TEXT                = 1;
6116//var Z_ASCII               = 1; // = Z_TEXT
6117var Z_UNKNOWN             = 2;
6118
6119
6120/* The deflate compression method */
6121var Z_DEFLATED  = 8;
6122
6123/*============================================================================*/
6124
6125
6126var MAX_MEM_LEVEL = 9;
6127/* Maximum value for memLevel in deflateInit2 */
6128var MAX_WBITS = 15;
6129/* 32K LZ77 window */
6130var DEF_MEM_LEVEL = 8;
6131
6132
6133var LENGTH_CODES  = 29;
6134/* number of length codes, not counting the special END_BLOCK code */
6135var LITERALS      = 256;
6136/* number of literal bytes 0..255 */
6137var L_CODES       = LITERALS + 1 + LENGTH_CODES;
6138/* number of Literal or Length codes, including the END_BLOCK code */
6139var D_CODES       = 30;
6140/* number of distance codes */
6141var BL_CODES      = 19;
6142/* number of codes used to transfer the bit lengths */
6143var HEAP_SIZE     = 2*L_CODES + 1;
6144/* maximum heap size */
6145var MAX_BITS  = 15;
6146/* All codes must not exceed MAX_BITS bits */
6147
6148var MIN_MATCH = 3;
6149var MAX_MATCH = 258;
6150var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
6151
6152var PRESET_DICT = 0x20;
6153
6154var INIT_STATE = 42;
6155var EXTRA_STATE = 69;
6156var NAME_STATE = 73;
6157var COMMENT_STATE = 91;
6158var HCRC_STATE = 103;
6159var BUSY_STATE = 113;
6160var FINISH_STATE = 666;
6161
6162var BS_NEED_MORE      = 1; /* block not completed, need more input or more output */
6163var BS_BLOCK_DONE     = 2; /* block flush performed */
6164var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
6165var BS_FINISH_DONE    = 4; /* finish done, accept no more input or output */
6166
6167var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
6168
6169function err(strm, errorCode) {
6170  strm.msg = msg[errorCode];
6171  return errorCode;
6172}
6173
6174function rank(f) {
6175  return ((f) << 1) - ((f) > 4 ? 9 : 0);
6176}
6177
6178function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
6179
6180
6181/* =========================================================================
6182 * Flush as much pending output as possible. All deflate() output goes
6183 * through this function so some applications may wish to modify it
6184 * to avoid allocating a large strm->output buffer and copying into it.
6185 * (See also read_buf()).
6186 */
6187function flush_pending(strm) {
6188  var s = strm.state;
6189
6190  //_tr_flush_bits(s);
6191  var len = s.pending;
6192  if (len > strm.avail_out) {
6193    len = strm.avail_out;
6194  }
6195  if (len === 0) { return; }
6196
6197  utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
6198  strm.next_out += len;
6199  s.pending_out += len;
6200  strm.total_out += len;
6201  strm.avail_out -= len;
6202  s.pending -= len;
6203  if (s.pending === 0) {
6204    s.pending_out = 0;
6205  }
6206}
6207
6208
6209function flush_block_only (s, last) {
6210  trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
6211  s.block_start = s.strstart;
6212  flush_pending(s.strm);
6213}
6214
6215
6216function put_byte(s, b) {
6217  s.pending_buf[s.pending++] = b;
6218}
6219
6220
6221/* =========================================================================
6222 * Put a short in the pending buffer. The 16-bit value is put in MSB order.
6223 * IN assertion: the stream state is correct and there is enough room in
6224 * pending_buf.
6225 */
6226function putShortMSB(s, b) {
6227//  put_byte(s, (Byte)(b >> 8));
6228//  put_byte(s, (Byte)(b & 0xff));
6229  s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
6230  s.pending_buf[s.pending++] = b & 0xff;
6231}
6232
6233
6234/* ===========================================================================
6235 * Read a new buffer from the current input stream, update the adler32
6236 * and total number of bytes read.  All deflate() input goes through
6237 * this function so some applications may wish to modify it to avoid
6238 * allocating a large strm->input buffer and copying from it.
6239 * (See also flush_pending()).
6240 */
6241function read_buf(strm, buf, start, size) {
6242  var len = strm.avail_in;
6243
6244  if (len > size) { len = size; }
6245  if (len === 0) { return 0; }
6246
6247  strm.avail_in -= len;
6248
6249  utils.arraySet(buf, strm.input, strm.next_in, len, start);
6250  if (strm.state.wrap === 1) {
6251    strm.adler = adler32(strm.adler, buf, len, start);
6252  }
6253
6254  else if (strm.state.wrap === 2) {
6255    strm.adler = crc32(strm.adler, buf, len, start);
6256  }
6257
6258  strm.next_in += len;
6259  strm.total_in += len;
6260
6261  return len;
6262}
6263
6264
6265/* ===========================================================================
6266 * Set match_start to the longest match starting at the given string and
6267 * return its length. Matches shorter or equal to prev_length are discarded,
6268 * in which case the result is equal to prev_length and match_start is
6269 * garbage.
6270 * IN assertions: cur_match is the head of the hash chain for the current
6271 *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
6272 * OUT assertion: the match length is not greater than s->lookahead.
6273 */
6274function longest_match(s, cur_match) {
6275  var chain_length = s.max_chain_length;      /* max hash chain length */
6276  var scan = s.strstart; /* current string */
6277  var match;                       /* matched string */
6278  var len;                           /* length of current match */
6279  var best_len = s.prev_length;              /* best match length so far */
6280  var nice_match = s.nice_match;             /* stop if match long enough */
6281  var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
6282      s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
6283
6284  var _win = s.window; // shortcut
6285
6286  var wmask = s.w_mask;
6287  var prev  = s.prev;
6288
6289  /* Stop when cur_match becomes <= limit. To simplify the code,
6290   * we prevent matches with the string of window index 0.
6291   */
6292
6293  var strend = s.strstart + MAX_MATCH;
6294  var scan_end1  = _win[scan + best_len - 1];
6295  var scan_end   = _win[scan + best_len];
6296
6297  /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
6298   * It is easy to get rid of this optimization if necessary.
6299   */
6300  // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
6301
6302  /* Do not waste too much time if we already have a good match: */
6303  if (s.prev_length >= s.good_match) {
6304    chain_length >>= 2;
6305  }
6306  /* Do not look for matches beyond the end of the input. This is necessary
6307   * to make deflate deterministic.
6308   */
6309  if (nice_match > s.lookahead) { nice_match = s.lookahead; }
6310
6311  // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
6312
6313  do {
6314    // Assert(cur_match < s->strstart, "no future");
6315    match = cur_match;
6316
6317    /* Skip to next match if the match length cannot increase
6318     * or if the match length is less than 2.  Note that the checks below
6319     * for insufficient lookahead only occur occasionally for performance
6320     * reasons.  Therefore uninitialized memory will be accessed, and
6321     * conditional jumps will be made that depend on those values.
6322     * However the length of the match is limited to the lookahead, so
6323     * the output of deflate is not affected by the uninitialized values.
6324     */
6325
6326    if (_win[match + best_len]     !== scan_end  ||
6327        _win[match + best_len - 1] !== scan_end1 ||
6328        _win[match]                !== _win[scan] ||
6329        _win[++match]              !== _win[scan + 1]) {
6330      continue;
6331    }
6332
6333    /* The check at best_len-1 can be removed because it will be made
6334     * again later. (This heuristic is not always a win.)
6335     * It is not necessary to compare scan[2] and match[2] since they
6336     * are always equal when the other bytes match, given that
6337     * the hash keys are equal and that HASH_BITS >= 8.
6338     */
6339    scan += 2;
6340    match++;
6341    // Assert(*scan == *match, "match[2]?");
6342
6343    /* We check for insufficient lookahead only every 8th comparison;
6344     * the 256th check will be made at strstart+258.
6345     */
6346    do {
6347      /*jshint noempty:false*/
6348    } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6349             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6350             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6351             _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
6352             scan < strend);
6353
6354    // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
6355
6356    len = MAX_MATCH - (strend - scan);
6357    scan = strend - MAX_MATCH;
6358
6359    if (len > best_len) {
6360      s.match_start = cur_match;
6361      best_len = len;
6362      if (len >= nice_match) {
6363        break;
6364      }
6365      scan_end1  = _win[scan + best_len - 1];
6366      scan_end   = _win[scan + best_len];
6367    }
6368  } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
6369
6370  if (best_len <= s.lookahead) {
6371    return best_len;
6372  }
6373  return s.lookahead;
6374}
6375
6376
6377/* ===========================================================================
6378 * Fill the window when the lookahead becomes insufficient.
6379 * Updates strstart and lookahead.
6380 *
6381 * IN assertion: lookahead < MIN_LOOKAHEAD
6382 * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
6383 *    At least one byte has been read, or avail_in == 0; reads are
6384 *    performed for at least two bytes (required for the zip translate_eol
6385 *    option -- not supported here).
6386 */
6387function fill_window(s) {
6388  var _w_size = s.w_size;
6389  var p, n, m, more, str;
6390
6391  //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
6392
6393  do {
6394    more = s.window_size - s.lookahead - s.strstart;
6395
6396    // JS ints have 32 bit, block below not needed
6397    /* Deal with !@#$% 64K limit: */
6398    //if (sizeof(int) <= 2) {
6399    //    if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
6400    //        more = wsize;
6401    //
6402    //  } else if (more == (unsigned)(-1)) {
6403    //        /* Very unlikely, but possible on 16 bit machine if
6404    //         * strstart == 0 && lookahead == 1 (input done a byte at time)
6405    //         */
6406    //        more--;
6407    //    }
6408    //}
6409
6410
6411    /* If the window is almost full and there is insufficient lookahead,
6412     * move the upper half to the lower one to make room in the upper half.
6413     */
6414    if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
6415
6416      utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
6417      s.match_start -= _w_size;
6418      s.strstart -= _w_size;
6419      /* we now have strstart >= MAX_DIST */
6420      s.block_start -= _w_size;
6421
6422      /* Slide the hash table (could be avoided with 32 bit values
6423       at the expense of memory usage). We slide even when level == 0
6424       to keep the hash table consistent if we switch back to level > 0
6425       later. (Using level 0 permanently is not an optimal usage of
6426       zlib, so we don't care about this pathological case.)
6427       */
6428
6429      n = s.hash_size;
6430      p = n;
6431      do {
6432        m = s.head[--p];
6433        s.head[p] = (m >= _w_size ? m - _w_size : 0);
6434      } while (--n);
6435
6436      n = _w_size;
6437      p = n;
6438      do {
6439        m = s.prev[--p];
6440        s.prev[p] = (m >= _w_size ? m - _w_size : 0);
6441        /* If n is not on any hash chain, prev[n] is garbage but
6442         * its value will never be used.
6443         */
6444      } while (--n);
6445
6446      more += _w_size;
6447    }
6448    if (s.strm.avail_in === 0) {
6449      break;
6450    }
6451
6452    /* If there was no sliding:
6453     *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
6454     *    more == window_size - lookahead - strstart
6455     * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
6456     * => more >= window_size - 2*WSIZE + 2
6457     * In the BIG_MEM or MMAP case (not yet supported),
6458     *   window_size == input_size + MIN_LOOKAHEAD  &&
6459     *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
6460     * Otherwise, window_size == 2*WSIZE so more >= 2.
6461     * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
6462     */
6463    //Assert(more >= 2, "more < 2");
6464    n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
6465    s.lookahead += n;
6466
6467    /* Initialize the hash value now that we have some input: */
6468    if (s.lookahead + s.insert >= MIN_MATCH) {
6469      str = s.strstart - s.insert;
6470      s.ins_h = s.window[str];
6471
6472      /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
6473      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
6474//#if MIN_MATCH != 3
6475//        Call update_hash() MIN_MATCH-3 more times
6476//#endif
6477      while (s.insert) {
6478        /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
6479        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
6480
6481        s.prev[str & s.w_mask] = s.head[s.ins_h];
6482        s.head[s.ins_h] = str;
6483        str++;
6484        s.insert--;
6485        if (s.lookahead + s.insert < MIN_MATCH) {
6486          break;
6487        }
6488      }
6489    }
6490    /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
6491     * but this is not important since only literal bytes will be emitted.
6492     */
6493
6494  } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
6495
6496  /* If the WIN_INIT bytes after the end of the current data have never been
6497   * written, then zero those bytes in order to avoid memory check reports of
6498   * the use of uninitialized (or uninitialised as Julian writes) bytes by
6499   * the longest match routines.  Update the high water mark for the next
6500   * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
6501   * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
6502   */
6503//  if (s.high_water < s.window_size) {
6504//    var curr = s.strstart + s.lookahead;
6505//    var init = 0;
6506//
6507//    if (s.high_water < curr) {
6508//      /* Previous high water mark below current data -- zero WIN_INIT
6509//       * bytes or up to end of window, whichever is less.
6510//       */
6511//      init = s.window_size - curr;
6512//      if (init > WIN_INIT)
6513//        init = WIN_INIT;
6514//      zmemzero(s->window + curr, (unsigned)init);
6515//      s->high_water = curr + init;
6516//    }
6517//    else if (s->high_water < (ulg)curr + WIN_INIT) {
6518//      /* High water mark at or above current data, but below current data
6519//       * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
6520//       * to end of window, whichever is less.
6521//       */
6522//      init = (ulg)curr + WIN_INIT - s->high_water;
6523//      if (init > s->window_size - s->high_water)
6524//        init = s->window_size - s->high_water;
6525//      zmemzero(s->window + s->high_water, (unsigned)init);
6526//      s->high_water += init;
6527//    }
6528//  }
6529//
6530//  Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
6531//    "not enough room for search");
6532}
6533
6534/* ===========================================================================
6535 * Copy without compression as much as possible from the input stream, return
6536 * the current block state.
6537 * This function does not insert new strings in the dictionary since
6538 * uncompressible data is probably not useful. This function is used
6539 * only for the level=0 compression option.
6540 * NOTE: this function should be optimized to avoid extra copying from
6541 * window to pending_buf.
6542 */
6543function deflate_stored(s, flush) {
6544  /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
6545   * to pending_buf_size, and each stored block has a 5 byte header:
6546   */
6547  var max_block_size = 0xffff;
6548
6549  if (max_block_size > s.pending_buf_size - 5) {
6550    max_block_size = s.pending_buf_size - 5;
6551  }
6552
6553  /* Copy as much as possible from input to output: */
6554  for (;;) {
6555    /* Fill the window as much as possible: */
6556    if (s.lookahead <= 1) {
6557
6558      //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
6559      //  s->block_start >= (long)s->w_size, "slide too late");
6560//      if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
6561//        s.block_start >= s.w_size)) {
6562//        throw  new Error("slide too late");
6563//      }
6564
6565      fill_window(s);
6566      if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
6567        return BS_NEED_MORE;
6568      }
6569
6570      if (s.lookahead === 0) {
6571        break;
6572      }
6573      /* flush the current block */
6574    }
6575    //Assert(s->block_start >= 0L, "block gone");
6576//    if (s.block_start < 0) throw new Error("block gone");
6577
6578    s.strstart += s.lookahead;
6579    s.lookahead = 0;
6580
6581    /* Emit a stored block if pending_buf will be full: */
6582    var max_start = s.block_start + max_block_size;
6583
6584    if (s.strstart === 0 || s.strstart >= max_start) {
6585      /* strstart == 0 is possible when wraparound on 16-bit machine */
6586      s.lookahead = s.strstart - max_start;
6587      s.strstart = max_start;
6588      /*** FLUSH_BLOCK(s, 0); ***/
6589      flush_block_only(s, false);
6590      if (s.strm.avail_out === 0) {
6591        return BS_NEED_MORE;
6592      }
6593      /***/
6594
6595
6596    }
6597    /* Flush if we may have to slide, otherwise block_start may become
6598     * negative and the data will be gone:
6599     */
6600    if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
6601      /*** FLUSH_BLOCK(s, 0); ***/
6602      flush_block_only(s, false);
6603      if (s.strm.avail_out === 0) {
6604        return BS_NEED_MORE;
6605      }
6606      /***/
6607    }
6608  }
6609
6610  s.insert = 0;
6611
6612  if (flush === Z_FINISH) {
6613    /*** FLUSH_BLOCK(s, 1); ***/
6614    flush_block_only(s, true);
6615    if (s.strm.avail_out === 0) {
6616      return BS_FINISH_STARTED;
6617    }
6618    /***/
6619    return BS_FINISH_DONE;
6620  }
6621
6622  if (s.strstart > s.block_start) {
6623    /*** FLUSH_BLOCK(s, 0); ***/
6624    flush_block_only(s, false);
6625    if (s.strm.avail_out === 0) {
6626      return BS_NEED_MORE;
6627    }
6628    /***/
6629  }
6630
6631  return BS_NEED_MORE;
6632}
6633
6634/* ===========================================================================
6635 * Compress as much as possible from the input stream, return the current
6636 * block state.
6637 * This function does not perform lazy evaluation of matches and inserts
6638 * new strings in the dictionary only for unmatched strings or for short
6639 * matches. It is used only for the fast compression options.
6640 */
6641function deflate_fast(s, flush) {
6642  var hash_head;        /* head of the hash chain */
6643  var bflush;           /* set if current block must be flushed */
6644
6645  for (;;) {
6646    /* Make sure that we always have enough lookahead, except
6647     * at the end of the input file. We need MAX_MATCH bytes
6648     * for the next match, plus MIN_MATCH bytes to insert the
6649     * string following the next match.
6650     */
6651    if (s.lookahead < MIN_LOOKAHEAD) {
6652      fill_window(s);
6653      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
6654        return BS_NEED_MORE;
6655      }
6656      if (s.lookahead === 0) {
6657        break; /* flush the current block */
6658      }
6659    }
6660
6661    /* Insert the string window[strstart .. strstart+2] in the
6662     * dictionary, and set hash_head to the head of the hash chain:
6663     */
6664    hash_head = 0/*NIL*/;
6665    if (s.lookahead >= MIN_MATCH) {
6666      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6667      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6668      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6669      s.head[s.ins_h] = s.strstart;
6670      /***/
6671    }
6672
6673    /* Find the longest match, discarding those <= prev_length.
6674     * At this point we have always match_length < MIN_MATCH
6675     */
6676    if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
6677      /* To simplify the code, we prevent matches with the string
6678       * of window index 0 (in particular we have to avoid a match
6679       * of the string with itself at the start of the input file).
6680       */
6681      s.match_length = longest_match(s, hash_head);
6682      /* longest_match() sets match_start */
6683    }
6684    if (s.match_length >= MIN_MATCH) {
6685      // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
6686
6687      /*** _tr_tally_dist(s, s.strstart - s.match_start,
6688                     s.match_length - MIN_MATCH, bflush); ***/
6689      bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
6690
6691      s.lookahead -= s.match_length;
6692
6693      /* Insert new strings in the hash table only if the match length
6694       * is not too large. This saves time but degrades compression.
6695       */
6696      if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
6697        s.match_length--; /* string at strstart already in table */
6698        do {
6699          s.strstart++;
6700          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6701          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6702          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6703          s.head[s.ins_h] = s.strstart;
6704          /***/
6705          /* strstart never exceeds WSIZE-MAX_MATCH, so there are
6706           * always MIN_MATCH bytes ahead.
6707           */
6708        } while (--s.match_length !== 0);
6709        s.strstart++;
6710      } else
6711      {
6712        s.strstart += s.match_length;
6713        s.match_length = 0;
6714        s.ins_h = s.window[s.strstart];
6715        /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
6716        s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
6717
6718//#if MIN_MATCH != 3
6719//                Call UPDATE_HASH() MIN_MATCH-3 more times
6720//#endif
6721        /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
6722         * matter since it will be recomputed at next deflate call.
6723         */
6724      }
6725    } else {
6726      /* No match, output a literal byte */
6727      //Tracevv((stderr,"%c", s.window[s.strstart]));
6728      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6729      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6730
6731      s.lookahead--;
6732      s.strstart++;
6733    }
6734    if (bflush) {
6735      /*** FLUSH_BLOCK(s, 0); ***/
6736      flush_block_only(s, false);
6737      if (s.strm.avail_out === 0) {
6738        return BS_NEED_MORE;
6739      }
6740      /***/
6741    }
6742  }
6743  s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
6744  if (flush === Z_FINISH) {
6745    /*** FLUSH_BLOCK(s, 1); ***/
6746    flush_block_only(s, true);
6747    if (s.strm.avail_out === 0) {
6748      return BS_FINISH_STARTED;
6749    }
6750    /***/
6751    return BS_FINISH_DONE;
6752  }
6753  if (s.last_lit) {
6754    /*** FLUSH_BLOCK(s, 0); ***/
6755    flush_block_only(s, false);
6756    if (s.strm.avail_out === 0) {
6757      return BS_NEED_MORE;
6758    }
6759    /***/
6760  }
6761  return BS_BLOCK_DONE;
6762}
6763
6764/* ===========================================================================
6765 * Same as above, but achieves better compression. We use a lazy
6766 * evaluation for matches: a match is finally adopted only if there is
6767 * no better match at the next window position.
6768 */
6769function deflate_slow(s, flush) {
6770  var hash_head;          /* head of hash chain */
6771  var bflush;              /* set if current block must be flushed */
6772
6773  var max_insert;
6774
6775  /* Process the input block. */
6776  for (;;) {
6777    /* Make sure that we always have enough lookahead, except
6778     * at the end of the input file. We need MAX_MATCH bytes
6779     * for the next match, plus MIN_MATCH bytes to insert the
6780     * string following the next match.
6781     */
6782    if (s.lookahead < MIN_LOOKAHEAD) {
6783      fill_window(s);
6784      if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
6785        return BS_NEED_MORE;
6786      }
6787      if (s.lookahead === 0) { break; } /* flush the current block */
6788    }
6789
6790    /* Insert the string window[strstart .. strstart+2] in the
6791     * dictionary, and set hash_head to the head of the hash chain:
6792     */
6793    hash_head = 0/*NIL*/;
6794    if (s.lookahead >= MIN_MATCH) {
6795      /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6796      s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6797      hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6798      s.head[s.ins_h] = s.strstart;
6799      /***/
6800    }
6801
6802    /* Find the longest match, discarding those <= prev_length.
6803     */
6804    s.prev_length = s.match_length;
6805    s.prev_match = s.match_start;
6806    s.match_length = MIN_MATCH-1;
6807
6808    if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
6809        s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
6810      /* To simplify the code, we prevent matches with the string
6811       * of window index 0 (in particular we have to avoid a match
6812       * of the string with itself at the start of the input file).
6813       */
6814      s.match_length = longest_match(s, hash_head);
6815      /* longest_match() sets match_start */
6816
6817      if (s.match_length <= 5 &&
6818         (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
6819
6820        /* If prev_match is also MIN_MATCH, match_start is garbage
6821         * but we will ignore the current match anyway.
6822         */
6823        s.match_length = MIN_MATCH-1;
6824      }
6825    }
6826    /* If there was a match at the previous step and the current
6827     * match is not better, output the previous match:
6828     */
6829    if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
6830      max_insert = s.strstart + s.lookahead - MIN_MATCH;
6831      /* Do not insert strings in hash table beyond this. */
6832
6833      //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
6834
6835      /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
6836                     s.prev_length - MIN_MATCH, bflush);***/
6837      bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
6838      /* Insert in hash table all strings up to the end of the match.
6839       * strstart-1 and strstart are already inserted. If there is not
6840       * enough lookahead, the last two strings are not inserted in
6841       * the hash table.
6842       */
6843      s.lookahead -= s.prev_length-1;
6844      s.prev_length -= 2;
6845      do {
6846        if (++s.strstart <= max_insert) {
6847          /*** INSERT_STRING(s, s.strstart, hash_head); ***/
6848          s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
6849          hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
6850          s.head[s.ins_h] = s.strstart;
6851          /***/
6852        }
6853      } while (--s.prev_length !== 0);
6854      s.match_available = 0;
6855      s.match_length = MIN_MATCH-1;
6856      s.strstart++;
6857
6858      if (bflush) {
6859        /*** FLUSH_BLOCK(s, 0); ***/
6860        flush_block_only(s, false);
6861        if (s.strm.avail_out === 0) {
6862          return BS_NEED_MORE;
6863        }
6864        /***/
6865      }
6866
6867    } else if (s.match_available) {
6868      /* If there was no match at the previous position, output a
6869       * single literal. If there was a match but the current match
6870       * is longer, truncate the previous match to a single literal.
6871       */
6872      //Tracevv((stderr,"%c", s->window[s->strstart-1]));
6873      /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
6874      bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
6875
6876      if (bflush) {
6877        /*** FLUSH_BLOCK_ONLY(s, 0) ***/
6878        flush_block_only(s, false);
6879        /***/
6880      }
6881      s.strstart++;
6882      s.lookahead--;
6883      if (s.strm.avail_out === 0) {
6884        return BS_NEED_MORE;
6885      }
6886    } else {
6887      /* There is no previous match to compare with, wait for
6888       * the next step to decide.
6889       */
6890      s.match_available = 1;
6891      s.strstart++;
6892      s.lookahead--;
6893    }
6894  }
6895  //Assert (flush != Z_NO_FLUSH, "no flush?");
6896  if (s.match_available) {
6897    //Tracevv((stderr,"%c", s->window[s->strstart-1]));
6898    /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
6899    bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
6900
6901    s.match_available = 0;
6902  }
6903  s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
6904  if (flush === Z_FINISH) {
6905    /*** FLUSH_BLOCK(s, 1); ***/
6906    flush_block_only(s, true);
6907    if (s.strm.avail_out === 0) {
6908      return BS_FINISH_STARTED;
6909    }
6910    /***/
6911    return BS_FINISH_DONE;
6912  }
6913  if (s.last_lit) {
6914    /*** FLUSH_BLOCK(s, 0); ***/
6915    flush_block_only(s, false);
6916    if (s.strm.avail_out === 0) {
6917      return BS_NEED_MORE;
6918    }
6919    /***/
6920  }
6921
6922  return BS_BLOCK_DONE;
6923}
6924
6925
6926/* ===========================================================================
6927 * For Z_RLE, simply look for runs of bytes, generate matches only of distance
6928 * one.  Do not maintain a hash table.  (It will be regenerated if this run of
6929 * deflate switches away from Z_RLE.)
6930 */
6931function deflate_rle(s, flush) {
6932  var bflush;            /* set if current block must be flushed */
6933  var prev;              /* byte at distance one to match */
6934  var scan, strend;      /* scan goes up to strend for length of run */
6935
6936  var _win = s.window;
6937
6938  for (;;) {
6939    /* Make sure that we always have enough lookahead, except
6940     * at the end of the input file. We need MAX_MATCH bytes
6941     * for the longest run, plus one for the unrolled loop.
6942     */
6943    if (s.lookahead <= MAX_MATCH) {
6944      fill_window(s);
6945      if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
6946        return BS_NEED_MORE;
6947      }
6948      if (s.lookahead === 0) { break; } /* flush the current block */
6949    }
6950
6951    /* See how many times the previous byte repeats */
6952    s.match_length = 0;
6953    if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
6954      scan = s.strstart - 1;
6955      prev = _win[scan];
6956      if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
6957        strend = s.strstart + MAX_MATCH;
6958        do {
6959          /*jshint noempty:false*/
6960        } while (prev === _win[++scan] && prev === _win[++scan] &&
6961                 prev === _win[++scan] && prev === _win[++scan] &&
6962                 prev === _win[++scan] && prev === _win[++scan] &&
6963                 prev === _win[++scan] && prev === _win[++scan] &&
6964                 scan < strend);
6965        s.match_length = MAX_MATCH - (strend - scan);
6966        if (s.match_length > s.lookahead) {
6967          s.match_length = s.lookahead;
6968        }
6969      }
6970      //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
6971    }
6972
6973    /* Emit match if have run of MIN_MATCH or longer, else emit literal */
6974    if (s.match_length >= MIN_MATCH) {
6975      //check_match(s, s.strstart, s.strstart - 1, s.match_length);
6976
6977      /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
6978      bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
6979
6980      s.lookahead -= s.match_length;
6981      s.strstart += s.match_length;
6982      s.match_length = 0;
6983    } else {
6984      /* No match, output a literal byte */
6985      //Tracevv((stderr,"%c", s->window[s->strstart]));
6986      /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
6987      bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
6988
6989      s.lookahead--;
6990      s.strstart++;
6991    }
6992    if (bflush) {
6993      /*** FLUSH_BLOCK(s, 0); ***/
6994      flush_block_only(s, false);
6995      if (s.strm.avail_out === 0) {
6996        return BS_NEED_MORE;
6997      }
6998      /***/
6999    }
7000  }
7001  s.insert = 0;
7002  if (flush === Z_FINISH) {
7003    /*** FLUSH_BLOCK(s, 1); ***/
7004    flush_block_only(s, true);
7005    if (s.strm.avail_out === 0) {
7006      return BS_FINISH_STARTED;
7007    }
7008    /***/
7009    return BS_FINISH_DONE;
7010  }
7011  if (s.last_lit) {
7012    /*** FLUSH_BLOCK(s, 0); ***/
7013    flush_block_only(s, false);
7014    if (s.strm.avail_out === 0) {
7015      return BS_NEED_MORE;
7016    }
7017    /***/
7018  }
7019  return BS_BLOCK_DONE;
7020}
7021
7022/* ===========================================================================
7023 * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
7024 * (It will be regenerated if this run of deflate switches away from Huffman.)
7025 */
7026function deflate_huff(s, flush) {
7027  var bflush;             /* set if current block must be flushed */
7028
7029  for (;;) {
7030    /* Make sure that we have a literal to write. */
7031    if (s.lookahead === 0) {
7032      fill_window(s);
7033      if (s.lookahead === 0) {
7034        if (flush === Z_NO_FLUSH) {
7035          return BS_NEED_MORE;
7036        }
7037        break;      /* flush the current block */
7038      }
7039    }
7040
7041    /* Output a literal byte */
7042    s.match_length = 0;
7043    //Tracevv((stderr,"%c", s->window[s->strstart]));
7044    /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
7045    bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
7046    s.lookahead--;
7047    s.strstart++;
7048    if (bflush) {
7049      /*** FLUSH_BLOCK(s, 0); ***/
7050      flush_block_only(s, false);
7051      if (s.strm.avail_out === 0) {
7052        return BS_NEED_MORE;
7053      }
7054      /***/
7055    }
7056  }
7057  s.insert = 0;
7058  if (flush === Z_FINISH) {
7059    /*** FLUSH_BLOCK(s, 1); ***/
7060    flush_block_only(s, true);
7061    if (s.strm.avail_out === 0) {
7062      return BS_FINISH_STARTED;
7063    }
7064    /***/
7065    return BS_FINISH_DONE;
7066  }
7067  if (s.last_lit) {
7068    /*** FLUSH_BLOCK(s, 0); ***/
7069    flush_block_only(s, false);
7070    if (s.strm.avail_out === 0) {
7071      return BS_NEED_MORE;
7072    }
7073    /***/
7074  }
7075  return BS_BLOCK_DONE;
7076}
7077
7078/* Values for max_lazy_match, good_match and max_chain_length, depending on
7079 * the desired pack level (0..9). The values given below have been tuned to
7080 * exclude worst case performance for pathological files. Better values may be
7081 * found for specific files.
7082 */
7083var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
7084  this.good_length = good_length;
7085  this.max_lazy = max_lazy;
7086  this.nice_length = nice_length;
7087  this.max_chain = max_chain;
7088  this.func = func;
7089};
7090
7091var configuration_table;
7092
7093configuration_table = [
7094  /*      good lazy nice chain */
7095  new Config(0, 0, 0, 0, deflate_stored),          /* 0 store only */
7096  new Config(4, 4, 8, 4, deflate_fast),            /* 1 max speed, no lazy matches */
7097  new Config(4, 5, 16, 8, deflate_fast),           /* 2 */
7098  new Config(4, 6, 32, 32, deflate_fast),          /* 3 */
7099
7100  new Config(4, 4, 16, 16, deflate_slow),          /* 4 lazy matches */
7101  new Config(8, 16, 32, 32, deflate_slow),         /* 5 */
7102  new Config(8, 16, 128, 128, deflate_slow),       /* 6 */
7103  new Config(8, 32, 128, 256, deflate_slow),       /* 7 */
7104  new Config(32, 128, 258, 1024, deflate_slow),    /* 8 */
7105  new Config(32, 258, 258, 4096, deflate_slow)     /* 9 max compression */
7106];
7107
7108
7109/* ===========================================================================
7110 * Initialize the "longest match" routines for a new zlib stream
7111 */
7112function lm_init(s) {
7113  s.window_size = 2 * s.w_size;
7114
7115  /*** CLEAR_HASH(s); ***/
7116  zero(s.head); // Fill with NIL (= 0);
7117
7118  /* Set the default configuration parameters:
7119   */
7120  s.max_lazy_match = configuration_table[s.level].max_lazy;
7121  s.good_match = configuration_table[s.level].good_length;
7122  s.nice_match = configuration_table[s.level].nice_length;
7123  s.max_chain_length = configuration_table[s.level].max_chain;
7124
7125  s.strstart = 0;
7126  s.block_start = 0;
7127  s.lookahead = 0;
7128  s.insert = 0;
7129  s.match_length = s.prev_length = MIN_MATCH - 1;
7130  s.match_available = 0;
7131  s.ins_h = 0;
7132}
7133
7134
7135function DeflateState() {
7136  this.strm = null;            /* pointer back to this zlib stream */
7137  this.status = 0;            /* as the name implies */
7138  this.pending_buf = null;      /* output still pending */
7139  this.pending_buf_size = 0;  /* size of pending_buf */
7140  this.pending_out = 0;       /* next pending byte to output to the stream */
7141  this.pending = 0;           /* nb of bytes in the pending buffer */
7142  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
7143  this.gzhead = null;         /* gzip header information to write */
7144  this.gzindex = 0;           /* where in extra, name, or comment */
7145  this.method = Z_DEFLATED; /* can only be DEFLATED */
7146  this.last_flush = -1;   /* value of flush param for previous deflate call */
7147
7148  this.w_size = 0;  /* LZ77 window size (32K by default) */
7149  this.w_bits = 0;  /* log2(w_size)  (8..16) */
7150  this.w_mask = 0;  /* w_size - 1 */
7151
7152  this.window = null;
7153  /* Sliding window. Input bytes are read into the second half of the window,
7154   * and move to the first half later to keep a dictionary of at least wSize
7155   * bytes. With this organization, matches are limited to a distance of
7156   * wSize-MAX_MATCH bytes, but this ensures that IO is always
7157   * performed with a length multiple of the block size.
7158   */
7159
7160  this.window_size = 0;
7161  /* Actual size of window: 2*wSize, except when the user input buffer
7162   * is directly used as sliding window.
7163   */
7164
7165  this.prev = null;
7166  /* Link to older string with same hash index. To limit the size of this
7167   * array to 64K, this link is maintained only for the last 32K strings.
7168   * An index in this array is thus a window index modulo 32K.
7169   */
7170
7171  this.head = null;   /* Heads of the hash chains or NIL. */
7172
7173  this.ins_h = 0;       /* hash index of string to be inserted */
7174  this.hash_size = 0;   /* number of elements in hash table */
7175  this.hash_bits = 0;   /* log2(hash_size) */
7176  this.hash_mask = 0;   /* hash_size-1 */
7177
7178  this.hash_shift = 0;
7179  /* Number of bits by which ins_h must be shifted at each input
7180   * step. It must be such that after MIN_MATCH steps, the oldest
7181   * byte no longer takes part in the hash key, that is:
7182   *   hash_shift * MIN_MATCH >= hash_bits
7183   */
7184
7185  this.block_start = 0;
7186  /* Window position at the beginning of the current output block. Gets
7187   * negative when the window is moved backwards.
7188   */
7189
7190  this.match_length = 0;      /* length of best match */
7191  this.prev_match = 0;        /* previous match */
7192  this.match_available = 0;   /* set if previous match exists */
7193  this.strstart = 0;          /* start of string to insert */
7194  this.match_start = 0;       /* start of matching string */
7195  this.lookahead = 0;         /* number of valid bytes ahead in window */
7196
7197  this.prev_length = 0;
7198  /* Length of the best match at previous step. Matches not greater than this
7199   * are discarded. This is used in the lazy match evaluation.
7200   */
7201
7202  this.max_chain_length = 0;
7203  /* To speed up deflation, hash chains are never searched beyond this
7204   * length.  A higher limit improves compression ratio but degrades the
7205   * speed.
7206   */
7207
7208  this.max_lazy_match = 0;
7209  /* Attempt to find a better match only when the current match is strictly
7210   * smaller than this value. This mechanism is used only for compression
7211   * levels >= 4.
7212   */
7213  // That's alias to max_lazy_match, don't use directly
7214  //this.max_insert_length = 0;
7215  /* Insert new strings in the hash table only if the match length is not
7216   * greater than this length. This saves time but degrades compression.
7217   * max_insert_length is used only for compression levels <= 3.
7218   */
7219
7220  this.level = 0;     /* compression level (1..9) */
7221  this.strategy = 0;  /* favor or force Huffman coding*/
7222
7223  this.good_match = 0;
7224  /* Use a faster search when the previous match is longer than this */
7225
7226  this.nice_match = 0; /* Stop searching when current match exceeds this */
7227
7228              /* used by trees.c: */
7229
7230  /* Didn't use ct_data typedef below to suppress compiler warning */
7231
7232  // struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
7233  // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
7234  // struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
7235
7236  // Use flat array of DOUBLE size, with interleaved fata,
7237  // because JS does not support effective
7238  this.dyn_ltree  = new utils.Buf16(HEAP_SIZE * 2);
7239  this.dyn_dtree  = new utils.Buf16((2*D_CODES+1) * 2);
7240  this.bl_tree    = new utils.Buf16((2*BL_CODES+1) * 2);
7241  zero(this.dyn_ltree);
7242  zero(this.dyn_dtree);
7243  zero(this.bl_tree);
7244
7245  this.l_desc   = null;         /* desc. for literal tree */
7246  this.d_desc   = null;         /* desc. for distance tree */
7247  this.bl_desc  = null;         /* desc. for bit length tree */
7248
7249  //ush bl_count[MAX_BITS+1];
7250  this.bl_count = new utils.Buf16(MAX_BITS+1);
7251  /* number of codes at each bit length for an optimal tree */
7252
7253  //int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
7254  this.heap = new utils.Buf16(2*L_CODES+1);  /* heap used to build the Huffman trees */
7255  zero(this.heap);
7256
7257  this.heap_len = 0;               /* number of elements in the heap */
7258  this.heap_max = 0;               /* element of largest frequency */
7259  /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
7260   * The same heap array is used to build all trees.
7261   */
7262
7263  this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
7264  zero(this.depth);
7265  /* Depth of each subtree used as tie breaker for trees of equal frequency
7266   */
7267
7268  this.l_buf = 0;          /* buffer index for literals or lengths */
7269
7270  this.lit_bufsize = 0;
7271  /* Size of match buffer for literals/lengths.  There are 4 reasons for
7272   * limiting lit_bufsize to 64K:
7273   *   - frequencies can be kept in 16 bit counters
7274   *   - if compression is not successful for the first block, all input
7275   *     data is still in the window so we can still emit a stored block even
7276   *     when input comes from standard input.  (This can also be done for
7277   *     all blocks if lit_bufsize is not greater than 32K.)
7278   *   - if compression is not successful for a file smaller than 64K, we can
7279   *     even emit a stored file instead of a stored block (saving 5 bytes).
7280   *     This is applicable only for zip (not gzip or zlib).
7281   *   - creating new Huffman trees less frequently may not provide fast
7282   *     adaptation to changes in the input data statistics. (Take for
7283   *     example a binary file with poorly compressible code followed by
vendor: 3,610 bytes, lines 7284-7424
7284   *     a highly compressible string table.) Smaller buffer sizes give
7285   *     fast adaptation but have of course the overhead of transmitting
7286   *     trees more frequently.
7287   *   - I can't count above 4
7288   */
7289
7290  this.last_lit = 0;      /* running index in l_buf */
7291
7292  this.d_buf = 0;
7293  /* Buffer index for distances. To simplify the code, d_buf and l_buf have
7294   * the same number of elements. To use different lengths, an extra flag
7295   * array would be necessary.
7296   */
7297
7298  this.opt_len = 0;       /* bit length of current block with optimal trees */
7299  this.static_len = 0;    /* bit length of current block with static trees */
7300  this.matches = 0;       /* number of string matches in current block */
7301  this.insert = 0;        /* bytes at end of window left to insert */
7302
7303
7304  this.bi_buf = 0;
7305  /* Output buffer. bits are inserted starting at the bottom (least
7306   * significant bits).
7307   */
7308  this.bi_valid = 0;
7309  /* Number of valid bits in bi_buf.  All bits above the last valid bit
7310   * are always zero.
7311   */
7312
7313  // Used for window memory init. We safely ignore it for JS. That makes
7314  // sense only for pointers and memory check tools.
7315  //this.high_water = 0;
7316  /* High water mark offset in window for initialized bytes -- bytes above
7317   * this are set to zero in order to avoid memory check warnings when
7318   * longest match routines access bytes past the input.  This is then
7319   * updated to the new high water mark.
7320   */
7321}
7322
7323
7324function deflateResetKeep(strm) {
7325  var s;
7326
7327  if (!strm || !strm.state) {
7328    return err(strm, Z_STREAM_ERROR);
7329  }
7330
7331  strm.total_in = strm.total_out = 0;
7332  strm.data_type = Z_UNKNOWN;
7333
7334  s = strm.state;
7335  s.pending = 0;
7336  s.pending_out = 0;
7337
7338  if (s.wrap < 0) {
7339    s.wrap = -s.wrap;
7340    /* was made negative by deflate(..., Z_FINISH); */
7341  }
7342  s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
7343  strm.adler = (s.wrap === 2) ?
7344    0  // crc32(0, Z_NULL, 0)
7345  :
7346    1; // adler32(0, Z_NULL, 0)
7347  s.last_flush = Z_NO_FLUSH;
7348  trees._tr_init(s);
7349  return Z_OK;
7350}
7351
7352
7353function deflateReset(strm) {
7354  var ret = deflateResetKeep(strm);
7355  if (ret === Z_OK) {
7356    lm_init(strm.state);
7357  }
7358  return ret;
7359}
7360
7361
7362function deflateSetHeader(strm, head) {
7363  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
7364  if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
7365  strm.state.gzhead = head;
7366  return Z_OK;
7367}
7368
7369
7370function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
7371  if (!strm) { // === Z_NULL
7372    return Z_STREAM_ERROR;
7373  }
7374  var wrap = 1;
7375
7376  if (level === Z_DEFAULT_COMPRESSION) {
7377    level = 6;
7378  }
7379
7380  if (windowBits < 0) { /* suppress zlib wrapper */
7381    wrap = 0;
7382    windowBits = -windowBits;
7383  }
7384
7385  else if (windowBits > 15) {
7386    wrap = 2;           /* write gzip wrapper instead */
7387    windowBits -= 16;
7388  }
7389
7390
7391  if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
7392    windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
7393    strategy < 0 || strategy > Z_FIXED) {
7394    return err(strm, Z_STREAM_ERROR);
7395  }
7396
7397
7398  if (windowBits === 8) {
7399    windowBits = 9;
7400  }
7401  /* until 256-byte window bug fixed */
7402
7403  var s = new DeflateState();
7404
7405  strm.state = s;
7406  s.strm = strm;
7407
7408  s.wrap = wrap;
7409  s.gzhead = null;
7410  s.w_bits = windowBits;
7411  s.w_size = 1 << s.w_bits;
7412  s.w_mask = s.w_size - 1;
7413
7414  s.hash_bits = memLevel + 7;
7415  s.hash_size = 1 << s.hash_bits;
7416  s.hash_mask = s.hash_size - 1;
7417  s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
7418
7419  s.window = new utils.Buf8(s.w_size * 2);
7420  s.head = new utils.Buf16(s.hash_size);
7421  s.prev = new utils.Buf16(s.w_size);
7422
7423  // Don't need mem init magic for JS.
7424  //s.high_water = 0;
vendor: 5,225 bytes, lines 7424-7600
7424  /* nothing written to s->window yet */
7425
7426  s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
7427
7428  s.pending_buf_size = s.lit_bufsize * 4;
7429  s.pending_buf = new utils.Buf8(s.pending_buf_size);
7430
7431  s.d_buf = s.lit_bufsize >> 1;
7432  s.l_buf = (1 + 2) * s.lit_bufsize;
7433
7434  s.level = level;
7435  s.strategy = strategy;
7436  s.method = method;
7437
7438  return deflateReset(strm);
7439}
7440
7441function deflateInit(strm, level) {
7442  return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
7443}
7444
7445
7446function deflate(strm, flush) {
7447  var old_flush, s;
7448  var beg, val; // for gzip header write only
7449
7450  if (!strm || !strm.state ||
7451    flush > Z_BLOCK || flush < 0) {
7452    return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
7453  }
7454
7455  s = strm.state;
7456
7457  if (!strm.output ||
7458      (!strm.input && strm.avail_in !== 0) ||
7459      (s.status === FINISH_STATE && flush !== Z_FINISH)) {
7460    return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
7461  }
7462
7463  s.strm = strm; /* just in case */
7464  old_flush = s.last_flush;
7465  s.last_flush = flush;
7466
7467  /* Write the header */
7468  if (s.status === INIT_STATE) {
7469
7470    if (s.wrap === 2) { // GZIP header
7471      strm.adler = 0;  //crc32(0L, Z_NULL, 0);
7472      put_byte(s, 31);
7473      put_byte(s, 139);
7474      put_byte(s, 8);
7475      if (!s.gzhead) { // s->gzhead == Z_NULL
7476        put_byte(s, 0);
7477        put_byte(s, 0);
7478        put_byte(s, 0);
7479        put_byte(s, 0);
7480        put_byte(s, 0);
7481        put_byte(s, s.level === 9 ? 2 :
7482                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
7483                     4 : 0));
7484        put_byte(s, OS_CODE);
7485        s.status = BUSY_STATE;
7486      }
7487      else {
7488        put_byte(s, (s.gzhead.text ? 1 : 0) +
7489                    (s.gzhead.hcrc ? 2 : 0) +
7490                    (!s.gzhead.extra ? 0 : 4) +
7491                    (!s.gzhead.name ? 0 : 8) +
7492                    (!s.gzhead.comment ? 0 : 16)
7493                );
7494        put_byte(s, s.gzhead.time & 0xff);
7495        put_byte(s, (s.gzhead.time >> 8) & 0xff);
7496        put_byte(s, (s.gzhead.time >> 16) & 0xff);
7497        put_byte(s, (s.gzhead.time >> 24) & 0xff);
7498        put_byte(s, s.level === 9 ? 2 :
7499                    (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
7500                     4 : 0));
7501        put_byte(s, s.gzhead.os & 0xff);
7502        if (s.gzhead.extra && s.gzhead.extra.length) {
7503          put_byte(s, s.gzhead.extra.length & 0xff);
7504          put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
7505        }
7506        if (s.gzhead.hcrc) {
7507          strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
7508        }
7509        s.gzindex = 0;
7510        s.status = EXTRA_STATE;
7511      }
7512    }
7513    else // DEFLATE header
7514    {
7515      var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
7516      var level_flags = -1;
7517
7518      if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
7519        level_flags = 0;
7520      } else if (s.level < 6) {
7521        level_flags = 1;
7522      } else if (s.level === 6) {
7523        level_flags = 2;
7524      } else {
7525        level_flags = 3;
7526      }
7527      header |= (level_flags << 6);
7528      if (s.strstart !== 0) { header |= PRESET_DICT; }
7529      header += 31 - (header % 31);
7530
7531      s.status = BUSY_STATE;
7532      putShortMSB(s, header);
7533
7534      /* Save the adler32 of the preset dictionary: */
7535      if (s.strstart !== 0) {
7536        putShortMSB(s, strm.adler >>> 16);
7537        putShortMSB(s, strm.adler & 0xffff);
7538      }
7539      strm.adler = 1; // adler32(0L, Z_NULL, 0);
7540    }
7541  }
7542
7543//#ifdef GZIP
7544  if (s.status === EXTRA_STATE) {
7545    if (s.gzhead.extra/* != Z_NULL*/) {
7546      beg = s.pending;  /* start of bytes to update crc */
7547
7548      while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
7549        if (s.pending === s.pending_buf_size) {
7550          if (s.gzhead.hcrc && s.pending > beg) {
7551            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7552          }
7553          flush_pending(strm);
7554          beg = s.pending;
7555          if (s.pending === s.pending_buf_size) {
7556            break;
7557          }
7558        }
7559        put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
7560        s.gzindex++;
7561      }
7562      if (s.gzhead.hcrc && s.pending > beg) {
7563        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7564      }
7565      if (s.gzindex === s.gzhead.extra.length) {
7566        s.gzindex = 0;
7567        s.status = NAME_STATE;
7568      }
7569    }
7570    else {
7571      s.status = NAME_STATE;
7572    }
7573  }
7574  if (s.status === NAME_STATE) {
7575    if (s.gzhead.name/* != Z_NULL*/) {
7576      beg = s.pending;  /* start of bytes to update crc */
7577      //int val;
7578
7579      do {
7580        if (s.pending === s.pending_buf_size) {
7581          if (s.gzhead.hcrc && s.pending > beg) {
7582            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7583          }
7584          flush_pending(strm);
7585          beg = s.pending;
7586          if (s.pending === s.pending_buf_size) {
7587            val = 1;
7588            break;
7589          }
7590        }
7591        // JS specific: little magic to add zero terminator to end of string
7592        if (s.gzindex < s.gzhead.name.length) {
7593          val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
7594        } else {
7595          val = 0;
7596        }
7597        put_byte(s, val);
7598      } while (val !== 0);
7599
7600      if (s.gzhead.hcrc && s.pending > beg)
vendor: 7,146 bytes, lines 7600-7838
7600 {
7601        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7602      }
7603      if (val === 0) {
7604        s.gzindex = 0;
7605        s.status = COMMENT_STATE;
7606      }
7607    }
7608    else {
7609      s.status = COMMENT_STATE;
7610    }
7611  }
7612  if (s.status === COMMENT_STATE) {
7613    if (s.gzhead.comment/* != Z_NULL*/) {
7614      beg = s.pending;  /* start of bytes to update crc */
7615      //int val;
7616
7617      do {
7618        if (s.pending === s.pending_buf_size) {
7619          if (s.gzhead.hcrc && s.pending > beg) {
7620            strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7621          }
7622          flush_pending(strm);
7623          beg = s.pending;
7624          if (s.pending === s.pending_buf_size) {
7625            val = 1;
7626            break;
7627          }
7628        }
7629        // JS specific: little magic to add zero terminator to end of string
7630        if (s.gzindex < s.gzhead.comment.length) {
7631          val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
7632        } else {
7633          val = 0;
7634        }
7635        put_byte(s, val);
7636      } while (val !== 0);
7637
7638      if (s.gzhead.hcrc && s.pending > beg) {
7639        strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
7640      }
7641      if (val === 0) {
7642        s.status = HCRC_STATE;
7643      }
7644    }
7645    else {
7646      s.status = HCRC_STATE;
7647    }
7648  }
7649  if (s.status === HCRC_STATE) {
7650    if (s.gzhead.hcrc) {
7651      if (s.pending + 2 > s.pending_buf_size) {
7652        flush_pending(strm);
7653      }
7654      if (s.pending + 2 <= s.pending_buf_size) {
7655        put_byte(s, strm.adler & 0xff);
7656        put_byte(s, (strm.adler >> 8) & 0xff);
7657        strm.adler = 0; //crc32(0L, Z_NULL, 0);
7658        s.status = BUSY_STATE;
7659      }
7660    }
7661    else {
7662      s.status = BUSY_STATE;
7663    }
7664  }
7665//#endif
7666
7667  /* Flush as much pending output as possible */
7668  if (s.pending !== 0) {
7669    flush_pending(strm);
7670    if (strm.avail_out === 0) {
7671      /* Since avail_out is 0, deflate will be called again with
7672       * more output space, but possibly with both pending and
7673       * avail_in equal to zero. There won't be anything to do,
7674       * but this is not an error situation so make sure we
7675       * return OK instead of BUF_ERROR at next call of deflate:
7676       */
7677      s.last_flush = -1;
7678      return Z_OK;
7679    }
7680
7681    /* Make sure there is something to do and avoid duplicate consecutive
7682     * flushes. For repeated and useless calls with Z_FINISH, we keep
7683     * returning Z_STREAM_END instead of Z_BUF_ERROR.
7684     */
7685  } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
7686    flush !== Z_FINISH) {
7687    return err(strm, Z_BUF_ERROR);
7688  }
7689
7690  /* User must not provide more input after the first FINISH: */
7691  if (s.status === FINISH_STATE && strm.avail_in !== 0) {
7692    return err(strm, Z_BUF_ERROR);
7693  }
7694
7695  /* Start a new block or continue the current one.
7696   */
7697  if (strm.avail_in !== 0 || s.lookahead !== 0 ||
7698    (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
7699    var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
7700      (s.strategy === Z_RLE ? deflate_rle(s, flush) :
7701        configuration_table[s.level].func(s, flush));
7702
7703    if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
7704      s.status = FINISH_STATE;
7705    }
7706    if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
7707      if (strm.avail_out === 0) {
7708        s.last_flush = -1;
7709        /* avoid BUF_ERROR next call, see above */
7710      }
7711      return Z_OK;
7712      /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
7713       * of deflate should use the same flush parameter to make sure
7714       * that the flush is complete. So we don't have to output an
7715       * empty block here, this will be done at next call. This also
7716       * ensures that for a very small output buffer, we emit at most
7717       * one empty block.
7718       */
7719    }
7720    if (bstate === BS_BLOCK_DONE) {
7721      if (flush === Z_PARTIAL_FLUSH) {
7722        trees._tr_align(s);
7723      }
7724      else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
7725
7726        trees._tr_stored_block(s, 0, 0, false);
7727        /* For a full flush, this empty block will be recognized
7728         * as a special marker by inflate_sync().
7729         */
7730        if (flush === Z_FULL_FLUSH) {
7731          /*** CLEAR_HASH(s); ***/             /* forget history */
7732          zero(s.head); // Fill with NIL (= 0);
7733
7734          if (s.lookahead === 0) {
7735            s.strstart = 0;
7736            s.block_start = 0;
7737            s.insert = 0;
7738          }
7739        }
7740      }
7741      flush_pending(strm);
7742      if (strm.avail_out === 0) {
7743        s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
7744        return Z_OK;
7745      }
7746    }
7747  }
7748  //Assert(strm->avail_out > 0, "bug2");
7749  //if (strm.avail_out <= 0) { throw new Error("bug2");}
7750
7751  if (flush !== Z_FINISH) { return Z_OK; }
7752  if (s.wrap <= 0) { return Z_STREAM_END; }
7753
7754  /* Write the trailer */
7755  if (s.wrap === 2) {
7756    put_byte(s, strm.adler & 0xff);
7757    put_byte(s, (strm.adler >> 8) & 0xff);
7758    put_byte(s, (strm.adler >> 16) & 0xff);
7759    put_byte(s, (strm.adler >> 24) & 0xff);
7760    put_byte(s, strm.total_in & 0xff);
7761    put_byte(s, (strm.total_in >> 8) & 0xff);
7762    put_byte(s, (strm.total_in >> 16) & 0xff);
7763    put_byte(s, (strm.total_in >> 24) & 0xff);
7764  }
7765  else
7766  {
7767    putShortMSB(s, strm.adler >>> 16);
7768    putShortMSB(s, strm.adler & 0xffff);
7769  }
7770
7771  flush_pending(strm);
7772  /* If avail_out is zero, the application will call deflate again
7773   * to flush the rest.
7774   */
7775  if (s.wrap > 0) { s.wrap = -s.wrap; }
7776  /* write the trailer only once! */
7777  return s.pending !== 0 ? Z_OK : Z_STREAM_END;
7778}
7779
7780function deflateEnd(strm) {
7781  var status;
7782
7783  if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
7784    return Z_STREAM_ERROR;
7785  }
7786
7787  status = strm.state.status;
7788  if (status !== INIT_STATE &&
7789    status !== EXTRA_STATE &&
7790    status !== NAME_STATE &&
7791    status !== COMMENT_STATE &&
7792    status !== HCRC_STATE &&
7793    status !== BUSY_STATE &&
7794    status !== FINISH_STATE
7795  ) {
7796    return err(strm, Z_STREAM_ERROR);
7797  }
7798
7799  strm.state = null;
7800
7801  return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
7802}
7803
7804/* =========================================================================
7805 * Copy the source state to the destination state
7806 */
7807//function deflateCopy(dest, source) {
7808//
7809//}
7810
7811exports.deflateInit = deflateInit;
7812exports.deflateInit2 = deflateInit2;
7813exports.deflateReset = deflateReset;
7814exports.deflateResetKeep = deflateResetKeep;
7815exports.deflateSetHeader = deflateSetHeader;
7816exports.deflate = deflate;
7817exports.deflateEnd = deflateEnd;
7818exports.deflateInfo = 'pako deflate (from Nodeca project)';
7819
7820/* Not implemented
7821exports.deflateBound = deflateBound;
7822exports.deflateCopy = deflateCopy;
7823exports.deflateSetDictionary = deflateSetDictionary;
7824exports.deflateParams = deflateParams;
7825exports.deflatePending = deflatePending;
7826exports.deflatePrime = deflatePrime;
7827exports.deflateTune = deflateTune;
7828*/
7829
7830},{"../utils/common":35,"./adler32":37,"./crc32":39,"./messages":45,"./trees":46}],41:[function(require,module,exports){
7831'use strict';
7832
7833
7834function GZheader() {
7835  /* true if compressed data believed to be text */
7836  this.text       = 0;
7837  /* modification time */
7838  this.time       = 0;
7839  /* extra flags (not used when writing a gzip file) */
7840  this.xflags     = 0;
7841  /* operating system */
7842  this.os         = 0;
7843  /* pointer to extra field or Z_NULL if none */
7844  this.extra      = null;
7845  /* extra field length (valid if extra != Z_NULL) */
7846  this.extra_len  = 0; // Actually, we don't need it in JS,
7847                       // but leave for few code modifications
7848
7849  //
7850  // Setup limits is not necessary because in js we should not preallocate memory
7851  // for inflate use constant limit in 65536 bytes
7852  //
7853
7854  /* space at extra (only when reading header) */
7855  // this.extra_max  = 0;
7856  /* pointer to zero-terminated file name or Z_NULL */
7857  this.name       = '';
7858  /* space at name (only when reading header) */
7859  // this.name_max   = 0;
7860  /* pointer to zero-terminated comment or Z_NULL */
7861  this.comment    = '';
7862  /* space at comment (only when reading header) */
7863  // this.comm_max   = 0;
7864  /* true if there was or will be a header crc */
7865  this.hcrc       = 0;
7866  /* true when done reading gzip header (not used when writing a gzip file) */
7867  this.done       = false;
7868}
7869
7870module.exports = GZheader;
7871
7872},{}],42:[function(require
vendor: 11,640 bytes, lines 7872-8199
7872,module,exports){
7873'use strict';
7874
7875// See state defs from inflate.js
7876var BAD = 30;       /* got a data error -- remain here until reset */
7877var TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
7878
7879/*
7880   Decode literal, length, and distance codes and write out the resulting
7881   literal and match bytes until either not enough input or output is
7882   available, an end-of-block is encountered, or a data error is encountered.
7883   When large enough input and output buffers are supplied to inflate(), for
7884   example, a 16K input buffer and a 64K output buffer, more than 95% of the
7885   inflate execution time is spent in this routine.
7886
7887   Entry assumptions:
7888
7889        state.mode === LEN
7890        strm.avail_in >= 6
7891        strm.avail_out >= 258
7892        start >= strm.avail_out
7893        state.bits < 8
7894
7895   On return, state.mode is one of:
7896
7897        LEN -- ran out of enough output space or enough available input
7898        TYPE -- reached end of block code, inflate() to interpret next block
7899        BAD -- error in block data
7900
7901   Notes:
7902
7903    - The maximum input bits used by a length/distance pair is 15 bits for the
7904      length code, 5 bits for the length extra, 15 bits for the distance code,
7905      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
7906      Therefore if strm.avail_in >= 6, then there is enough input to avoid
7907      checking for available input while decoding.
7908
7909    - The maximum bytes that a single length/distance pair can output is 258
7910      bytes, which is the maximum length that can be coded.  inflate_fast()
7911      requires strm.avail_out >= 258 for each loop to avoid checking for
7912      output space.
7913 */
7914module.exports = function inflate_fast(strm, start) {
7915  var state;
7916  var _in;                    /* local strm.input */
7917  var last;                   /* have enough input while in < last */
7918  var _out;                   /* local strm.output */
7919  var beg;                    /* inflate()'s initial strm.output */
7920  var end;                    /* while out < end, enough space available */
7921//#ifdef INFLATE_STRICT
7922  var dmax;                   /* maximum distance from zlib header */
7923//#endif
7924  var wsize;                  /* window size or zero if not using window */
7925  var whave;                  /* valid bytes in the window */
7926  var wnext;                  /* window write index */
7927  var window;                 /* allocated sliding window, if wsize != 0 */
7928  var hold;                   /* local strm.hold */
7929  var bits;                   /* local strm.bits */
7930  var lcode;                  /* local strm.lencode */
7931  var dcode;                  /* local strm.distcode */
7932  var lmask;                  /* mask for first level of length codes */
7933  var dmask;                  /* mask for first level of distance codes */
7934  var here;                   /* retrieved table entry */
7935  var op;                     /* code bits, operation, extra bits, or */
7936                              /*  window position, window bytes to copy */
7937  var len;                    /* match length, unused bytes */
7938  var dist;                   /* match distance */
7939  var from;                   /* where to copy match from */
7940  var from_source;
7941
7942
7943  var input, output; // JS specific, because we have no pointers
7944
7945  /* copy state to local variables */
7946  state = strm.state;
7947  //here = state.here;
7948  _in = strm.next_in;
7949  input = strm.input;
7950  last = _in + (strm.avail_in - 5);
7951  _out = strm.next_out;
7952  output = strm.output;
7953  beg = _out - (start - strm.avail_out);
7954  end = _out + (strm.avail_out - 257);
7955//#ifdef INFLATE_STRICT
7956  dmax = state.dmax;
7957//#endif
7958  wsize = state.wsize;
7959  whave = state.whave;
7960  wnext = state.wnext;
7961  window = state.window;
7962  hold = state.hold;
7963  bits = state.bits;
7964  lcode = state.lencode;
7965  dcode = state.distcode;
7966  lmask = (1 << state.lenbits) - 1;
7967  dmask = (1 << state.distbits) - 1;
7968
7969
7970  /* decode literals and length/distances until end-of-block or not enough
7971     input data or output space */
7972
7973  top:
7974  do {
7975    if (bits < 15) {
7976      hold += input[_in++] << bits;
7977      bits += 8;
7978      hold += input[_in++] << bits;
7979      bits += 8;
7980    }
7981
7982    here = lcode[hold & lmask];
7983
7984    dolen:
7985    for (;;) { // Goto emulation
7986      op = here >>> 24/*here.bits*/;
7987      hold >>>= op;
7988      bits -= op;
7989      op = (here >>> 16) & 0xff/*here.op*/;
7990      if (op === 0) {                          /* literal */
7991        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
7992        //        "inflate:         literal '%c'\n" :
7993        //        "inflate:         literal 0x%02x\n", here.val));
7994        output[_out++] = here & 0xffff/*here.val*/;
7995      }
7996      else if (op & 16) {                     /* length base */
7997        len = here & 0xffff/*here.val*/;
7998        op &= 15;                           /* number of extra bits */
7999        if (op) {
8000          if (bits < op) {
8001            hold += input[_in++] << bits;
8002            bits += 8;
8003          }
8004          len += hold & ((1 << op) - 1);
8005          hold >>>= op;
8006          bits -= op;
8007        }
8008        //Tracevv((stderr, "inflate:         length %u\n", len));
8009        if (bits < 15) {
8010          hold += input[_in++] << bits;
8011          bits += 8;
8012          hold += input[_in++] << bits;
8013          bits += 8;
8014        }
8015        here = dcode[hold & dmask];
8016
8017        dodist:
8018        for (;;) { // goto emulation
8019          op = here >>> 24/*here.bits*/;
8020          hold >>>= op;
8021          bits -= op;
8022          op = (here >>> 16) & 0xff/*here.op*/;
8023
8024          if (op & 16) {                      /* distance base */
8025            dist = here & 0xffff/*here.val*/;
8026            op &= 15;                       /* number of extra bits */
8027            if (bits < op) {
8028              hold += input[_in++] << bits;
8029              bits += 8;
8030              if (bits < op) {
8031                hold += input[_in++] << bits;
8032                bits += 8;
8033              }
8034            }
8035            dist += hold & ((1 << op) - 1);
8036//#ifdef INFLATE_STRICT
8037            if (dist > dmax) {
8038              strm.msg = 'invalid distance too far back';
8039              state.mode = BAD;
8040              break top;
8041            }
8042//#endif
8043            hold >>>= op;
8044            bits -= op;
8045            //Tracevv((stderr, "inflate:         distance %u\n", dist));
8046            op = _out - beg;                /* max distance in output */
8047            if (dist > op) {                /* see if copy from window */
8048              op = dist - op;               /* distance back in window */
8049              if (op > whave) {
8050                if (state.sane) {
8051                  strm.msg = 'invalid distance too far back';
8052                  state.mode = BAD;
8053                  break top;
8054                }
8055
8056// (!) This block is disabled in zlib defailts,
8057// don't enable it for binary compatibility
8058//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
8059//                if (len <= op - whave) {
8060//                  do {
8061//                    output[_out++] = 0;
8062//                  } while (--len);
8063//                  continue top;
8064//                }
8065//                len -= op - whave;
8066//                do {
8067//                  output[_out++] = 0;
8068//                } while (--op > whave);
8069//                if (op === 0) {
8070//                  from = _out - dist;
8071//                  do {
8072//                    output[_out++] = output[from++];
8073//                  } while (--len);
8074//                  continue top;
8075//                }
8076//#endif
8077              }
8078              from = 0; // window index
8079              from_source = window;
8080              if (wnext === 0) {           /* very common case */
8081                from += wsize - op;
8082                if (op < len) {         /* some from window */
8083                  len -= op;
8084                  do {
8085                    output[_out++] = window[from++];
8086                  } while (--op);
8087                  from = _out - dist;  /* rest from output */
8088                  from_source = output;
8089                }
8090              }
8091              else if (wnext < op) {      /* wrap around window */
8092                from += wsize + wnext - op;
8093                op -= wnext;
8094                if (op < len) {         /* some from end of window */
8095                  len -= op;
8096                  do {
8097                    output[_out++] = window[from++];
8098                  } while (--op);
8099                  from = 0;
8100                  if (wnext < len) {  /* some from start of window */
8101                    op = wnext;
8102                    len -= op;
8103                    do {
8104                      output[_out++] = window[from++];
8105                    } while (--op);
8106                    from = _out - dist;      /* rest from output */
8107                    from_source = output;
8108                  }
8109                }
8110              }
8111              else {                      /* contiguous in window */
8112                from += wnext - op;
8113                if (op < len) {         /* some from window */
8114                  len -= op;
8115                  do {
8116                    output[_out++] = window[from++];
8117                  } while (--op);
8118                  from = _out - dist;  /* rest from output */
8119                  from_source = output;
8120                }
8121              }
8122              while (len > 2) {
8123                output[_out++] = from_source[from++];
8124                output[_out++] = from_source[from++];
8125                output[_out++] = from_source[from++];
8126                len -= 3;
8127              }
8128              if (len) {
8129                output[_out++] = from_source[from++];
8130                if (len > 1) {
8131                  output[_out++] = from_source[from++];
8132                }
8133              }
8134            }
8135            else {
8136              from = _out - dist;          /* copy direct from output */
8137              do {                        /* minimum length is three */
8138                output[_out++] = output[from++];
8139                output[_out++] = output[from++];
8140                output[_out++] = output[from++];
8141                len -= 3;
8142              } while (len > 2);
8143              if (len) {
8144                output[_out++] = output[from++];
8145                if (len > 1) {
8146                  output[_out++] = output[from++];
8147                }
8148              }
8149            }
8150          }
8151          else if ((op & 64) === 0) {          /* 2nd level distance code */
8152            here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
8153            continue dodist;
8154          }
8155          else {
8156            strm.msg = 'invalid distance code';
8157            state.mode = BAD;
8158            break top;
8159          }
8160
8161          break; // need to emulate goto via "continue"
8162        }
8163      }
8164      else if ((op & 64) === 0) {              /* 2nd level length code */
8165        here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
8166        continue dolen;
8167      }
8168      else if (op & 32) {                     /* end-of-block */
8169        //Tracevv((stderr, "inflate:         end of block\n"));
8170        state.mode = TYPE;
8171        break top;
8172      }
8173      else {
8174        strm.msg = 'invalid literal/length code';
8175        state.mode = BAD;
8176        break top;
8177      }
8178
8179      break; // need to emulate goto via "continue"
8180    }
8181  } while (_in < last && _out < end);
8182
8183  /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
8184  len = bits >> 3;
8185  _in -= len;
8186  bits -= len << 3;
8187  hold &= (1 << bits) - 1;
8188
8189  /* update state and return */
8190  strm.next_in = _in;
8191  strm.next_out = _out;
8192  strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
8193  strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
8194  state.hold = hold;
8195  state.bits = bits;
8196  return;
8197};
8198
8199},{}],
819943:[function(require,module,exports){
8200'use strict';
8201
8202
8203var utils = require('../utils/common');
8204var adler32 = require('./adler32');
8205var crc32   = require('./crc32');
8206var inflate_fast = require('./inffast');
8207var inflate_table = require
vendor: 46,173 bytes, lines 8207-9702
8207('./inftrees');
8208
8209var CODES = 0;
8210var LENS = 1;
8211var DISTS = 2;
8212
8213/* Public constants ==========================================================*/
8214/* ===========================================================================*/
8215
8216
8217/* Allowed flush values; see deflate() and inflate() below for details */
8218//var Z_NO_FLUSH      = 0;
8219//var Z_PARTIAL_FLUSH = 1;
8220//var Z_SYNC_FLUSH    = 2;
8221//var Z_FULL_FLUSH    = 3;
8222var Z_FINISH        = 4;
8223var Z_BLOCK         = 5;
8224var Z_TREES         = 6;
8225
8226
8227/* Return codes for the compression/decompression functions. Negative values
8228 * are errors, positive values are used for special but normal events.
8229 */
8230var Z_OK            = 0;
8231var Z_STREAM_END    = 1;
8232var Z_NEED_DICT     = 2;
8233//var Z_ERRNO         = -1;
8234var Z_STREAM_ERROR  = -2;
8235var Z_DATA_ERROR    = -3;
8236var Z_MEM_ERROR     = -4;
8237var Z_BUF_ERROR     = -5;
8238//var Z_VERSION_ERROR = -6;
8239
8240/* The deflate compression method */
8241var Z_DEFLATED  = 8;
8242
8243
8244/* STATES ====================================================================*/
8245/* ===========================================================================*/
8246
8247
8248var    HEAD = 1;       /* i: waiting for magic header */
8249var    FLAGS = 2;      /* i: waiting for method and flags (gzip) */
8250var    TIME = 3;       /* i: waiting for modification time (gzip) */
8251var    OS = 4;         /* i: waiting for extra flags and operating system (gzip) */
8252var    EXLEN = 5;      /* i: waiting for extra length (gzip) */
8253var    EXTRA = 6;      /* i: waiting for extra bytes (gzip) */
8254var    NAME = 7;       /* i: waiting for end of file name (gzip) */
8255var    COMMENT = 8;    /* i: waiting for end of comment (gzip) */
8256var    HCRC = 9;       /* i: waiting for header crc (gzip) */
8257var    DICTID = 10;    /* i: waiting for dictionary check value */
8258var    DICT = 11;      /* waiting for inflateSetDictionary() call */
8259var        TYPE = 12;      /* i: waiting for type bits, including last-flag bit */
8260var        TYPEDO = 13;    /* i: same, but skip check to exit inflate on new block */
8261var        STORED = 14;    /* i: waiting for stored size (length and complement) */
8262var        COPY_ = 15;     /* i/o: same as COPY below, but only first time in */
8263var        COPY = 16;      /* i/o: waiting for input or output to copy stored block */
8264var        TABLE = 17;     /* i: waiting for dynamic block table lengths */
8265var        LENLENS = 18;   /* i: waiting for code length code lengths */
8266var        CODELENS = 19;  /* i: waiting for length/lit and distance code lengths */
8267var            LEN_ = 20;      /* i: same as LEN below, but only first time in */
8268var            LEN = 21;       /* i: waiting for length/lit/eob code */
8269var            LENEXT = 22;    /* i: waiting for length extra bits */
8270var            DIST = 23;      /* i: waiting for distance code */
8271var            DISTEXT = 24;   /* i: waiting for distance extra bits */
8272var            MATCH = 25;     /* o: waiting for output space to copy string */
8273var            LIT = 26;       /* o: waiting for output space to write literal */
8274var    CHECK = 27;     /* i: waiting for 32-bit check value */
8275var    LENGTH = 28;    /* i: waiting for 32-bit length (gzip) */
8276var    DONE = 29;      /* finished check, done -- remain here until reset */
8277var    BAD = 30;       /* got a data error -- remain here until reset */
8278var    MEM = 31;       /* got an inflate() memory error -- remain here until reset */
8279var    SYNC = 32;      /* looking for synchronization bytes to restart inflate() */
8280
8281/* ===========================================================================*/
8282
8283
8284
8285var ENOUGH_LENS = 852;
8286var ENOUGH_DISTS = 592;
8287//var ENOUGH =  (ENOUGH_LENS+ENOUGH_DISTS);
8288
8289var MAX_WBITS = 15;
8290/* 32K LZ77 window */
8291var DEF_WBITS = MAX_WBITS;
8292
8293
8294function ZSWAP32(q) {
8295  return  (((q >>> 24) & 0xff) +
8296          ((q >>> 8) & 0xff00) +
8297          ((q & 0xff00) << 8) +
8298          ((q & 0xff) << 24));
8299}
8300
8301
8302function InflateState() {
8303  this.mode = 0;             /* current inflate mode */
8304  this.last = false;          /* true if processing last block */
8305  this.wrap = 0;              /* bit 0 true for zlib, bit 1 true for gzip */
8306  this.havedict = false;      /* true if dictionary provided */
8307  this.flags = 0;             /* gzip header method and flags (0 if zlib) */
8308  this.dmax = 0;              /* zlib header max distance (INFLATE_STRICT) */
8309  this.check = 0;             /* protected copy of check value */
8310  this.total = 0;             /* protected copy of output count */
8311  // TODO: may be {}
8312  this.head = null;           /* where to save gzip header information */
8313
8314  /* sliding window */
8315  this.wbits = 0;             /* log base 2 of requested window size */
8316  this.wsize = 0;             /* window size or zero if not using window */
8317  this.whave = 0;             /* valid bytes in the window */
8318  this.wnext = 0;             /* window write index */
8319  this.window = null;         /* allocated sliding window, if needed */
8320
8321  /* bit accumulator */
8322  this.hold = 0;              /* input bit accumulator */
8323  this.bits = 0;              /* number of bits in "in" */
8324
8325  /* for string and stored block copying */
8326  this.length = 0;            /* literal or length of data to copy */
8327  this.offset = 0;            /* distance back to copy string from */
8328
8329  /* for table and code decoding */
8330  this.extra = 0;             /* extra bits needed */
8331
8332  /* fixed and dynamic code tables */
8333  this.lencode = null;          /* starting table for length/literal codes */
8334  this.distcode = null;         /* starting table for distance codes */
8335  this.lenbits = 0;           /* index bits for lencode */
8336  this.distbits = 0;          /* index bits for distcode */
8337
8338  /* dynamic table building */
8339  this.ncode = 0;             /* number of code length code lengths */
8340  this.nlen = 0;              /* number of length code lengths */
8341  this.ndist = 0;             /* number of distance code lengths */
8342  this.have = 0;              /* number of code lengths in lens[] */
8343  this.next = null;              /* next available space in codes[] */
8344
8345  this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
8346  this.work = new utils.Buf16(288); /* work area for code table building */
8347
8348  /*
8349   because we don't have pointers in js, we use lencode and distcode directly
8350   as buffers so we don't need codes
8351  */
8352  //this.codes = new utils.Buf32(ENOUGH);       /* space for code tables */
8353  this.lendyn = null;              /* dynamic table for length/literal codes (JS specific) */
8354  this.distdyn = null;             /* dynamic table for distance codes (JS specific) */
8355  this.sane = 0;                   /* if false, allow invalid distance too far */
8356  this.back = 0;                   /* bits back of last unprocessed length/lit */
8357  this.was = 0;                    /* initial length of match */
8358}
8359
8360function inflateResetKeep(strm) {
8361  var state;
8362
8363  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8364  state = strm.state;
8365  strm.total_in = strm.total_out = state.total = 0;
8366  strm.msg = ''; /*Z_NULL*/
8367  if (state.wrap) {       /* to support ill-conceived Java test suite */
8368    strm.adler = state.wrap & 1;
8369  }
8370  state.mode = HEAD;
8371  state.last = 0;
8372  state.havedict = 0;
8373  state.dmax = 32768;
8374  state.head = null/*Z_NULL*/;
8375  state.hold = 0;
8376  state.bits = 0;
8377  //state.lencode = state.distcode = state.next = state.codes;
8378  state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
8379  state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
8380
8381  state.sane = 1;
8382  state.back = -1;
8383  //Tracev((stderr, "inflate: reset\n"));
8384  return Z_OK;
8385}
8386
8387function inflateReset(strm) {
8388  var state;
8389
8390  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8391  state = strm.state;
8392  state.wsize = 0;
8393  state.whave = 0;
8394  state.wnext = 0;
8395  return inflateResetKeep(strm);
8396
8397}
8398
8399function inflateReset2(strm, windowBits) {
8400  var wrap;
8401  var state;
8402
8403  /* get the state */
8404  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
8405  state = strm.state;
8406
8407  /* extract wrap request from windowBits parameter */
8408  if (windowBits < 0) {
8409    wrap = 0;
8410    windowBits = -windowBits;
8411  }
8412  else {
8413    wrap = (windowBits >> 4) + 1;
8414    if (windowBits < 48) {
8415      windowBits &= 15;
8416    }
8417  }
8418
8419  /* set number of window bits, free window if different */
8420  if (windowBits && (windowBits < 8 || windowBits > 15)) {
8421    return Z_STREAM_ERROR;
8422  }
8423  if (state.window !== null && state.wbits !== windowBits) {
8424    state.window = null;
8425  }
8426
8427  /* update state and reset the rest of it */
8428  state.wrap = wrap;
8429  state.wbits = windowBits;
8430  return inflateReset(strm);
8431}
8432
8433function inflateInit2(strm, windowBits) {
8434  var ret;
8435  var state;
8436
8437  if (!strm) { return Z_STREAM_ERROR; }
8438  //strm.msg = Z_NULL;                 /* in case we return an error */
8439
8440  state = new InflateState();
8441
8442  //if (state === Z_NULL) return Z_MEM_ERROR;
8443  //Tracev((stderr, "inflate: allocated\n"));
8444  strm.state = state;
8445  state.window = null/*Z_NULL*/;
8446  ret = inflateReset2(strm, windowBits);
8447  if (ret !== Z_OK) {
8448    strm.state = null/*Z_NULL*/;
8449  }
8450  return ret;
8451}
8452
8453function inflateInit(strm) {
8454  return inflateInit2(strm, DEF_WBITS);
8455}
8456
8457
8458/*
8459 Return state with length and distance decoding tables and index sizes set to
8460 fixed code decoding.  Normally this returns fixed tables from inffixed.h.
8461 If BUILDFIXED is defined, then instead this routine builds the tables the
8462 first time it's called, and returns those tables the first time and
8463 thereafter.  This reduces the size of the code by about 2K bytes, in
8464 exchange for a little execution time.  However, BUILDFIXED should not be
8465 used for threaded applications, since the rewriting of the tables and virgin
8466 may not be thread-safe.
8467 */
8468var virgin = true;
8469
8470var lenfix, distfix; // We have no pointers in JS, so keep tables separate
8471
8472function fixedtables(state) {
8473  /* build fixed huffman tables if first call (may not be thread safe) */
8474  if (virgin) {
8475    var sym;
8476
8477    lenfix = new utils.Buf32(512);
8478    distfix = new utils.Buf32(32);
8479
8480    /* literal/length table */
8481    sym = 0;
8482    while (sym < 144) { state.lens[sym++] = 8; }
8483    while (sym < 256) { state.lens[sym++] = 9; }
8484    while (sym < 280) { state.lens[sym++] = 7; }
8485    while (sym < 288) { state.lens[sym++] = 8; }
8486
8487    inflate_table(LENS,  state.lens, 0, 288, lenfix,   0, state.work, {bits: 9});
8488
8489    /* distance table */
8490    sym = 0;
8491    while (sym < 32) { state.lens[sym++] = 5; }
8492
8493    inflate_table(DISTS, state.lens, 0, 32,   distfix, 0, state.work, {bits: 5});
8494
8495    /* do this just once */
8496    virgin = false;
8497  }
8498
8499  state.lencode = lenfix;
8500  state.lenbits = 9;
8501  state.distcode = distfix;
8502  state.distbits = 5;
8503}
8504
8505
8506/*
8507 Update the window with the last wsize (normally 32K) bytes written before
8508 returning.  If window does not exist yet, create it.  This is only called
8509 when a window is already in use, or when output has been written during this
8510 inflate call, but the end of the deflate stream has not been reached yet.
8511 It is also called to create a window for dictionary data when a dictionary
8512 is loaded.
8513
8514 Providing output buffers larger than 32K to inflate() should provide a speed
8515 advantage, since only the last 32K of output is copied to the sliding window
8516 upon return from inflate(), and since all distances after the first 32K of
8517 output will fall in the output data, making match copies simpler and faster.
8518 The advantage may be dependent on the size of the processor's data caches.
8519 */
8520function updatewindow(strm, src, end, copy) {
8521  var dist;
8522  var state = strm.state;
8523
8524  /* if it hasn't been done already, allocate space for the window */
8525  if (state.window === null) {
8526    state.wsize = 1 << state.wbits;
8527    state.wnext = 0;
8528    state.whave = 0;
8529
8530    state.window = new utils.Buf8(state.wsize);
8531  }
8532
8533  /* copy state->wsize or less output bytes into the circular window */
8534  if (copy >= state.wsize) {
8535    utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
8536    state.wnext = 0;
8537    state.whave = state.wsize;
8538  }
8539  else {
8540    dist = state.wsize - state.wnext;
8541    if (dist > copy) {
8542      dist = copy;
8543    }
8544    //zmemcpy(state->window + state->wnext, end - copy, dist);
8545    utils.arraySet(state.window,src, end - copy, dist, state.wnext);
8546    copy -= dist;
8547    if (copy) {
8548      //zmemcpy(state->window, end - copy, copy);
8549      utils.arraySet(state.window,src, end - copy, copy, 0);
8550      state.wnext = copy;
8551      state.whave = state.wsize;
8552    }
8553    else {
8554      state.wnext += dist;
8555      if (state.wnext === state.wsize) { state.wnext = 0; }
8556      if (state.whave < state.wsize) { state.whave += dist; }
8557    }
8558  }
8559  return 0;
8560}
8561
8562function inflate(strm, flush) {
8563  var state;
8564  var input, output;          // input/output buffers
8565  var next;                   /* next input INDEX */
8566  var put;                    /* next output INDEX */
8567  var have, left;             /* available input and output */
8568  var hold;                   /* bit buffer */
8569  var bits;                   /* bits in bit buffer */
8570  var _in, _out;              /* save starting available input and output */
8571  var copy;                   /* number of stored or match bytes to copy */
8572  var from;                   /* where to copy match bytes from */
8573  var from_source;
8574  var here = 0;               /* current decoding table entry */
8575  var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
8576  //var last;                   /* parent table entry */
8577  var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
8578  var len;                    /* length to copy for repeats, bits to drop */
8579  var ret;                    /* return code */
8580  var hbuf = new utils.Buf8(4);    /* buffer for gzip header crc calculation */
8581  var opts;
8582
8583  var n; // temporary var for NEED_BITS
8584
8585  var order = /* permutation of code lengths */
8586    [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
8587
8588
8589  if (!strm || !strm.state || !strm.output ||
8590      (!strm.input && strm.avail_in !== 0)) {
8591    return Z_STREAM_ERROR;
8592  }
8593
8594  state = strm.state;
8595  if (state.mode === TYPE) { state.mode = TYPEDO; }    /* skip check */
8596
8597
8598  //--- LOAD() ---
8599  put = strm.next_out;
8600  output = strm.output;
8601  left = strm.avail_out;
8602  next = strm.next_in;
8603  input = strm.input;
8604  have = strm.avail_in;
8605  hold = state.hold;
8606  bits = state.bits;
8607  //---
8608
8609  _in = have;
8610  _out = left;
8611  ret = Z_OK;
8612
8613  inf_leave: // goto emulation
8614  for (;;) {
8615    switch (state.mode) {
8616    case HEAD:
8617      if (state.wrap === 0) {
8618        state.mode = TYPEDO;
8619        break;
8620      }
8621      //=== NEEDBITS(16);
8622      while (bits < 16) {
8623        if (have === 0) { break inf_leave; }
8624        have--;
8625        hold += input[next++] << bits;
8626        bits += 8;
8627      }
8628      //===//
8629      if ((state.wrap & 2) && hold === 0x8b1f) {  /* gzip header */
8630        state.check = 0/*crc32(0L, Z_NULL, 0)*/;
8631        //=== CRC2(state.check, hold);
8632        hbuf[0] = hold & 0xff;
8633        hbuf[1] = (hold >>> 8) & 0xff;
8634        state.check = crc32(state.check, hbuf, 2, 0);
8635        //===//
8636
8637        //=== INITBITS();
8638        hold = 0;
8639        bits = 0;
8640        //===//
8641        state.mode = FLAGS;
8642        break;
8643      }
8644      state.flags = 0;           /* expect zlib header */
8645      if (state.head) {
8646        state.head.done = false;
8647      }
8648      if (!(state.wrap & 1) ||   /* check if zlib header allowed */
8649        (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
8650        strm.msg = 'incorrect header check';
8651        state.mode = BAD;
8652        break;
8653      }
8654      if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
8655        strm.msg = 'unknown compression method';
8656        state.mode = BAD;
8657        break;
8658      }
8659      //--- DROPBITS(4) ---//
8660      hold >>>= 4;
8661      bits -= 4;
8662      //---//
8663      len = (hold & 0x0f)/*BITS(4)*/ + 8;
8664      if (state.wbits === 0) {
8665        state.wbits = len;
8666      }
8667      else if (len > state.wbits) {
8668        strm.msg = 'invalid window size';
8669        state.mode = BAD;
8670        break;
8671      }
8672      state.dmax = 1 << len;
8673      //Tracev((stderr, "inflate:   zlib header ok\n"));
8674      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
8675      state.mode = hold & 0x200 ? DICTID : TYPE;
8676      //=== INITBITS();
8677      hold = 0;
8678      bits = 0;
8679      //===//
8680      break;
8681    case FLAGS:
8682      //=== NEEDBITS(16); */
8683      while (bits < 16) {
8684        if (have === 0) { break inf_leave; }
8685        have--;
8686        hold += input[next++] << bits;
8687        bits += 8;
8688      }
8689      //===//
8690      state.flags = hold;
8691      if ((state.flags & 0xff) !== Z_DEFLATED) {
8692        strm.msg = 'unknown compression method';
8693        state.mode = BAD;
8694        break;
8695      }
8696      if (state.flags & 0xe000) {
8697        strm.msg = 'unknown header flags set';
8698        state.mode = BAD;
8699        break;
8700      }
8701      if (state.head) {
8702        state.head.text = ((hold >> 8) & 1);
8703      }
8704      if (state.flags & 0x0200) {
8705        //=== CRC2(state.check, hold);
8706        hbuf[0] = hold & 0xff;
8707        hbuf[1] = (hold >>> 8) & 0xff;
8708        state.check = crc32(state.check, hbuf, 2, 0);
8709        //===//
8710      }
8711      //=== INITBITS();
8712      hold = 0;
8713      bits = 0;
8714      //===//
8715      state.mode = TIME;
8716      /* falls through */
8717    case TIME:
8718      //=== NEEDBITS(32); */
8719      while (bits < 32) {
8720        if (have === 0) { break inf_leave; }
8721        have--;
8722        hold += input[next++] << bits;
8723        bits += 8;
8724      }
8725      //===//
8726      if (state.head) {
8727        state.head.time = hold;
8728      }
8729      if (state.flags & 0x0200) {
8730        //=== CRC4(state.check, hold)
8731        hbuf[0] = hold & 0xff;
8732        hbuf[1] = (hold >>> 8) & 0xff;
8733        hbuf[2] = (hold >>> 16) & 0xff;
8734        hbuf[3] = (hold >>> 24) & 0xff;
8735        state.check = crc32(state.check, hbuf, 4, 0);
8736        //===
8737      }
8738      //=== INITBITS();
8739      hold = 0;
8740      bits = 0;
8741      //===//
8742      state.mode = OS;
8743      /* falls through */
8744    case OS:
8745      //=== NEEDBITS(16); */
8746      while (bits < 16) {
8747        if (have === 0) { break inf_leave; }
8748        have--;
8749        hold += input[next++] << bits;
8750        bits += 8;
8751      }
8752      //===//
8753      if (state.head) {
8754        state.head.xflags = (hold & 0xff);
8755        state.head.os = (hold >> 8);
8756      }
8757      if (state.flags & 0x0200) {
8758        //=== CRC2(state.check, hold);
8759        hbuf[0] = hold & 0xff;
8760        hbuf[1] = (hold >>> 8) & 0xff;
8761        state.check = crc32(state.check, hbuf, 2, 0);
8762        //===//
8763      }
8764      //=== INITBITS();
8765      hold = 0;
8766      bits = 0;
8767      //===//
8768      state.mode = EXLEN;
8769      /* falls through */
8770    case EXLEN:
8771      if (state.flags & 0x0400) {
8772        //=== NEEDBITS(16); */
8773        while (bits < 16) {
8774          if (have === 0) { break inf_leave; }
8775          have--;
8776          hold += input[next++] << bits;
8777          bits += 8;
8778        }
8779        //===//
8780        state.length = hold;
8781        if (state.head) {
8782          state.head.extra_len = hold;
8783        }
8784        if (state.flags & 0x0200) {
8785          //=== CRC2(state.check, hold);
8786          hbuf[0] = hold & 0xff;
8787          hbuf[1] = (hold >>> 8) & 0xff;
8788          state.check = crc32(state.check, hbuf, 2, 0);
8789          //===//
8790        }
8791        //=== INITBITS();
8792        hold = 0;
8793        bits = 0;
8794        //===//
8795      }
8796      else if (state.head) {
8797        state.head.extra = null/*Z_NULL*/;
8798      }
8799      state.mode = EXTRA;
8800      /* falls through */
8801    case EXTRA:
8802      if (state.flags & 0x0400) {
8803        copy = state.length;
8804        if (copy > have) { copy = have; }
8805        if (copy) {
8806          if (state.head) {
8807            len = state.head.extra_len - state.length;
8808            if (!state.head.extra) {
8809              // Use untyped array for more conveniend processing later
8810              state.head.extra = new Array(state.head.extra_len);
8811            }
8812            utils.arraySet(
8813              state.head.extra,
8814              input,
8815              next,
8816              // extra field is limited to 65536 bytes
8817              // - no need for additional size check
8818              copy,
8819              /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
8820              len
8821            );
8822            //zmemcpy(state.head.extra + len, next,
8823            //        len + copy > state.head.extra_max ?
8824            //        state.head.extra_max - len : copy);
8825          }
8826          if (state.flags & 0x0200) {
8827            state.check = crc32(state.check, input, copy, next);
8828          }
8829          have -= copy;
8830          next += copy;
8831          state.length -= copy;
8832        }
8833        if (state.length) { break inf_leave; }
8834      }
8835      state.length = 0;
8836      state.mode = NAME;
8837      /* falls through */
8838    case NAME:
8839      if (state.flags & 0x0800) {
8840        if (have === 0) { break inf_leave; }
8841        copy = 0;
8842        do {
8843          // TODO: 2 or 1 bytes?
8844          len = input[next + copy++];
8845          /* use constant limit because in js we should not preallocate memory */
8846          if (state.head && len &&
8847              (state.length < 65536 /*state.head.name_max*/)) {
8848            state.head.name += String.fromCharCode(len);
8849          }
8850        } while (len && copy < have);
8851
8852        if (state.flags & 0x0200) {
8853          state.check = crc32(state.check, input, copy, next);
8854        }
8855        have -= copy;
8856        next += copy;
8857        if (len) { break inf_leave; }
8858      }
8859      else if (state.head) {
8860        state.head.name = null;
8861      }
8862      state.length = 0;
8863      state.mode = COMMENT;
8864      /* falls through */
8865    case COMMENT:
8866      if (state.flags & 0x1000) {
8867        if (have === 0) { break inf_leave; }
8868        copy = 0;
8869        do {
8870          len = input[next + copy++];
8871          /* use constant limit because in js we should not preallocate memory */
8872          if (state.head && len &&
8873              (state.length < 65536 /*state.head.comm_max*/)) {
8874            state.head.comment += String.fromCharCode(len);
8875          }
8876        } while (len && copy < have);
8877        if (state.flags & 0x0200) {
8878          state.check = crc32(state.check, input, copy, next);
8879        }
8880        have -= copy;
8881        next += copy;
8882        if (len) { break inf_leave; }
8883      }
8884      else if (state.head) {
8885        state.head.comment = null;
8886      }
8887      state.mode = HCRC;
8888      /* falls through */
8889    case HCRC:
8890      if (state.flags & 0x0200) {
8891        //=== NEEDBITS(16); */
8892        while (bits < 16) {
8893          if (have === 0) { break inf_leave; }
8894          have--;
8895          hold += input[next++] << bits;
8896          bits += 8;
8897        }
8898        //===//
8899        if (hold !== (state.check & 0xffff)) {
8900          strm.msg = 'header crc mismatch';
8901          state.mode = BAD;
8902          break;
8903        }
8904        //=== INITBITS();
8905        hold = 0;
8906        bits = 0;
8907        //===//
8908      }
8909      if (state.head) {
8910        state.head.hcrc = ((state.flags >> 9) & 1);
8911        state.head.done = true;
8912      }
8913      strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
8914      state.mode = TYPE;
8915      break;
8916    case DICTID:
8917      //=== NEEDBITS(32); */
8918      while (bits < 32) {
8919        if (have === 0) { break inf_leave; }
8920        have--;
8921        hold += input[next++] << bits;
8922        bits += 8;
8923      }
8924      //===//
8925      strm.adler = state.check = ZSWAP32(hold);
8926      //=== INITBITS();
8927      hold = 0;
8928      bits = 0;
8929      //===//
8930      state.mode = DICT;
8931      /* falls through */
8932    case DICT:
8933      if (state.havedict === 0) {
8934        //--- RESTORE() ---
8935        strm.next_out = put;
8936        strm.avail_out = left;
8937        strm.next_in = next;
8938        strm.avail_in = have;
8939        state.hold = hold;
8940        state.bits = bits;
8941        //---
8942        return Z_NEED_DICT;
8943      }
8944      strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
8945      state.mode = TYPE;
8946      /* falls through */
8947    case TYPE:
8948      if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
8949      /* falls through */
8950    case TYPEDO:
8951      if (state.last) {
8952        //--- BYTEBITS() ---//
8953        hold >>>= bits & 7;
8954        bits -= bits & 7;
8955        //---//
8956        state.mode = CHECK;
8957        break;
8958      }
8959      //=== NEEDBITS(3); */
8960      while (bits < 3) {
8961        if (have === 0) { break inf_leave; }
8962        have--;
8963        hold += input[next++] << bits;
8964        bits += 8;
8965      }
8966      //===//
8967      state.last = (hold & 0x01)/*BITS(1)*/;
8968      //--- DROPBITS(1) ---//
8969      hold >>>= 1;
8970      bits -= 1;
8971      //---//
8972
8973      switch ((hold & 0x03)/*BITS(2)*/) {
8974      case 0:                             /* stored block */
8975        //Tracev((stderr, "inflate:     stored block%s\n",
8976        //        state.last ? " (last)" : ""));
8977        state.mode = STORED;
8978        break;
8979      case 1:                             /* fixed block */
8980        fixedtables(state);
8981        //Tracev((stderr, "inflate:     fixed codes block%s\n",
8982        //        state.last ? " (last)" : ""));
8983        state.mode = LEN_;             /* decode codes */
8984        if (flush === Z_TREES) {
8985          //--- DROPBITS(2) ---//
8986          hold >>>= 2;
8987          bits -= 2;
8988          //---//
8989          break inf_leave;
8990        }
8991        break;
8992      case 2:                             /* dynamic block */
8993        //Tracev((stderr, "inflate:     dynamic codes block%s\n",
8994        //        state.last ? " (last)" : ""));
8995        state.mode = TABLE;
8996        break;
8997      case 3:
8998        strm.msg = 'invalid block type';
8999        state.mode = BAD;
9000      }
9001      //--- DROPBITS(2) ---//
9002      hold >>>= 2;
9003      bits -= 2;
9004      //---//
9005      break;
9006    case STORED:
9007      //--- BYTEBITS() ---// /* go to byte boundary */
9008      hold >>>= bits & 7;
9009      bits -= bits & 7;
9010      //---//
9011      //=== NEEDBITS(32); */
9012      while (bits < 32) {
9013        if (have === 0) { break inf_leave; }
9014        have--;
9015        hold += input[next++] << bits;
9016        bits += 8;
9017      }
9018      //===//
9019      if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
9020        strm.msg = 'invalid stored block lengths';
9021        state.mode = BAD;
9022        break;
9023      }
9024      state.length = hold & 0xffff;
9025      //Tracev((stderr, "inflate:       stored length %u\n",
9026      //        state.length));
9027      //=== INITBITS();
9028      hold = 0;
9029      bits = 0;
9030      //===//
9031      state.mode = COPY_;
9032      if (flush === Z_TREES) { break inf_leave; }
9033      /* falls through */
9034    case COPY_:
9035      state.mode = COPY;
9036      /* falls through */
9037    case COPY:
9038      copy = state.length;
9039      if (copy) {
9040        if (copy > have) { copy = have; }
9041        if (copy > left) { copy = left; }
9042        if (copy === 0) { break inf_leave; }
9043        //--- zmemcpy(put, next, copy); ---
9044        utils.arraySet(output, input, next, copy, put);
9045        //---//
9046        have -= copy;
9047        next += copy;
9048        left -= copy;
9049        put += copy;
9050        state.length -= copy;
9051        break;
9052      }
9053      //Tracev((stderr, "inflate:       stored end\n"));
9054      state.mode = TYPE;
9055      break;
9056    case TABLE:
9057      //=== NEEDBITS(14); */
9058      while (bits < 14) {
9059        if (have === 0) { break inf_leave; }
9060        have--;
9061        hold += input[next++] << bits;
9062        bits += 8;
9063      }
9064      //===//
9065      state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
9066      //--- DROPBITS(5) ---//
9067      hold >>>= 5;
9068      bits -= 5;
9069      //---//
9070      state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
9071      //--- DROPBITS(5) ---//
9072      hold >>>= 5;
9073      bits -= 5;
9074      //---//
9075      state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
9076      //--- DROPBITS(4) ---//
9077      hold >>>= 4;
9078      bits -= 4;
9079      //---//
9080//#ifndef PKZIP_BUG_WORKAROUND
9081      if (state.nlen > 286 || state.ndist > 30) {
9082        strm.msg = 'too many length or distance symbols';
9083        state.mode = BAD;
9084        break;
9085      }
9086//#endif
9087      //Tracev((stderr, "inflate:       table sizes ok\n"));
9088      state.have = 0;
9089      state.mode = LENLENS;
9090      /* falls through */
9091    case LENLENS:
9092      while (state.have < state.ncode) {
9093        //=== NEEDBITS(3);
9094        while (bits < 3) {
9095          if (have === 0) { break inf_leave; }
9096          have--;
9097          hold += input[next++] << bits;
9098          bits += 8;
9099        }
9100        //===//
9101        state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
9102        //--- DROPBITS(3) ---//
9103        hold >>>= 3;
9104        bits -= 3;
9105        //---//
9106      }
9107      while (state.have < 19) {
9108        state.lens[order[state.have++]] = 0;
9109      }
9110      // We have separate tables & no pointers. 2 commented lines below not needed.
9111      //state.next = state.codes;
9112      //state.lencode = state.next;
9113      // Switch to use dynamic table
9114      state.lencode = state.lendyn;
9115      state.lenbits = 7;
9116
9117      opts = {bits: state.lenbits};
9118      ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
9119      state.lenbits = opts.bits;
9120
9121      if (ret) {
9122        strm.msg = 'invalid code lengths set';
9123        state.mode = BAD;
9124        break;
9125      }
9126      //Tracev((stderr, "inflate:       code lengths ok\n"));
9127      state.have = 0;
9128      state.mode = CODELENS;
9129      /* falls through */
9130    case CODELENS:
9131      while (state.have < state.nlen + state.ndist) {
9132        for (;;) {
9133          here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
9134          here_bits = here >>> 24;
9135          here_op = (here >>> 16) & 0xff;
9136          here_val = here & 0xffff;
9137
9138          if ((here_bits) <= bits) { break; }
9139          //--- PULLBYTE() ---//
9140          if (have === 0) { break inf_leave; }
9141          have--;
9142          hold += input[next++] << bits;
9143          bits += 8;
9144          //---//
9145        }
9146        if (here_val < 16) {
9147          //--- DROPBITS(here.bits) ---//
9148          hold >>>= here_bits;
9149          bits -= here_bits;
9150          //---//
9151          state.lens[state.have++] = here_val;
9152        }
9153        else {
9154          if (here_val === 16) {
9155            //=== NEEDBITS(here.bits + 2);
9156            n = here_bits + 2;
9157            while (bits < n) {
9158              if (have === 0) { break inf_leave; }
9159              have--;
9160              hold += input[next++] << bits;
9161              bits += 8;
9162            }
9163            //===//
9164            //--- DROPBITS(here.bits) ---//
9165            hold >>>= here_bits;
9166            bits -= here_bits;
9167            //---//
9168            if (state.have === 0) {
9169              strm.msg = 'invalid bit length repeat';
9170              state.mode = BAD;
9171              break;
9172            }
9173            len = state.lens[state.have - 1];
9174            copy = 3 + (hold & 0x03);//BITS(2);
9175            //--- DROPBITS(2) ---//
9176            hold >>>= 2;
9177            bits -= 2;
9178            //---//
9179          }
9180          else if (here_val === 17) {
9181            //=== NEEDBITS(here.bits + 3);
9182            n = here_bits + 3;
9183            while (bits < n) {
9184              if (have === 0) { break inf_leave; }
9185              have--;
9186              hold += input[next++] << bits;
9187              bits += 8;
9188            }
9189            //===//
9190            //--- DROPBITS(here.bits) ---//
9191            hold >>>= here_bits;
9192            bits -= here_bits;
9193            //---//
9194            len = 0;
9195            copy = 3 + (hold & 0x07);//BITS(3);
9196            //--- DROPBITS(3) ---//
9197            hold >>>= 3;
9198            bits -= 3;
9199            //---//
9200          }
9201          else {
9202            //=== NEEDBITS(here.bits + 7);
9203            n = here_bits + 7;
9204            while (bits < n) {
9205              if (have === 0) { break inf_leave; }
9206              have--;
9207              hold += input[next++] << bits;
9208              bits += 8;
9209            }
9210            //===//
9211            //--- DROPBITS(here.bits) ---//
9212            hold >>>= here_bits;
9213            bits -= here_bits;
9214            //---//
9215            len = 0;
9216            copy = 11 + (hold & 0x7f);//BITS(7);
9217            //--- DROPBITS(7) ---//
9218            hold >>>= 7;
9219            bits -= 7;
9220            //---//
9221          }
9222          if (state.have + copy > state.nlen + state.ndist) {
9223            strm.msg = 'invalid bit length repeat';
9224            state.mode = BAD;
9225            break;
9226          }
9227          while (copy--) {
9228            state.lens[state.have++] = len;
9229          }
9230        }
9231      }
9232
9233      /* handle error breaks in while */
9234      if (state.mode === BAD) { break; }
9235
9236      /* check for end-of-block code (better have one) */
9237      if (state.lens[256] === 0) {
9238        strm.msg = 'invalid code -- missing end-of-block';
9239        state.mode = BAD;
9240        break;
9241      }
9242
9243      /* build code tables -- note: do not change the lenbits or distbits
9244         values here (9 and 6) without reading the comments in inftrees.h
9245         concerning the ENOUGH constants, which depend on those values */
9246      state.lenbits = 9;
9247
9248      opts = {bits: state.lenbits};
9249      ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
9250      // We have separate tables & no pointers. 2 commented lines below not needed.
9251      // state.next_index = opts.table_index;
9252      state.lenbits = opts.bits;
9253      // state.lencode = state.next;
9254
9255      if (ret) {
9256        strm.msg = 'invalid literal/lengths set';
9257        state.mode = BAD;
9258        break;
9259      }
9260
9261      state.distbits = 6;
9262      //state.distcode.copy(state.codes);
9263      // Switch to use dynamic table
9264      state.distcode = state.distdyn;
9265      opts = {bits: state.distbits};
9266      ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
9267      // We have separate tables & no pointers. 2 commented lines below not needed.
9268      // state.next_index = opts.table_index;
9269      state.distbits = opts.bits;
9270      // state.distcode = state.next;
9271
9272      if (ret) {
9273        strm.msg = 'invalid distances set';
9274        state.mode = BAD;
9275        break;
9276      }
9277      //Tracev((stderr, 'inflate:       codes ok\n'));
9278      state.mode = LEN_;
9279      if (flush === Z_TREES) { break inf_leave; }
9280      /* falls through */
9281    case LEN_:
9282      state.mode = LEN;
9283      /* falls through */
9284    case LEN:
9285      if (have >= 6 && left >= 258) {
9286        //--- RESTORE() ---
9287        strm.next_out = put;
9288        strm.avail_out = left;
9289        strm.next_in = next;
9290        strm.avail_in = have;
9291        state.hold = hold;
9292        state.bits = bits;
9293        //---
9294        inflate_fast(strm, _out);
9295        //--- LOAD() ---
9296        put = strm.next_out;
9297        output = strm.output;
9298        left = strm.avail_out;
9299        next = strm.next_in;
9300        input = strm.input;
9301        have = strm.avail_in;
9302        hold = state.hold;
9303        bits = state.bits;
9304        //---
9305
9306        if (state.mode === TYPE) {
9307          state.back = -1;
9308        }
9309        break;
9310      }
9311      state.back = 0;
9312      for (;;) {
9313        here = state.lencode[hold & ((1 << state.lenbits) -1)];  /*BITS(state.lenbits)*/
9314        here_bits = here >>> 24;
9315        here_op = (here >>> 16) & 0xff;
9316        here_val = here & 0xffff;
9317
9318        if (here_bits <= bits) { break; }
9319        //--- PULLBYTE() ---//
9320        if (have === 0) { break inf_leave; }
9321        have--;
9322        hold += input[next++] << bits;
9323        bits += 8;
9324        //---//
9325      }
9326      if (here_op && (here_op & 0xf0) === 0) {
9327        last_bits = here_bits;
9328        last_op = here_op;
9329        last_val = here_val;
9330        for (;;) {
9331          here = state.lencode[last_val +
9332                  ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
9333          here_bits = here >>> 24;
9334          here_op = (here >>> 16) & 0xff;
9335          here_val = here & 0xffff;
9336
9337          if ((last_bits + here_bits) <= bits) { break; }
9338          //--- PULLBYTE() ---//
9339          if (have === 0) { break inf_leave; }
9340          have--;
9341          hold += input[next++] << bits;
9342          bits += 8;
9343          //---//
9344        }
9345        //--- DROPBITS(last.bits) ---//
9346        hold >>>= last_bits;
9347        bits -= last_bits;
9348        //---//
9349        state.back += last_bits;
9350      }
9351      //--- DROPBITS(here.bits) ---//
9352      hold >>>= here_bits;
9353      bits -= here_bits;
9354      //---//
9355      state.back += here_bits;
9356      state.length = here_val;
9357      if (here_op === 0) {
9358        //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
9359        //        "inflate:         literal '%c'\n" :
9360        //        "inflate:         literal 0x%02x\n", here.val));
9361        state.mode = LIT;
9362        break;
9363      }
9364      if (here_op & 32) {
9365        //Tracevv((stderr, "inflate:         end of block\n"));
9366        state.back = -1;
9367        state.mode = TYPE;
9368        break;
9369      }
9370      if (here_op & 64) {
9371        strm.msg = 'invalid literal/length code';
9372        state.mode = BAD;
9373        break;
9374      }
9375      state.extra = here_op & 15;
9376      state.mode = LENEXT;
9377      /* falls through */
9378    case LENEXT:
9379      if (state.extra) {
9380        //=== NEEDBITS(state.extra);
9381        n = state.extra;
9382        while (bits < n) {
9383          if (have === 0) { break inf_leave; }
9384          have--;
9385          hold += input[next++] << bits;
9386          bits += 8;
9387        }
9388        //===//
9389        state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
9390        //--- DROPBITS(state.extra) ---//
9391        hold >>>= state.extra;
9392        bits -= state.extra;
9393        //---//
9394        state.back += state.extra;
9395      }
9396      //Tracevv((stderr, "inflate:         length %u\n", state.length));
9397      state.was = state.length;
9398      state.mode = DIST;
9399      /* falls through */
9400    case DIST:
9401      for (;;) {
9402        here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
9403        here_bits = here >>> 24;
9404        here_op = (here >>> 16) & 0xff;
9405        here_val = here & 0xffff;
9406
9407        if ((here_bits) <= bits) { break; }
9408        //--- PULLBYTE() ---//
9409        if (have === 0) { break inf_leave; }
9410        have--;
9411        hold += input[next++] << bits;
9412        bits += 8;
9413        //---//
9414      }
9415      if ((here_op & 0xf0) === 0) {
9416        last_bits = here_bits;
9417        last_op = here_op;
9418        last_val = here_val;
9419        for (;;) {
9420          here = state.distcode[last_val +
9421                  ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
9422          here_bits = here >>> 24;
9423          here_op = (here >>> 16) & 0xff;
9424          here_val = here & 0xffff;
9425
9426          if ((last_bits + here_bits) <= bits) { break; }
9427          //--- PULLBYTE() ---//
9428          if (have === 0) { break inf_leave; }
9429          have--;
9430          hold += input[next++] << bits;
9431          bits += 8;
9432          //---//
9433        }
9434        //--- DROPBITS(last.bits) ---//
9435        hold >>>= last_bits;
9436        bits -= last_bits;
9437        //---//
9438        state.back += last_bits;
9439      }
9440      //--- DROPBITS(here.bits) ---//
9441      hold >>>= here_bits;
9442      bits -= here_bits;
9443      //---//
9444      state.back += here_bits;
9445      if (here_op & 64) {
9446        strm.msg = 'invalid distance code';
9447        state.mode = BAD;
9448        break;
9449      }
9450      state.offset = here_val;
9451      state.extra = (here_op) & 15;
9452      state.mode = DISTEXT;
9453      /* falls through */
9454    case DISTEXT:
9455      if (state.extra) {
9456        //=== NEEDBITS(state.extra);
9457        n = state.extra;
9458        while (bits < n) {
9459          if (have === 0) { break inf_leave; }
9460          have--;
9461          hold += input[next++] << bits;
9462          bits += 8;
9463        }
9464        //===//
9465        state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
9466        //--- DROPBITS(state.extra) ---//
9467        hold >>>= state.extra;
9468        bits -= state.extra;
9469        //---//
9470        state.back += state.extra;
9471      }
9472//#ifdef INFLATE_STRICT
9473      if (state.offset > state.dmax) {
9474        strm.msg = 'invalid distance too far back';
9475        state.mode = BAD;
9476        break;
9477      }
9478//#endif
9479      //Tracevv((stderr, "inflate:         distance %u\n", state.offset));
9480      state.mode = MATCH;
9481      /* falls through */
9482    case MATCH:
9483      if (left === 0) { break inf_leave; }
9484      copy = _out - left;
9485      if (state.offset > copy) {         /* copy from window */
9486        copy = state.offset - copy;
9487        if (copy > state.whave) {
9488          if (state.sane) {
9489            strm.msg = 'invalid distance too far back';
9490            state.mode = BAD;
9491            break;
9492          }
9493// (!) This block is disabled in zlib defailts,
9494// don't enable it for binary compatibility
9495//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
9496//          Trace((stderr, "inflate.c too far\n"));
9497//          copy -= state.whave;
9498//          if (copy > state.length) { copy = state.length; }
9499//          if (copy > left) { copy = left; }
9500//          left -= copy;
9501//          state.length -= copy;
9502//          do {
9503//            output[put++] = 0;
9504//          } while (--copy);
9505//          if (state.length === 0) { state.mode = LEN; }
9506//          break;
9507//#endif
9508        }
9509        if (copy > state.wnext) {
9510          copy -= state.wnext;
9511          from = state.wsize - copy;
9512        }
9513        else {
9514          from = state.wnext - copy;
9515        }
9516        if (copy > state.length) { copy = state.length; }
9517        from_source = state.window;
9518      }
9519      else {                              /* copy from output */
9520        from_source = output;
9521        from = put - state.offset;
9522        copy = state.length;
9523      }
9524      if (copy > left) { copy = left; }
9525      left -= copy;
9526      state.length -= copy;
9527      do {
9528        output[put++] = from_source[from++];
9529      } while (--copy);
9530      if (state.length === 0) { state.mode = LEN; }
9531      break;
9532    case LIT:
9533      if (left === 0) { break inf_leave; }
9534      output[put++] = state.length;
9535      left--;
9536      state.mode = LEN;
9537      break;
9538    case CHECK:
9539      if (state.wrap) {
9540        //=== NEEDBITS(32);
9541        while (bits < 32) {
9542          if (have === 0) { break inf_leave; }
9543          have--;
9544          // Use '|' insdead of '+' to make sure that result is signed
9545          hold |= input[next++] << bits;
9546          bits += 8;
9547        }
9548        //===//
9549        _out -= left;
9550        strm.total_out += _out;
9551        state.total += _out;
9552        if (_out) {
9553          strm.adler = state.check =
9554              /*UPDATE(state.check, put - _out, _out);*/
9555              (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
9556
9557        }
9558        _out = left;
9559        // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
9560        if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
9561          strm.msg = 'incorrect data check';
9562          state.mode = BAD;
9563          break;
9564        }
9565        //=== INITBITS();
9566        hold = 0;
9567        bits = 0;
9568        //===//
9569        //Tracev((stderr, "inflate:   check matches trailer\n"));
9570      }
9571      state.mode = LENGTH;
9572      /* falls through */
9573    case LENGTH:
9574      if (state.wrap && state.flags) {
9575        //=== NEEDBITS(32);
9576        while (bits < 32) {
9577          if (have === 0) { break inf_leave; }
9578          have--;
9579          hold += input[next++] << bits;
9580          bits += 8;
9581        }
9582        //===//
9583        if (hold !== (state.total & 0xffffffff)) {
9584          strm.msg = 'incorrect length check';
9585          state.mode = BAD;
9586          break;
9587        }
9588        //=== INITBITS();
9589        hold = 0;
9590        bits = 0;
9591        //===//
9592        //Tracev((stderr, "inflate:   length matches trailer\n"));
9593      }
9594      state.mode = DONE;
9595      /* falls through */
9596    case DONE:
9597      ret = Z_STREAM_END;
9598      break inf_leave;
9599    case BAD:
9600      ret = Z_DATA_ERROR;
9601      break inf_leave;
9602    case MEM:
9603      return Z_MEM_ERROR;
9604    case SYNC:
9605      /* falls through */
9606    default:
9607      return Z_STREAM_ERROR;
9608    }
9609  }
9610
9611  // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
9612
9613  /*
9614     Return from inflate(), updating the total counts and the check value.
9615     If there was no progress during the inflate() call, return a buffer
9616     error.  Call updatewindow() to create and/or update the window state.
9617     Note: a memory error from inflate() is non-recoverable.
9618   */
9619
9620  //--- RESTORE() ---
9621  strm.next_out = put;
9622  strm.avail_out = left;
9623  strm.next_in = next;
9624  strm.avail_in = have;
9625  state.hold = hold;
9626  state.bits = bits;
9627  //---
9628
9629  if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
9630                      (state.mode < CHECK || flush !== Z_FINISH))) {
9631    if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
9632      state.mode = MEM;
9633      return Z_MEM_ERROR;
9634    }
9635  }
9636  _in -= strm.avail_in;
9637  _out -= strm.avail_out;
9638  strm.total_in += _in;
9639  strm.total_out += _out;
9640  state.total += _out;
9641  if (state.wrap && _out) {
9642    strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
9643      (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
9644  }
9645  strm.data_type = state.bits + (state.last ? 64 : 0) +
9646                    (state.mode === TYPE ? 128 : 0) +
9647                    (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
9648  if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
9649    ret = Z_BUF_ERROR;
9650  }
9651  return ret;
9652}
9653
9654function inflateEnd(strm) {
9655
9656  if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
9657    return Z_STREAM_ERROR;
9658  }
9659
9660  var state = strm.state;
9661  if (state.window) {
9662    state.window = null;
9663  }
9664  strm.state = null;
9665  return Z_OK;
9666}
9667
9668function inflateGetHeader(strm, head) {
9669  var state;
9670
9671  /* check state */
9672  if (!strm || !strm.state) { return Z_STREAM_ERROR; }
9673  state = strm.state;
9674  if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
9675
9676  /* save header structure */
9677  state.head = head;
9678  head.done = false;
9679  return Z_OK;
9680}
9681
9682
9683exports.inflateReset = inflateReset;
9684exports.inflateReset2 = inflateReset2;
9685exports.inflateResetKeep = inflateResetKeep;
9686exports.inflateInit = inflateInit;
9687exports.inflateInit2 = inflateInit2;
9688exports.inflate = inflate;
9689exports.inflateEnd = inflateEnd;
9690exports.inflateGetHeader = inflateGetHeader;
9691exports.inflateInfo = 'pako inflate (from Nodeca project)';
9692
9693/* Not implemented
9694exports.inflateCopy = inflateCopy;
9695exports.inflateGetDictionary = inflateGetDictionary;
9696exports.inflateMark = inflateMark;
9697exports.inflatePrime = inflatePrime;
9698exports.inflateSetDictionary = inflateSetDictionary;
9699exports.inflateSync = inflateSync;
9700exports.inflateSyncPoint = inflateSyncPoint;
9701exports.inflateUndermine = inflateUndermine;
9702*/
9703
9704},{"../utils/common":35,"./adler32":37,"./crc32":39,"./inffast":42,"./inftrees":44}],44:[function(require,module,exports){
9705'use strict';
9706
9707
9708var utils = require('../utils/common');
9709
9710var MAXBITS = 15;
9711var ENOUGH_LENS = 852;
9712var ENOUGH_DISTS = 592;
9713//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
9714
9715var CODES = 0;
9716var LENS = 1;
9717var DISTS = 2;
9718
9719var lbase = [ /* Length codes 257..285 base */
9720  3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
9721  35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
9722];
9723
9724var lext = [ /* Length codes 257..285 extra */
9725  16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
9726  19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
9727];
9728
9729var dbase = [ /* Distance codes 0..29 base */
9730  1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
9731  257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
9732  8193, 12289, 16385, 24577, 0, 0
9733];
9734
9735var dext = [ /* Distance codes 0..29 extra */
9736  16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
9737  23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
9738  28, 28, 29, 29, 64, 64
9739];
9740
9741module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
9742{
9743  var bits = opts.bits;
9744      //here = opts.here; /* table entry for duplication */
9745
9746  var len = 0;               /* a code's length in bits */
9747  var sym = 0;               /* index of code symbols */
9748  var min = 0, max = 0;          /* minimum and maximum code lengths */
9749  var root = 0;              /* number of index bits for root table */
9750  var curr = 0;              /* number of index bits for current table */
9751  var drop = 0;              /* code bits to drop for sub-table */
9752  var left = 0;                   /* number of prefix codes available */
9753  var used = 0;              /* code entries in table used */
9754  var huff = 0;              /* Huffman code */
9755  var incr;              /* for incrementing code, index */
9756  var fill;              /* index for replicating entries */
9757  var low;               /* low bits for current root entry */
9758  var mask;              /* mask for low root bits */
9759  var next;             /* next available space in table */
9760  var base = null;     /* base value table to use */
9761  var base_index = 0;
9762//  var shoextra;    /* extra bits table to use */
9763  var end;                    /* use base and extra for symbol > end */
9764  var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1];    /* number of codes of each length */
9765  var offs = new utils.Buf16(MAXBITS+
vendor: 6,483 bytes, lines 9765-9934
97651); //[MAXBITS+1];     /* offsets in table for each length */
9766  var extra = null;
9767  var extra_index = 0;
9768
9769  var here_bits, here_op, here_val;
9770
9771  /*
9772   Process a set of code lengths to create a canonical Huffman code.  The
9773   code lengths are lens[0..codes-1].  Each length corresponds to the
9774   symbols 0..codes-1.  The Huffman code is generated by first sorting the
9775   symbols by length from short to long, and retaining the symbol order
9776   for codes with equal lengths.  Then the code starts with all zero bits
9777   for the first code of the shortest length, and the codes are integer
9778   increments for the same length, and zeros are appended as the length
9779   increases.  For the deflate format, these bits are stored backwards
9780   from their more natural integer increment ordering, and so when the
9781   decoding tables are built in the large loop below, the integer codes
9782   are incremented backwards.
9783
9784   This routine assumes, but does not check, that all of the entries in
9785   lens[] are in the range 0..MAXBITS.  The caller must assure this.
9786   1..MAXBITS is interpreted as that code length.  zero means that that
9787   symbol does not occur in this code.
9788
9789   The codes are sorted by computing a count of codes for each length,
9790   creating from that a table of starting indices for each length in the
9791   sorted table, and then entering the symbols in order in the sorted
9792   table.  The sorted table is work[], with that space being provided by
9793   the caller.
9794
9795   The length counts are used for other purposes as well, i.e. finding
9796   the minimum and maximum length codes, determining if there are any
9797   codes at all, checking for a valid set of lengths, and looking ahead
9798   at length counts to determine sub-table sizes when building the
9799   decoding tables.
9800   */
9801
9802  /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
9803  for (len = 0; len <= MAXBITS; len++) {
9804    count[len] = 0;
9805  }
9806  for (sym = 0; sym < codes; sym++) {
9807    count[lens[lens_index + sym]]++;
9808  }
9809
9810  /* bound code lengths, force root to be within code lengths */
9811  root = bits;
9812  for (max = MAXBITS; max >= 1; max--) {
9813    if (count[max] !== 0) { break; }
9814  }
9815  if (root > max) {
9816    root = max;
9817  }
9818  if (max === 0) {                     /* no symbols to code at all */
9819    //table.op[opts.table_index] = 64;  //here.op = (var char)64;    /* invalid code marker */
9820    //table.bits[opts.table_index] = 1;   //here.bits = (var char)1;
9821    //table.val[opts.table_index++] = 0;   //here.val = (var short)0;
9822    table[table_index++] = (1 << 24) | (64 << 16) | 0;
9823
9824
9825    //table.op[opts.table_index] = 64;
9826    //table.bits[opts.table_index] = 1;
9827    //table.val[opts.table_index++] = 0;
9828    table[table_index++] = (1 << 24) | (64 << 16) | 0;
9829
9830    opts.bits = 1;
9831    return 0;     /* no symbols, but wait for decoding to report error */
9832  }
9833  for (min = 1; min < max; min++) {
9834    if (count[min] !== 0) { break; }
9835  }
9836  if (root < min) {
9837    root = min;
9838  }
9839
9840  /* check for an over-subscribed or incomplete set of lengths */
9841  left = 1;
9842  for (len = 1; len <= MAXBITS; len++) {
9843    left <<= 1;
9844    left -= count[len];
9845    if (left < 0) {
9846      return -1;
9847    }        /* over-subscribed */
9848  }
9849  if (left > 0 && (type === CODES || max !== 1)) {
9850    return -1;                      /* incomplete set */
9851  }
9852
9853  /* generate offsets into symbol table for each length for sorting */
9854  offs[1] = 0;
9855  for (len = 1; len < MAXBITS; len++) {
9856    offs[len + 1] = offs[len] + count[len];
9857  }
9858
9859  /* sort symbols by length, by symbol order within each length */
9860  for (sym = 0; sym < codes; sym++) {
9861    if (lens[lens_index + sym] !== 0) {
9862      work[offs[lens[lens_index + sym]]++] = sym;
9863    }
9864  }
9865
9866  /*
9867   Create and fill in decoding tables.  In this loop, the table being
9868   filled is at next and has curr index bits.  The code being used is huff
9869   with length len.  That code is converted to an index by dropping drop
9870   bits off of the bottom.  For codes where len is less than drop + curr,
9871   those top drop + curr - len bits are incremented through all values to
9872   fill the table with replicated entries.
9873
9874   root is the number of index bits for the root table.  When len exceeds
9875   root, sub-tables are created pointed to by the root entry with an index
9876   of the low root bits of huff.  This is saved in low to check for when a
9877   new sub-table should be started.  drop is zero when the root table is
9878   being filled, and drop is root when sub-tables are being filled.
9879
9880   When a new sub-table is needed, it is necessary to look ahead in the
9881   code lengths to determine what size sub-table is needed.  The length
9882   counts are used for this, and so count[] is decremented as codes are
9883   entered in the tables.
9884
9885   used keeps track of how many table entries have been allocated from the
9886   provided *table space.  It is checked for LENS and DIST tables against
9887   the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
9888   the initial root table size constants.  See the comments in inftrees.h
9889   for more information.
9890
9891   sym increments through all symbols, and the loop terminates when
9892   all codes of length max, i.e. all codes, have been processed.  This
9893   routine permits incomplete codes, so another loop after this one fills
9894   in the rest of the decoding tables with invalid code markers.
9895   */
9896
9897  /* set up for code type */
9898  // poor man optimization - use if-else instead of switch,
9899  // to avoid deopts in old v8
9900  if (type === CODES) {
9901    base = extra = work;    /* dummy value--not used */
9902    end = 19;
9903
9904  } else if (type === LENS) {
9905    base = lbase;
9906    base_index -= 257;
9907    extra = lext;
9908    extra_index -= 257;
9909    end = 256;
9910
9911  } else {                    /* DISTS */
9912    base = dbase;
9913    extra = dext;
9914    end = -1;
9915  }
9916
9917  /* initialize opts for loop */
9918  huff = 0;                   /* starting code */
9919  sym = 0;                    /* starting code symbol */
9920  len = min;                  /* starting code length */
9921  next = table_index;              /* current table to fill in */
9922  curr = root;                /* current table index bits */
9923  drop = 0;                   /* current bits to drop from code for index */
9924  low = -1;                   /* trigger new sub-table when len > root */
9925  used = 1 << root;          /* use root table entries */
9926  mask = used - 1;            /* mask for comparing low */
9927
9928  /* check available table space */
9929  if ((type === LENS && used > ENOUGH_LENS) ||
9930    (type === DISTS && used > ENOUGH_DISTS)) {
9931    return 1;
9932  }
9933
9934  
vendor: 3,442 bytes, lines 9934-10052
9934var i=0;
9935  /* process all codes and make table entries */
9936  for (;;) {
9937    i++;
9938    /* create table entry */
9939    here_bits = len - drop;
9940    if (work[sym] < end) {
9941      here_op = 0;
9942      here_val = work[sym];
9943    }
9944    else if (work[sym] > end) {
9945      here_op = extra[extra_index + work[sym]];
9946      here_val = base[base_index + work[sym]];
9947    }
9948    else {
9949      here_op = 32 + 64;         /* end of block */
9950      here_val = 0;
9951    }
9952
9953    /* replicate for those indices with low len bits equal to huff */
9954    incr = 1 << (len - drop);
9955    fill = 1 << curr;
9956    min = fill;                 /* save offset to next table */
9957    do {
9958      fill -= incr;
9959      table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
9960    } while (fill !== 0);
9961
9962    /* backwards increment the len-bit code huff */
9963    incr = 1 << (len - 1);
9964    while (huff & incr) {
9965      incr >>= 1;
9966    }
9967    if (incr !== 0) {
9968      huff &= incr - 1;
9969      huff += incr;
9970    } else {
9971      huff = 0;
9972    }
9973
9974    /* go to next symbol, update count, len */
9975    sym++;
9976    if (--count[len] === 0) {
9977      if (len === max) { break; }
9978      len = lens[lens_index + work[sym]];
9979    }
9980
9981    /* create new sub-table if needed */
9982    if (len > root && (huff & mask) !== low) {
9983      /* if first time, transition to sub-tables */
9984      if (drop === 0) {
9985        drop = root;
9986      }
9987
9988      /* increment past last table */
9989      next += min;            /* here min is 1 << curr */
9990
9991      /* determine length of next table */
9992      curr = len - drop;
9993      left = 1 << curr;
9994      while (curr + drop < max) {
9995        left -= count[curr + drop];
9996        if (left <= 0) { break; }
9997        curr++;
9998        left <<= 1;
9999      }
10000
10001      /* check for enough space */
10002      used += 1 << curr;
10003      if ((type === LENS && used > ENOUGH_LENS) ||
10004        (type === DISTS && used > ENOUGH_DISTS)) {
10005        return 1;
10006      }
10007
10008      /* point entry in root table to sub-table */
10009      low = huff & mask;
10010      /*table.op[low] = curr;
10011      table.bits[low] = root;
10012      table.val[low] = next - opts.table_index;*/
10013      table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
10014    }
10015  }
10016
10017  /* fill in remaining table entry if code is incomplete (guaranteed to have
10018   at most one remaining entry, since if the code is incomplete, the
10019   maximum code length that was allowed to get this far is one bit) */
10020  if (huff !== 0) {
10021    //table.op[next + huff] = 64;            /* invalid code marker */
10022    //table.bits[next + huff] = len - drop;
10023    //table.val[next + huff] = 0;
10024    table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
10025  }
10026
10027  /* set return parameters */
10028  //opts.table_index += used;
10029  opts.bits = root;
10030  return 0;
10031};
10032
10033},{"../utils/common":35}],45:[function(require,module,exports){
10034'use strict';
10035
10036module.exports = {
10037  '2':    'need dictionary',     /* Z_NEED_DICT       2  */
10038  '1':    'stream end',          /* Z_STREAM_END      1  */
10039  '0':    '',                    /* Z_OK              0  */
10040  '-1':   'file error',          /* Z_ERRNO         (-1) */
10041  '-2':   'stream error',        /* Z_STREAM_ERROR  (-2) */
10042  '-3':   'data error',          /* Z_DATA_ERROR    (-3) */
10043  '-4':   'insufficient memory', /* Z_MEM_ERROR     (-4) */
10044  '-5':   'buffer error',        /* Z_BUF_ERROR     (-5) */
10045  '-6':   'incompatible version' /* Z_VERSION_ERROR (-6) */
10046};
10047
10048},{}],46:[function(require,module,exports){
10049'use strict';
10050
10051
10052var utils = require
vendor: 38,553 bytes, lines 10052-11247
10052('../utils/common');
10053
10054/* Public constants ==========================================================*/
10055/* ===========================================================================*/
10056
10057
10058//var Z_FILTERED          = 1;
10059//var Z_HUFFMAN_ONLY      = 2;
10060//var Z_RLE               = 3;
10061var Z_FIXED               = 4;
10062//var Z_DEFAULT_STRATEGY  = 0;
10063
10064/* Possible values of the data_type field (though see inflate()) */
10065var Z_BINARY              = 0;
10066var Z_TEXT                = 1;
10067//var Z_ASCII             = 1; // = Z_TEXT
10068var Z_UNKNOWN             = 2;
10069
10070/*============================================================================*/
10071
10072
10073function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
10074
10075// From zutil.h
10076
10077var STORED_BLOCK = 0;
10078var STATIC_TREES = 1;
10079var DYN_TREES    = 2;
10080/* The three kinds of block type */
10081
10082var MIN_MATCH    = 3;
10083var MAX_MATCH    = 258;
10084/* The minimum and maximum match lengths */
10085
10086// From deflate.h
10087/* ===========================================================================
10088 * Internal compression state.
10089 */
10090
10091var LENGTH_CODES  = 29;
10092/* number of length codes, not counting the special END_BLOCK code */
10093
10094var LITERALS      = 256;
10095/* number of literal bytes 0..255 */
10096
10097var L_CODES       = LITERALS + 1 + LENGTH_CODES;
10098/* number of Literal or Length codes, including the END_BLOCK code */
10099
10100var D_CODES       = 30;
10101/* number of distance codes */
10102
10103var BL_CODES      = 19;
10104/* number of codes used to transfer the bit lengths */
10105
10106var HEAP_SIZE     = 2*L_CODES + 1;
10107/* maximum heap size */
10108
10109var MAX_BITS      = 15;
10110/* All codes must not exceed MAX_BITS bits */
10111
10112var Buf_size      = 16;
10113/* size of bit buffer in bi_buf */
10114
10115
10116/* ===========================================================================
10117 * Constants
10118 */
10119
10120var MAX_BL_BITS = 7;
10121/* Bit length codes must not exceed MAX_BL_BITS bits */
10122
10123var END_BLOCK   = 256;
10124/* end of block literal code */
10125
10126var REP_3_6     = 16;
10127/* repeat previous bit length 3-6 times (2 bits of repeat count) */
10128
10129var REPZ_3_10   = 17;
10130/* repeat a zero length 3-10 times  (3 bits of repeat count) */
10131
10132var REPZ_11_138 = 18;
10133/* repeat a zero length 11-138 times  (7 bits of repeat count) */
10134
10135var extra_lbits =   /* extra bits for each length code */
10136  [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0];
10137
10138var extra_dbits =   /* extra bits for each distance code */
10139  [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13];
10140
10141var extra_blbits =  /* extra bits for each bit length code */
10142  [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
10143
10144var bl_order =
10145  [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
10146/* The lengths of the bit length codes are sent in order of decreasing
10147 * probability, to avoid transmitting the lengths for unused bit length codes.
10148 */
10149
10150/* ===========================================================================
10151 * Local data. These are initialized only once.
10152 */
10153
10154// We pre-fill arrays with 0 to avoid uninitialized gaps
10155
10156var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
10157
10158// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
10159var static_ltree  = new Array((L_CODES+2) * 2);
10160zero(static_ltree);
10161/* The static literal tree. Since the bit lengths are imposed, there is no
10162 * need for the L_CODES extra codes used during heap construction. However
10163 * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
10164 * below).
10165 */
10166
10167var static_dtree  = new Array(D_CODES * 2);
10168zero(static_dtree);
10169/* The static distance tree. (Actually a trivial tree since all codes use
10170 * 5 bits.)
10171 */
10172
10173var _dist_code    = new Array(DIST_CODE_LEN);
10174zero(_dist_code);
10175/* Distance codes. The first 256 values correspond to the distances
10176 * 3 .. 258, the last 256 values correspond to the top 8 bits of
10177 * the 15 bit distances.
10178 */
10179
10180var _length_code  = new Array(MAX_MATCH-MIN_MATCH+1);
10181zero(_length_code);
10182/* length code for each normalized match length (0 == MIN_MATCH) */
10183
10184var base_length   = new Array(LENGTH_CODES);
10185zero(base_length);
10186/* First normalized length for each code (0 = MIN_MATCH) */
10187
10188var base_dist     = new Array(D_CODES);
10189zero(base_dist);
10190/* First normalized distance for each code (0 = distance of 1) */
10191
10192
10193var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
10194
10195  this.static_tree  = static_tree;  /* static tree or NULL */
10196  this.extra_bits   = extra_bits;   /* extra bits for each code or NULL */
10197  this.extra_base   = extra_base;   /* base index for extra_bits */
10198  this.elems        = elems;        /* max number of elements in the tree */
10199  this.max_length   = max_length;   /* max bit length for the codes */
10200
10201  // show if `static_tree` has data or dummy - needed for monomorphic objects
10202  this.has_stree    = static_tree && static_tree.length;
10203};
10204
10205
10206var static_l_desc;
10207var static_d_desc;
10208var static_bl_desc;
10209
10210
10211var TreeDesc = function(dyn_tree, stat_desc) {
10212  this.dyn_tree = dyn_tree;     /* the dynamic tree */
10213  this.max_code = 0;            /* largest code with non zero frequency */
10214  this.stat_desc = stat_desc;   /* the corresponding static tree */
10215};
10216
10217
10218
10219function d_code(dist) {
10220  return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
10221}
10222
10223
10224/* ===========================================================================
10225 * Output a short LSB first on the stream.
10226 * IN assertion: there is enough room in pendingBuf.
10227 */
10228function put_short (s, w) {
10229//    put_byte(s, (uch)((w) & 0xff));
10230//    put_byte(s, (uch)((ush)(w) >> 8));
10231  s.pending_buf[s.pending++] = (w) & 0xff;
10232  s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
10233}
10234
10235
10236/* ===========================================================================
10237 * Send a value on a given number of bits.
10238 * IN assertion: length <= 16 and value fits in length bits.
10239 */
10240function send_bits(s, value, length) {
10241  if (s.bi_valid > (Buf_size - length)) {
10242    s.bi_buf |= (value << s.bi_valid) & 0xffff;
10243    put_short(s, s.bi_buf);
10244    s.bi_buf = value >> (Buf_size - s.bi_valid);
10245    s.bi_valid += length - Buf_size;
10246  } else {
10247    s.bi_buf |= (value << s.bi_valid) & 0xffff;
10248    s.bi_valid += length;
10249  }
10250}
10251
10252
10253function send_code(s, c, tree) {
10254  send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
10255}
10256
10257
10258/* ===========================================================================
10259 * Reverse the first len bits of a code, using straightforward code (a faster
10260 * method would use a table)
10261 * IN assertion: 1 <= len <= 15
10262 */
10263function bi_reverse(code, len) {
10264  var res = 0;
10265  do {
10266    res |= code & 1;
10267    code >>>= 1;
10268    res <<= 1;
10269  } while (--len > 0);
10270  return res >>> 1;
10271}
10272
10273
10274/* ===========================================================================
10275 * Flush the bit buffer, keeping at most 7 bits in it.
10276 */
10277function bi_flush(s) {
10278  if (s.bi_valid === 16) {
10279    put_short(s, s.bi_buf);
10280    s.bi_buf = 0;
10281    s.bi_valid = 0;
10282
10283  } else if (s.bi_valid >= 8) {
10284    s.pending_buf[s.pending++] = s.bi_buf & 0xff;
10285    s.bi_buf >>= 8;
10286    s.bi_valid -= 8;
10287  }
10288}
10289
10290
10291/* ===========================================================================
10292 * Compute the optimal bit lengths for a tree and update the total bit length
10293 * for the current block.
10294 * IN assertion: the fields freq and dad are set, heap[heap_max] and
10295 *    above are the tree nodes sorted by increasing frequency.
10296 * OUT assertions: the field len is set to the optimal bit length, the
10297 *     array bl_count contains the frequencies for each bit length.
10298 *     The length opt_len is updated; static_len is also updated if stree is
10299 *     not null.
10300 */
10301function gen_bitlen(s, desc)
10302//    deflate_state *s;
10303//    tree_desc *desc;    /* the tree descriptor */
10304{
10305  var tree            = desc.dyn_tree;
10306  var max_code        = desc.max_code;
10307  var stree           = desc.stat_desc.static_tree;
10308  var has_stree       = desc.stat_desc.has_stree;
10309  var extra           = desc.stat_desc.extra_bits;
10310  var base            = desc.stat_desc.extra_base;
10311  var max_length      = desc.stat_desc.max_length;
10312  var h;              /* heap index */
10313  var n, m;           /* iterate over the tree elements */
10314  var bits;           /* bit length */
10315  var xbits;          /* extra bits */
10316  var f;              /* frequency */
10317  var overflow = 0;   /* number of elements with bit length too large */
10318
10319  for (bits = 0; bits <= MAX_BITS; bits++) {
10320    s.bl_count[bits] = 0;
10321  }
10322
10323  /* In a first pass, compute the optimal bit lengths (which may
10324   * overflow in the case of the bit length tree).
10325   */
10326  tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
10327
10328  for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
10329    n = s.heap[h];
10330    bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
10331    if (bits > max_length) {
10332      bits = max_length;
10333      overflow++;
10334    }
10335    tree[n*2 + 1]/*.Len*/ = bits;
10336    /* We overwrite tree[n].Dad which is no longer needed */
10337
10338    if (n > max_code) { continue; } /* not a leaf node */
10339
10340    s.bl_count[bits]++;
10341    xbits = 0;
10342    if (n >= base) {
10343      xbits = extra[n-base];
10344    }
10345    f = tree[n * 2]/*.Freq*/;
10346    s.opt_len += f * (bits + xbits);
10347    if (has_stree) {
10348      s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
10349    }
10350  }
10351  if (overflow === 0) { return; }
10352
10353  // Trace((stderr,"\nbit length overflow\n"));
10354  /* This happens for example on obj2 and pic of the Calgary corpus */
10355
10356  /* Find the first bit length which could increase: */
10357  do {
10358    bits = max_length-1;
10359    while (s.bl_count[bits] === 0) { bits--; }
10360    s.bl_count[bits]--;      /* move one leaf down the tree */
10361    s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
10362    s.bl_count[max_length]--;
10363    /* The brother of the overflow item also moves one step up,
10364     * but this does not affect bl_count[max_length]
10365     */
10366    overflow -= 2;
10367  } while (overflow > 0);
10368
10369  /* Now recompute all bit lengths, scanning in increasing frequency.
10370   * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
10371   * lengths instead of fixing only the wrong ones. This idea is taken
10372   * from 'ar' written by Haruhiko Okumura.)
10373   */
10374  for (bits = max_length; bits !== 0; bits--) {
10375    n = s.bl_count[bits];
10376    while (n !== 0) {
10377      m = s.heap[--h];
10378      if (m > max_code) { continue; }
10379      if (tree[m*2 + 1]/*.Len*/ !== bits) {
10380        // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
10381        s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
10382        tree[m*2 + 1]/*.Len*/ = bits;
10383      }
10384      n--;
10385    }
10386  }
10387}
10388
10389
10390/* ===========================================================================
10391 * Generate the codes for a given tree and bit counts (which need not be
10392 * optimal).
10393 * IN assertion: the array bl_count contains the bit length statistics for
10394 * the given tree and the field len is set for all tree elements.
10395 * OUT assertion: the field code is set for all tree elements of non
10396 *     zero code length.
10397 */
10398function gen_codes(tree, max_code, bl_count)
10399//    ct_data *tree;             /* the tree to decorate */
10400//    int max_code;              /* largest code with non zero frequency */
10401//    ushf *bl_count;            /* number of codes at each bit length */
10402{
10403  var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
10404  var code = 0;              /* running code value */
10405  var bits;                  /* bit index */
10406  var n;                     /* code index */
10407
10408  /* The distribution counts are first used to generate the code values
10409   * without bit reversal.
10410   */
10411  for (bits = 1; bits <= MAX_BITS; bits++) {
10412    next_code[bits] = code = (code + bl_count[bits-1]) << 1;
10413  }
10414  /* Check that the bit counts in bl_count are consistent. The last code
10415   * must be all ones.
10416   */
10417  //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
10418  //        "inconsistent bit counts");
10419  //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
10420
10421  for (n = 0;  n <= max_code; n++) {
10422    var len = tree[n*2 + 1]/*.Len*/;
10423    if (len === 0) { continue; }
10424    /* Now reverse the bits */
10425    tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
10426
10427    //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
10428    //     n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
10429  }
10430}
10431
10432
10433/* ===========================================================================
10434 * Initialize the various 'constant' tables.
10435 */
10436function tr_static_init() {
10437  var n;        /* iterates over tree elements */
10438  var bits;     /* bit counter */
10439  var length;   /* length value */
10440  var code;     /* code value */
10441  var dist;     /* distance index */
10442  var bl_count = new Array(MAX_BITS+1);
10443  /* number of codes at each bit length for an optimal tree */
10444
10445  // do check in _tr_init()
10446  //if (static_init_done) return;
10447
10448  /* For some embedded targets, global variables are not initialized: */
10449/*#ifdef NO_INIT_GLOBAL_POINTERS
10450  static_l_desc.static_tree = static_ltree;
10451  static_l_desc.extra_bits = extra_lbits;
10452  static_d_desc.static_tree = static_dtree;
10453  static_d_desc.extra_bits = extra_dbits;
10454  static_bl_desc.extra_bits = extra_blbits;
10455#endif*/
10456
10457  /* Initialize the mapping length (0..255) -> length code (0..28) */
10458  length = 0;
10459  for (code = 0; code < LENGTH_CODES-1; code++) {
10460    base_length[code] = length;
10461    for (n = 0; n < (1<<extra_lbits[code]); n++) {
10462      _length_code[length++] = code;
10463    }
10464  }
10465  //Assert (length == 256, "tr_static_init: length != 256");
10466  /* Note that the length 255 (match length 258) can be represented
10467   * in two different ways: code 284 + 5 bits or code 285, so we
10468   * overwrite length_code[255] to use the best encoding:
10469   */
10470  _length_code[length-1] = code;
10471
10472  /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
10473  dist = 0;
10474  for (code = 0 ; code < 16; code++) {
10475    base_dist[code] = dist;
10476    for (n = 0; n < (1<<extra_dbits[code]); n++) {
10477      _dist_code[dist++] = code;
10478    }
10479  }
10480  //Assert (dist == 256, "tr_static_init: dist != 256");
10481  dist >>= 7; /* from now on, all distances are divided by 128 */
10482  for (; code < D_CODES; code++) {
10483    base_dist[code] = dist << 7;
10484    for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
10485      _dist_code[256 + dist++] = code;
10486    }
10487  }
10488  //Assert (dist == 256, "tr_static_init: 256+dist != 512");
10489
10490  /* Construct the codes of the static literal tree */
10491  for (bits = 0; bits <= MAX_BITS; bits++) {
10492    bl_count[bits] = 0;
10493  }
10494
10495  n = 0;
10496  while (n <= 143) {
10497    static_ltree[n*2 + 1]/*.Len*/ = 8;
10498    n++;
10499    bl_count[8]++;
10500  }
10501  while (n <= 255) {
10502    static_ltree[n*2 + 1]/*.Len*/ = 9;
10503    n++;
10504    bl_count[9]++;
10505  }
10506  while (n <= 279) {
10507    static_ltree[n*2 + 1]/*.Len*/ = 7;
10508    n++;
10509    bl_count[7]++;
10510  }
10511  while (n <= 287) {
10512    static_ltree[n*2 + 1]/*.Len*/ = 8;
10513    n++;
10514    bl_count[8]++;
10515  }
10516  /* Codes 286 and 287 do not exist, but we must include them in the
10517   * tree construction to get a canonical Huffman tree (longest code
10518   * all ones)
10519   */
10520  gen_codes(static_ltree, L_CODES+1, bl_count);
10521
10522  /* The static distance tree is trivial: */
10523  for (n = 0; n < D_CODES; n++) {
10524    static_dtree[n*2 + 1]/*.Len*/ = 5;
10525    static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
10526  }
10527
10528  // Now data ready and we can init static trees
10529  static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
10530  static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS);
10531  static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0,         BL_CODES, MAX_BL_BITS);
10532
10533  //static_init_done = true;
10534}
10535
10536
10537/* ===========================================================================
10538 * Initialize a new block.
10539 */
10540function init_block(s) {
10541  var n; /* iterates over tree elements */
10542
10543  /* Initialize the trees. */
10544  for (n = 0; n < L_CODES;  n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
10545  for (n = 0; n < D_CODES;  n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
10546  for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
10547
10548  s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
10549  s.opt_len = s.static_len = 0;
10550  s.last_lit = s.matches = 0;
10551}
10552
10553
10554/* ===========================================================================
10555 * Flush the bit buffer and align the output on a byte boundary
10556 */
10557function bi_windup(s)
10558{
10559  if (s.bi_valid > 8) {
10560    put_short(s, s.bi_buf);
10561  } else if (s.bi_valid > 0) {
10562    //put_byte(s, (Byte)s->bi_buf);
10563    s.pending_buf[s.pending++] = s.bi_buf;
10564  }
10565  s.bi_buf = 0;
10566  s.bi_valid = 0;
10567}
10568
10569/* ===========================================================================
10570 * Copy a stored block, storing first the length and its
10571 * one's complement if requested.
10572 */
10573function copy_block(s, buf, len, header)
10574//DeflateState *s;
10575//charf    *buf;    /* the input data */
10576//unsigned len;     /* its length */
10577//int      header;  /* true if block header must be written */
10578{
10579  bi_windup(s);        /* align on byte boundary */
10580
10581  if (header) {
10582    put_short(s, len);
10583    put_short(s, ~len);
10584  }
10585//  while (len--) {
10586//    put_byte(s, *buf++);
10587//  }
10588  utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
10589  s.pending += len;
10590}
10591
10592/* ===========================================================================
10593 * Compares to subtrees, using the tree depth as tie breaker when
10594 * the subtrees have equal frequency. This minimizes the worst case length.
10595 */
10596function smaller(tree, n, m, depth) {
10597  var _n2 = n*2;
10598  var _m2 = m*2;
10599  return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
10600         (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
10601}
10602
10603/* ===========================================================================
10604 * Restore the heap property by moving down the tree starting at node k,
10605 * exchanging a node with the smallest of its two sons if necessary, stopping
10606 * when the heap property is re-established (each father smaller than its
10607 * two sons).
10608 */
10609function pqdownheap(s, tree, k)
10610//    deflate_state *s;
10611//    ct_data *tree;  /* the tree to restore */
10612//    int k;               /* node to move down */
10613{
10614  var v = s.heap[k];
10615  var j = k << 1;  /* left son of k */
10616  while (j <= s.heap_len) {
10617    /* Set j to the smallest of the two sons: */
10618    if (j < s.heap_len &&
10619      smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
10620      j++;
10621    }
10622    /* Exit if v is smaller than both sons */
10623    if (smaller(tree, v, s.heap[j], s.depth)) { break; }
10624
10625    /* Exchange v with the smallest son */
10626    s.heap[k] = s.heap[j];
10627    k = j;
10628
10629    /* And continue down the tree, setting j to the left son of k */
10630    j <<= 1;
10631  }
10632  s.heap[k] = v;
10633}
10634
10635
10636// inlined manually
10637// var SMALLEST = 1;
10638
10639/* ===========================================================================
10640 * Send the block data compressed using the given Huffman trees
10641 */
10642function compress_block(s, ltree, dtree)
10643//    deflate_state *s;
10644//    const ct_data *ltree; /* literal tree */
10645//    const ct_data *dtree; /* distance tree */
10646{
10647  var dist;           /* distance of matched string */
10648  var lc;             /* match length or unmatched char (if dist == 0) */
10649  var lx = 0;         /* running index in l_buf */
10650  var code;           /* the code to send */
10651  var extra;          /* number of extra bits to send */
10652
10653  if (s.last_lit !== 0) {
10654    do {
10655      dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
10656      lc = s.pending_buf[s.l_buf + lx];
10657      lx++;
10658
10659      if (dist === 0) {
10660        send_code(s, lc, ltree); /* send a literal byte */
10661        //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
10662      } else {
10663        /* Here, lc is the match length - MIN_MATCH */
10664        code = _length_code[lc];
10665        send_code(s, code+LITERALS+1, ltree); /* send the length code */
10666        extra = extra_lbits[code];
10667        if (extra !== 0) {
10668          lc -= base_length[code];
10669          send_bits(s, lc, extra);       /* send the extra length bits */
10670        }
10671        dist--; /* dist is now the match distance - 1 */
10672        code = d_code(dist);
10673        //Assert (code < D_CODES, "bad d_code");
10674
10675        send_code(s, code, dtree);       /* send the distance code */
10676        extra = extra_dbits[code];
10677        if (extra !== 0) {
10678          dist -= base_dist[code];
10679          send_bits(s, dist, extra);   /* send the extra distance bits */
10680        }
10681      } /* literal or match pair ? */
10682
10683      /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
10684      //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
10685      //       "pendingBuf overflow");
10686
10687    } while (lx < s.last_lit);
10688  }
10689
10690  send_code(s, END_BLOCK, ltree);
10691}
10692
10693
10694/* ===========================================================================
10695 * Construct one Huffman tree and assigns the code bit strings and lengths.
10696 * Update the total bit length for the current block.
10697 * IN assertion: the field freq is set for all tree elements.
10698 * OUT assertions: the fields len and code are set to the optimal bit length
10699 *     and corresponding code. The length opt_len is updated; static_len is
10700 *     also updated if stree is not null. The field max_code is set.
10701 */
10702function build_tree(s, desc)
10703//    deflate_state *s;
10704//    tree_desc *desc; /* the tree descriptor */
10705{
10706  var tree     = desc.dyn_tree;
10707  var stree    = desc.stat_desc.static_tree;
10708  var has_stree = desc.stat_desc.has_stree;
10709  var elems    = desc.stat_desc.elems;
10710  var n, m;          /* iterate over heap elements */
10711  var max_code = -1; /* largest code with non zero frequency */
10712  var node;          /* new node being created */
10713
10714  /* Construct the initial heap, with least frequent element in
10715   * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
10716   * heap[0] is not used.
10717   */
10718  s.heap_len = 0;
10719  s.heap_max = HEAP_SIZE;
10720
10721  for (n = 0; n < elems; n++) {
10722    if (tree[n * 2]/*.Freq*/ !== 0) {
10723      s.heap[++s.heap_len] = max_code = n;
10724      s.depth[n] = 0;
10725
10726    } else {
10727      tree[n*2 + 1]/*.Len*/ = 0;
10728    }
10729  }
10730
10731  /* The pkzip format requires that at least one distance code exists,
10732   * and that at least one bit should be sent even if there is only one
10733   * possible code. So to avoid special checks later on we force at least
10734   * two codes of non zero frequency.
10735   */
10736  while (s.heap_len < 2) {
10737    node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
10738    tree[node * 2]/*.Freq*/ = 1;
10739    s.depth[node] = 0;
10740    s.opt_len--;
10741
10742    if (has_stree) {
10743      s.static_len -= stree[node*2 + 1]/*.Len*/;
10744    }
10745    /* node is 0 or 1 so it does not have extra bits */
10746  }
10747  desc.max_code = max_code;
10748
10749  /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
10750   * establish sub-heaps of increasing lengths:
10751   */
10752  for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
10753
10754  /* Construct the Huffman tree by repeatedly combining the least two
10755   * frequent nodes.
10756   */
10757  node = elems;              /* next internal node of the tree */
10758  do {
10759    //pqremove(s, tree, n);  /* n = node of least frequency */
10760    /*** pqremove ***/
10761    n = s.heap[1/*SMALLEST*/];
10762    s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
10763    pqdownheap(s, tree, 1/*SMALLEST*/);
10764    /***/
10765
10766    m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
10767
10768    s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
10769    s.heap[--s.heap_max] = m;
10770
10771    /* Create a new node father of n and m */
10772    tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
10773    s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
10774    tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
10775
10776    /* and insert the new node in the heap */
10777    s.heap[1/*SMALLEST*/] = node++;
10778    pqdownheap(s, tree, 1/*SMALLEST*/);
10779
10780  } while (s.heap_len >= 2);
10781
10782  s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
10783
10784  /* At this point, the fields freq and dad are set. We can now
10785   * generate the bit lengths.
10786   */
10787  gen_bitlen(s, desc);
10788
10789  /* The field len is now set, we can generate the bit codes */
10790  gen_codes(tree, max_code, s.bl_count);
10791}
10792
10793
10794/* ===========================================================================
10795 * Scan a literal or distance tree to determine the frequencies of the codes
10796 * in the bit length tree.
10797 */
10798function scan_tree(s, tree, max_code)
10799//    deflate_state *s;
10800//    ct_data *tree;   /* the tree to be scanned */
10801//    int max_code;    /* and its largest code of non zero frequency */
10802{
10803  var n;                     /* iterates over all tree elements */
10804  var prevlen = -1;          /* last emitted length */
10805  var curlen;                /* length of current code */
10806
10807  var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
10808
10809  var count = 0;             /* repeat count of the current code */
10810  var max_count = 7;         /* max repeat count */
10811  var min_count = 4;         /* min repeat count */
10812
10813  if (nextlen === 0) {
10814    max_count = 138;
10815    min_count = 3;
10816  }
10817  tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
10818
10819  for (n = 0; n <= max_code; n++) {
10820    curlen = nextlen;
10821    nextlen = tree[(n+1)*2 + 1]/*.Len*/;
10822
10823    if (++count < max_count && curlen === nextlen) {
10824      continue;
10825
10826    } else if (count < min_count) {
10827      s.bl_tree[curlen * 2]/*.Freq*/ += count;
10828
10829    } else if (curlen !== 0) {
10830
10831      if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
10832      s.bl_tree[REP_3_6*2]/*.Freq*/++;
10833
10834    } else if (count <= 10) {
10835      s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
10836
10837    } else {
10838      s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
10839    }
10840
10841    count = 0;
10842    prevlen = curlen;
10843
10844    if (nextlen === 0) {
10845      max_count = 138;
10846      min_count = 3;
10847
10848    } else if (curlen === nextlen) {
10849      max_count = 6;
10850      min_count = 3;
10851
10852    } else {
10853      max_count = 7;
10854      min_count = 4;
10855    }
10856  }
10857}
10858
10859
10860/* ===========================================================================
10861 * Send a literal or distance tree in compressed form, using the codes in
10862 * bl_tree.
10863 */
10864function send_tree(s, tree, max_code)
10865//    deflate_state *s;
10866//    ct_data *tree; /* the tree to be scanned */
10867//    int max_code;       /* and its largest code of non zero frequency */
10868{
10869  var n;                     /* iterates over all tree elements */
10870  var prevlen = -1;          /* last emitted length */
10871  var curlen;                /* length of current code */
10872
10873  var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
10874
10875  var count = 0;             /* repeat count of the current code */
10876  var max_count = 7;         /* max repeat count */
10877  var min_count = 4;         /* min repeat count */
10878
10879  /* tree[max_code+1].Len = -1; */  /* guard already set */
10880  if (nextlen === 0) {
10881    max_count = 138;
10882    min_count = 3;
10883  }
10884
10885  for (n = 0; n <= max_code; n++) {
10886    curlen = nextlen;
10887    nextlen = tree[(n+1)*2 + 1]/*.Len*/;
10888
10889    if (++count < max_count && curlen === nextlen) {
10890      continue;
10891
10892    } else if (count < min_count) {
10893      do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
10894
10895    } else if (curlen !== 0) {
10896      if (curlen !== prevlen) {
10897        send_code(s, curlen, s.bl_tree);
10898        count--;
10899      }
10900      //Assert(count >= 3 && count <= 6, " 3_6?");
10901      send_code(s, REP_3_6, s.bl_tree);
10902      send_bits(s, count-3, 2);
10903
10904    } else if (count <= 10) {
10905      send_code(s, REPZ_3_10, s.bl_tree);
10906      send_bits(s, count-3, 3);
10907
10908    } else {
10909      send_code(s, REPZ_11_138, s.bl_tree);
10910      send_bits(s, count-11, 7);
10911    }
10912
10913    count = 0;
10914    prevlen = curlen;
10915    if (nextlen === 0) {
10916      max_count = 138;
10917      min_count = 3;
10918
10919    } else if (curlen === nextlen) {
10920      max_count = 6;
10921      min_count = 3;
10922
10923    } else {
10924      max_count = 7;
10925      min_count = 4;
10926    }
10927  }
10928}
10929
10930
10931/* ===========================================================================
10932 * Construct the Huffman tree for the bit lengths and return the index in
10933 * bl_order of the last bit length code to send.
10934 */
10935function build_bl_tree(s) {
10936  var max_blindex;  /* index of last bit length code of non zero freq */
10937
10938  /* Determine the bit length frequencies for literal and distance trees */
10939  scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
10940  scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
10941
10942  /* Build the bit length tree: */
10943  build_tree(s, s.bl_desc);
10944  /* opt_len now includes the length of the tree representations, except
10945   * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
10946   */
10947
10948  /* Determine the number of bit length codes to send. The pkzip format
10949   * requires that at least 4 bit length codes be sent. (appnote.txt says
10950   * 3 but the actual value used is 4.)
10951   */
10952  for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
10953    if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
10954      break;
10955    }
10956  }
10957  /* Update opt_len to include the bit length tree and counts */
10958  s.opt_len += 3*(max_blindex+1) + 5+5+4;
10959  //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
10960  //        s->opt_len, s->static_len));
10961
10962  return max_blindex;
10963}
10964
10965
10966/* ===========================================================================
10967 * Send the header for a block using dynamic Huffman trees: the counts, the
10968 * lengths of the bit length codes, the literal tree and the distance tree.
10969 * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
10970 */
10971function send_all_trees(s, lcodes, dcodes, blcodes)
10972//    deflate_state *s;
10973//    int lcodes, dcodes, blcodes; /* number of codes for each tree */
10974{
10975  var rank;                    /* index in bl_order */
10976
10977  //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
10978  //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
10979  //        "too many codes");
10980  //Tracev((stderr, "\nbl counts: "));
10981  send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
10982  send_bits(s, dcodes-1,   5);
10983  send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
10984  for (rank = 0; rank < blcodes; rank++) {
10985    //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
10986    send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
10987  }
10988  //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
10989
10990  send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
10991  //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
10992
10993  send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
10994  //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
10995}
10996
10997
10998/* ===========================================================================
10999 * Check if the data type is TEXT or BINARY, using the following algorithm:
11000 * - TEXT if the two conditions below are satisfied:
11001 *    a) There are no non-portable control characters belonging to the
11002 *       "black list" (0..6, 14..25, 28..31).
11003 *    b) There is at least one printable character belonging to the
11004 *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
11005 * - BINARY otherwise.
11006 * - The following partially-portable control characters form a
11007 *   "gray list" that is ignored in this detection algorithm:
11008 *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
11009 * IN assertion: the fields Freq of dyn_ltree are set.
11010 */
11011function detect_data_type(s) {
11012  /* black_mask is the bit mask of black-listed bytes
11013   * set bits 0..6, 14..25, and 28..31
11014   * 0xf3ffc07f = binary 11110011111111111100000001111111
11015   */
11016  var black_mask = 0xf3ffc07f;
11017  var n;
11018
11019  /* Check for non-textual ("black-listed") bytes. */
11020  for (n = 0; n <= 31; n++, black_mask >>>= 1) {
11021    if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
11022      return Z_BINARY;
11023    }
11024  }
11025
11026  /* Check for textual ("white-listed") bytes. */
11027  if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
11028      s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
11029    return Z_TEXT;
11030  }
11031  for (n = 32; n < LITERALS; n++) {
11032    if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
11033      return Z_TEXT;
11034    }
11035  }
11036
11037  /* There are no "black-listed" or "white-listed" bytes:
11038   * this stream either is empty or has tolerated ("gray-listed") bytes only.
11039   */
11040  return Z_BINARY;
11041}
11042
11043
11044var static_init_done = false;
11045
11046/* ===========================================================================
11047 * Initialize the tree data structures for a new zlib stream.
11048 */
11049function _tr_init(s)
11050{
11051
11052  if (!static_init_done) {
11053    tr_static_init();
11054    static_init_done = true;
11055  }
11056
11057  s.l_desc  = new TreeDesc(s.dyn_ltree, static_l_desc);
11058  s.d_desc  = new TreeDesc(s.dyn_dtree, static_d_desc);
11059  s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
11060
11061  s.bi_buf = 0;
11062  s.bi_valid = 0;
11063
11064  /* Initialize the first block of the first file: */
11065  init_block(s);
11066}
11067
11068
11069/* ===========================================================================
11070 * Send a stored block
11071 */
11072function _tr_stored_block(s, buf, stored_len, last)
11073//DeflateState *s;
11074//charf *buf;       /* input block */
11075//ulg stored_len;   /* length of input block */
11076//int last;         /* one if this is the last block for a file */
11077{
11078  send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3);    /* send block type */
11079  copy_block(s, buf, stored_len, true); /* with header */
11080}
11081
11082
11083/* ===========================================================================
11084 * Send one empty static block to give enough lookahead for inflate.
11085 * This takes 10 bits, of which 7 may remain in the bit buffer.
11086 */
11087function _tr_align(s) {
11088  send_bits(s, STATIC_TREES<<1, 3);
11089  send_code(s, END_BLOCK, static_ltree);
11090  bi_flush(s);
11091}
11092
11093
11094/* ===========================================================================
11095 * Determine the best encoding for the current block: dynamic trees, static
11096 * trees or store, and output the encoded block to the zip file.
11097 */
11098function _tr_flush_block(s, buf, stored_len, last)
11099//DeflateState *s;
11100//charf *buf;       /* input block, or NULL if too old */
11101//ulg stored_len;   /* length of input block */
11102//int last;         /* one if this is the last block for a file */
11103{
11104  var opt_lenb, static_lenb;  /* opt_len and static_len in bytes */
11105  var max_blindex = 0;        /* index of last bit length code of non zero freq */
11106
11107  /* Build the Huffman trees unless a stored block is forced */
11108  if (s.level > 0) {
11109
11110    /* Check if the file is binary or text */
11111    if (s.strm.data_type === Z_UNKNOWN) {
11112      s.strm.data_type = detect_data_type(s);
11113    }
11114
11115    /* Construct the literal and distance trees */
11116    build_tree(s, s.l_desc);
11117    // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
11118    //        s->static_len));
11119
11120    build_tree(s, s.d_desc);
11121    // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
11122    //        s->static_len));
11123    /* At this point, opt_len and static_len are the total bit lengths of
11124     * the compressed block data, excluding the tree representations.
11125     */
11126
11127    /* Build the bit length tree for the above two trees, and get the index
11128     * in bl_order of the last bit length code to send.
11129     */
11130    max_blindex = build_bl_tree(s);
11131
11132    /* Determine the best encoding. Compute the block lengths in bytes. */
11133    opt_lenb = (s.opt_len+3+7) >>> 3;
11134    static_lenb = (s.static_len+3+7) >>> 3;
11135
11136    // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
11137    //        opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
11138    //        s->last_lit));
11139
11140    if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
11141
11142  } else {
11143    // Assert(buf != (char*)0, "lost buf");
11144    opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
11145  }
11146
11147  if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
11148    /* 4: two words for the lengths */
11149
11150    /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
11151     * Otherwise we can't have processed more than WSIZE input bytes since
11152     * the last block flush, because compression would have been
11153     * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
11154     * transform a block into a stored block.
11155     */
11156    _tr_stored_block(s, buf, stored_len, last);
11157
11158  } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
11159
11160    send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
11161    compress_block(s, static_ltree, static_dtree);
11162
11163  } else {
11164    send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
11165    send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
11166    compress_block(s, s.dyn_ltree, s.dyn_dtree);
11167  }
11168  // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
11169  /* The above check is made mod 2^32, for files larger than 512 MB
11170   * and uLong implemented on 32 bits.
11171   */
11172  init_block(s);
11173
11174  if (last) {
11175    bi_windup(s);
11176  }
11177  // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
11178  //       s->compressed_len-7*last));
11179}
11180
11181/* ===========================================================================
11182 * Save the match info and tally the frequency counts. Return true if
11183 * the current block must be flushed.
11184 */
11185function _tr_tally(s, dist, lc)
11186//    deflate_state *s;
11187//    unsigned dist;  /* distance of matched string */
11188//    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
11189{
11190  //var out_length, in_length, dcode;
11191
11192  s.pending_buf[s.d_buf + s.last_lit * 2]     = (dist >>> 8) & 0xff;
11193  s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
11194
11195  s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
11196  s.last_lit++;
11197
11198  if (dist === 0) {
11199    /* lc is the unmatched char */
11200    s.dyn_ltree[lc*2]/*.Freq*/++;
11201  } else {
11202    s.matches++;
11203    /* Here, lc is the match length - MIN_MATCH */
11204    dist--;             /* dist = match distance - 1 */
11205    //Assert((ush)dist < (ush)MAX_DIST(s) &&
11206    //       (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
11207    //       (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
11208
11209    s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
11210    s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
11211  }
11212
11213// (!) This block is disabled in zlib defailts,
11214// don't enable it for binary compatibility
11215
11216//#ifdef TRUNCATE_BLOCK
11217//  /* Try to guess if it is profitable to stop the current block here */
11218//  if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
11219//    /* Compute an upper bound for the compressed length */
11220//    out_length = s.last_lit*8;
11221//    in_length = s.strstart - s.block_start;
11222//
11223//    for (dcode = 0; dcode < D_CODES; dcode++) {
11224//      out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
11225//    }
11226//    out_length >>>= 3;
11227//    //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
11228//    //       s->last_lit, in_length, out_length,
11229//    //       100L - out_length*100L/in_length));
11230//    if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
11231//      return true;
11232//    }
11233//  }
11234//#endif
11235
11236  return (s.last_lit === s.lit_bufsize-1);
11237  /* We avoid equality with lit_bufsize because of wraparound at 64K
11238   * on 16 bit machines and because stored blocks are restricted to
11239   * 64K-1 bytes.
11240   */
11241}
11242
11243exports._tr_init  = _tr_init;
11244exports._tr_stored_block = _tr_stored_block;
11245exports._tr_flush_block  = _tr_flush_block;
11246exports._tr_tally = _tr_tally;
11247exports._tr_align = _tr_align;
11248
11249},{"../utils/common":35}],47:[function(require,module,exports){
11250'use strict';
11251
11252
11253function ZStream() {
11254  /* next input byte */
11255  this.input = null; // JS specific, because we have no pointers
11256  this.next_in = 0;
11257  /* number of bytes available at input */
11258  this.avail_in = 0;
11259  /* total number of input bytes read so far */
11260  this.total_in = 0;
11261  /* next output byte should be put there */
11262  this.output = null; // JS specific, because we have no pointers
11263  this.next_out = 0;
11264  /* remaining free space at output */
11265  this.avail_out = 0;
11266  /* total number of bytes output so far */
11267  this.total_out = 0;
11268  /* last error message, NULL if no error */
11269  this.msg = ''/*Z_NULL*/;
11270  /* not visible by applications */
11271  this.state = null;
11272  /* best guess about the data type: binary or text */
11273  this.data_type = 2/*Z_UNKNOWN*/;
11274  /* adler32 value of the uncompressed data */
11275  this.adler = 0;
11276}
11277
11278module.exports = ZStream;
11279
11280},{}],48:[function(require,module,exports){
11281'use strict';
11282
11283module.exports = INTERNAL;
11284
11285function INTERNAL() {}
11286},{}],49:[function(require,module,exports){
11287'use strict';
11288var Promise = require('./promise');
11289var reject = require('./reject');
11290var resolve = require('./resolve');
11291var INTERNAL = require('./INTERNAL');
11292var handlers = require('./handlers');
11293module.exports = all;
11294function all(iterable) {
11295  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
11296    return reject(new TypeError('must be an array'));
11297  }
11298
11299  var len = iterable.length;
11300  var called = false;
11301  if (!len) {
11302    return resolve([]);
11303  }
11304
11305  var values = new Array(len);
11306  var resolved = 0;
11307  var i = -1;
11308  var promise = new Promise(INTERNAL);
11309  
11310  while (++i < len) {
11311    allResolver(iterable[i], i);
11312  }
11313  return promise;
11314  function allResolver(value, i) {
11315    resolve(value).then(resolveFromAll, function (error) {
11316      if (!called) {
11317        called = true;
11318        handlers.reject(promise, error);
11319      }
11320    });
11321    function resolveFromAll(outValue) {
11322      values[i] = outValue;
11323      if (++resolved === len & !called) {
11324        called = true;
11325        handlers.resolve(promise, values);
11326      }
11327    }
11328  }
11329}
11330},{"./INTERNAL":48,"./handlers":50,"./promise":52,"./reject":55,"./resolve":56}],50:[function(require,module,exports){
11331'use strict';
11332var tryCatch = require('./tryCatch');
11333var resolveThenable = require('./resolveThenable');
11334var states = require('./states');
11335
11336exports.resolve = function (self, value) {
11337  var result = tryCatch(getThen, value);
11338  if (result.status === 'error') {
11339    return exports.reject(self, result.value);
11340  }
11341  var thenable = result.value;
11342
11343  if (thenable) {
11344    resolveThenable.safely(self, thenable);
11345  } else {
11346    self.state = states.FULFILLED;
11347    self.outcome = value;
11348    var i = -1;
11349    var len = self.queue.length;
11350    while (++i < len) {
11351      self.queue[i].callFulfilled(value);
11352    }
11353  }
11354  return self;
11355};
11356exports.reject = function (self, error) {
11357  self.state = states.REJECTED;
11358  self.outcome = error;
11359  var i = -1;
11360  var len = self.queue.length;
11361  while (++i < len) {
11362    self.queue[i].callRejected(error);
11363  }
11364  return self;
11365};
11366
11367function getThen(obj) {
11368  // Make sure we only access the accessor once as required by the spec
11369  var then = obj && obj.then;
11370  if (obj && typeof obj === 'object' && typeof then === 'function') {
11371    return function appyThen() {
11372      then.apply(obj, arguments);
11373    };
11374  }
11375}
11376
11377},{"./resolveThenable":57,"./states":58,"./tryCatch":59}],51:[function(require,module,exports){
11378module.exports = exports = require('./promise');
11379
11380exports.resolve = require('./resolve');
11381exports.reject = require('./reject');
11382exports.all = require('./all');
11383exports.race = require('./race');
11384
11385},{"./all":49,"./promise":52,"./race":54,"./reject":55,"./resolve":56}],52:[function(require,module,exports){
11386'use strict';
11387
11388var unwrap = require('./unwrap');
11389var INTERNAL = require('./INTERNAL');
11390var resolveThenable = require('./resolveThenable');
11391var states = require('./states');
11392var QueueItem = require('./queueItem');
11393
11394module.exports = Promise;
11395function Promise(resolver) {
11396  if (!(this instanceof Promise)) {
11397    return new Promise(resolver);
11398  }
11399  if (typeof resolver !== 'function') {
11400    throw new TypeError('resolver must be a function');
11401  }
11402  this.state = states.PENDING;
11403  this.queue = [];
11404  this.outcome = void 0;
11405  if (resolver !== INTERNAL) {
11406    resolveThenable.safely(this, resolver);
11407  }
11408}
11409
11410Promise.prototype['catch'] = function (onRejected) {
11411  return this.then(null, onRejected);
11412};
11413Promise.prototype.then = function (onFulfilled, onRejected) {
11414  if (typeof onFulfilled !== 'function' && this.state === states.FULFILLED ||
11415    typeof onRejected !== 'function' && this.state === states.REJECTED) {
11416    return this;
11417  }
11418  var promise = new Promise(INTERNAL);
11419  if (this.state !== states.PENDING) {
11420    var resolver = this.state === states.FULFILLED ? onFulfilled : onRejected;
11421    unwrap(promise, resolver, this.outcome);
11422  } else {
11423    this.queue.push(new QueueItem(promise, onFulfilled, onRejected));
11424  }
11425
11426  return promise;
11427};
11428
11429},{"./INTERNAL":48,"./queueItem":53,"./resolveThenable":57,"./states":58,"./unwrap":60}],53:[function(require,module,exports){
11430'use strict';
11431var handlers = require('./handlers');
11432var unwrap = require('./unwrap');
11433
11434module.exports = QueueItem;
11435function QueueItem(promise, onFulfilled, onRejected) {
11436  this.promise = promise;
11437  if (typeof onFulfilled === 'function') {
11438    this.onFulfilled = onFulfilled;
11439    this.callFulfilled = this.otherCallFulfilled;
11440  }
11441  if (typeof onRejected === 'function') {
11442    this.onRejected = onRejected;
11443    this.callRejected = this.otherCallRejected;
11444  }
11445}
11446QueueItem.prototype.callFulfilled = function (value) {
11447  handlers.resolve(this.promise, value);
11448};
11449QueueItem.prototype.otherCallFulfilled = function (value) {
11450  unwrap(this.promise, this.onFulfilled, value);
11451};
11452QueueItem.prototype.callRejected = function (value) {
11453  handlers.reject(this.promise, value);
11454};
11455QueueItem.prototype.otherCallRejected = function (value) {
11456  unwrap(this.promise, this.onRejected, value);
11457};
11458
11459},{"./handlers":50,"./unwrap":60}],54:[function(require,module,exports){
11460'use strict';
11461var Promise = require('./promise');
11462var reject = require('./reject');
11463var resolve = require('./resolve');
11464var INTERNAL = require('./INTERNAL');
11465var handlers = require('./handlers');
11466module.exports = race;
11467function race(iterable) {
11468  if (Object.prototype.toString.call(iterable) !== '[object Array]') {
11469    return reject(new TypeError('must be an array'));
11470  }
11471
11472  var len = iterable.length;
11473  var called = false;
11474  if (!len) {
11475    return resolve([]);
11476  }
11477
11478  var i = -1;
11479  var promise = new Promise(INTERNAL);
11480
11481  while (++i < len) {
11482    resolver(iterable[i]);
11483  }
11484  return promise;
11485  function resolver(value) {
11486    resolve(value).then(function (response) {
11487      if (!called) {
11488        called = true;
11489        handlers.resolve(promise, response);
11490      }
11491    }, function (error) {
11492      if (!called) {
11493        called = true;
11494        handlers.reject(promise, error);
11495      }
11496    });
11497  }
11498}
11499
11500},{"./INTERNAL":48,"./handlers":50,"./promise":52,"./reject":55,"./resolve":56}],55:[function(require,module,exports){
11501'use strict';
11502
11503var Promise = require('./promise');
11504var INTERNAL = require('./INTERNAL');
11505var handlers = require('./handlers');
11506module.exports = reject;
11507
11508function reject(reason) {
11509	var promise = new Promise(INTERNAL);
11510	return handlers.reject(promise, reason);
11511}
11512},{"./INTERNAL":48,"./handlers":50,"./promise":52}],56:[function(require,module,exports){
11513'use strict';
11514
11515var Promise = require('./promise');
11516var INTERNAL = require('./INTERNAL');
11517var handlers = require('./handlers');
11518module.exports = resolve;
11519
11520var FALSE = handlers.resolve(new Promise(INTERNAL), false);
11521var NULL = handlers.resolve(new Promise(INTERNAL), null);
11522var UNDEFINED = handlers.resolve(new Promise(INTERNAL), void 0);
11523var ZERO = handlers.resolve(new Promise(INTERNAL), 0);
11524var EMPTYSTRING = handlers.resolve(new Promise(INTERNAL), '');
11525
11526function resolve(value) {
11527  if (value) {
11528    if (value instanceof Promise) {
11529      return value;
11530    }
11531    return handlers.resolve(new Promise(INTERNAL), value);
11532  }
11533  var valueType = typeof value;
11534  switch (valueType) {
11535    case 'boolean':
11536      return FALSE;
11537    case 'undefined':
11538      return UNDEFINED;
11539    case 'object':
11540      return NULL;
11541    case 'number':
11542      return ZERO;
11543    case 'string':
11544      return EMPTYSTRING;
11545  }
11546}
11547},{"./INTERNAL":48,"./handlers":50,"./promise":52}],57:[function(require,module,exports){
11548'use strict';
11549var handlers = require('./handlers');
11550var tryCatch = require('./tryCatch');
11551function safelyResolveThenable(self, thenable) {
11552  // Either fulfill, reject or reject with error
11553  var called = false;
11554  function onError(value) {
11555    if (called) {
11556      return;
11557    }
11558    called = true;
11559    handlers.reject(self, value);
11560  }
11561
11562  function onSuccess(value) {
11563    if (called) {
11564      return;
11565    }
11566    called = true;
11567    handlers.resolve(self, value);
11568  }
11569
11570  function tryToUnwrap() {
11571    thenable(onSuccess, onError);
11572  }
11573  
11574  var result = tryCatch(tryToUnwrap);
11575  if (result.status === 'error') {
11576    onError(result.value);
11577  }
11578}
11579exports.safely = safelyResolveThenable;
11580},{"./handlers":50,"./tryCatch":59}],58:[function(require,module,exports){
11581// Lazy man's symbols for states
11582
11583exports.REJECTED = ['REJECTED'];
11584exports.FULFILLED = ['FULFILLED'];
11585exports.PENDING = ['PENDING'];
11586
11587},{}],59:[function(require,module,exports){
11588'use strict';
11589
11590module.exports = tryCatch;
11591
11592function tryCatch(func, value) {
11593  var out = {};
11594  try {
11595    out.value = func(value);
11596    out.status = 'success';
11597  } catch (e) {
11598    out.status = 'error';
11599    out.value = e;
11600  }
11601  return out;
11602}
11603},{}],60:[function(require,module,exports){
11604'use strict';
11605
11606var immediate = require('immediate');
11607var handlers = require('./handlers');
11608module.exports = unwrap;
11609
11610function unwrap(promise, func, value) {
11611  immediate(function () {
11612    var returnValue;
11613    try {
11614      returnValue = func(value);
11615    } catch (e) {
11616      return handlers.reject(promise, e);
11617    }
11618    if (returnValue === promise) {
11619      handlers.reject(promise, new TypeError('Cannot resolve promise with itself'));
11620    } else {
11621      handlers.resolve(promise, returnValue);
11622    }
11623  });
11624}
11625},{"./handlers":50,"immediate":61}],61:[function(require,module,exports){
11626(function (global){
11627'use strict';
11628var Mutation = global.MutationObserver || global.WebKitMutationObserver;
11629
11630var scheduleDrain;
11631
11632{
11633  if (Mutation) {
11634    var called = 0;
11635    var observer = new Mutation(nextTick);
11636    var element = global.document.createTextNode('');
11637    observer.observe(element, {
11638      characterData: true
11639    });
11640    scheduleDrain = function () {
11641      element.data = (called = ++called % 2);
11642    };
11643  }
11643 else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {
11644    var channel = new global.MessageChannel();
11645    channel.port1.onmessage = nextTick;
11646    scheduleDrain = function () {
11647      channel.port2.postMessage(0);
11648    };
11649  } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {
11650    scheduleDrain = function () {
11651
11652      // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
11653      // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
11654      var scriptEl = global.document.createElement('script');
11655      scriptEl.onreadystatechange = function () {
11656        nextTick();
11657
11658        scriptEl.onreadystatechange = null;
11659        scriptEl.parentNode.removeChild(scriptEl);
11660        scriptEl = null;
11661      };
11662      global.document.documentElement.appendChild(scriptEl);
11663    };
11664  } else {
11665    scheduleDrain = function () {
11666      setTimeout(nextTick, 0);
11667    };
11668  }
11669}
11670
11671var draining;
11672var queue = [];
11673//named nextTick for less confusing stack traces
11674function nextTick() {
11675  draining = true;
11676  var i, oldQueue;
11677  var len = queue.length;
11678  while (len) {
11679    oldQueue = queue;
11680    queue = [];
11681    i = -1;
11682    while (++i < len) {
11683      oldQueue[i]();
11684    }
11685    len = queue.length;
11686  }
11687  draining = false;
11688}
11689
11690module.exports = immediate;
11691function immediate(task) {
11692  if (queue.push(task) === 1 && !draining) {
11693    scheduleDrain();
11694  }
11695}
11696
11697}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11698},{}],62:[function(require,module,exports){
11699;(function () { // closure for web browsers
11700
11701if (typeof module === 'object' && module.exports) {
11702  module.exports = LRUCache
11703} else {
11704  // just set the global for non-node platforms.
11705  this.LRUCache = LRUCache
11706}
11707
11708function hOP (obj, key) {
11709  return Object.prototype.hasOwnProperty.call(obj, key)
11710}
11711
11712function naiveLength () { return 1 }
11713
11714function LRUCache (options) {
11715  if (!(this instanceof LRUCache))
11716    return new LRUCache(options)
11717
11718  if (typeof options === 'number')
11719    options = { max: options }
11720
11721  if (!options)
11722    options = {}
11723
11724  this._max = options.max
11725  // Kind of weird to have a default max of Infinity, but oh well.
11726  if (!this._max || !(typeof this._max === "number") || this._max <= 0 )
11727    this._max = Infinity
11728
11729  this._lengthCalculator = options.length || naiveLength
11730  if (typeof this._lengthCalculator !== "function")
11731    this._lengthCalculator = naiveLength
11732
11733  this._allowStale = options.stale || false
11734  this._maxAge = options.maxAge || null
11735  this._dispose = options.dispose
11736  this.reset()
11737}
11738
11739// resize the cache when the max changes.
11740Object.defineProperty(LRUCache.prototype, "max",
11741  { set : function (mL) {
11742      if (!mL || !(typeof mL === "number") || mL <= 0 ) mL = Infinity
11743      this._max = mL
11744      if (this._length > this._max) trim(this)
11745    }
11746  , get : function () { return this._max }
11747  , enumerable : true
11748  })
11749
11750// resize the cache when the lengthCalculator changes.
11751Object.defineProperty(LRUCache.prototype, "lengthCalculator",
11752  { set : function (lC) {
11753      if (typeof lC !== "function") {
11754        this._lengthCalculator = naiveLength
11755        this._length = this._itemCount
11756        for (var key in this._cache) {
11757          this._cache[key].length = 1
11758        }
11759      } else {
11760        this._lengthCalculator = lC
11761        this._length = 0
11762        for (var key in this._cache) {
11763          this._cache[key].length = this._lengthCalculator(this._cache[key].value)
11764          this._length += this._cache[key].length
11765        }
11766      }
11767
11768      if (this._length > this._max) trim(this)
11769    }
11770  , get : function () { return this._lengthCalculator }
11771  , enumerable : true
11772  })
11773
11774Object.defineProperty(LRUCache.prototype, "length",
11775  { get : function () { return this._length }
11776  , enumerable : true
11777  })
11778
11779
11780Object.defineProperty(LRUCache.prototype, "itemCount",
11781  { get : function () { return this._itemCount }
11782  , enumerable : true
11783  })
11784
11785LRUCache.prototype.forEach = function (fn, thisp) {
11786  thisp = thisp || this
11787  var i = 0
11788  var itemCount = this._itemCount
11789
11790  for (var k = this._mru - 1; k >= 0 && i < itemCount; k--) if (this._lruList[k]) {
11791    i++
11792    var hit = this._lruList[k]
11793    if (isStale(this, hit)) {
11794      del(this, hit)
11795      if (!this._allowStale) hit = undefined
11796    }
11797    if (hit) {
11798      fn.call(thisp, hit.value, hit.key, this)
11799    }
11800  }
11801}
11802
11803LRUCache.prototype.keys = function () {
11804  var keys = new Array(this._itemCount)
11805  var i = 0
11806  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
11807    var hit = this._lruList[k]
11808    keys[i++] = hit.key
11809  }
11810  return keys
11811}
11812
11813LRUCache.prototype.values = function () {
11814  var values = new Array(this._itemCount)
11815  var i = 0
11816  for (var k = this._mru - 1; k >= 0 && i < this._itemCount; k--) if (this._lruList[k]) {
11817    var hit = this._lruList[k]
11818    values[i++] = hit.value
11819  }
11820  return values
11821}
11822
11823LRUCache.prototype.reset = function () {
11824  if (this._dispose && this._cache) {
11825    for (var k in this._cache) {
11826      this._dispose(k, this._cache[k].value)
11827    }
11828  }
11829
11830  this._cache = Object.create(null) // hash of items by key
11831  this._lruList = Object.create(null) // list of items in order of use recency
11832  this._mru = 0 // most recently used
11833  this._lru = 0 // least recently used
11834  this._length = 0 // number of items in the list
11835  this._itemCount = 0
11836}
11837
11838// Provided for debugging/dev purposes only. No promises whatsoever that
11839// this API stays stable.
11840LRUCache.prototype.dump = function () {
11841  return this._cache
11842}
11843
11844LRUCache.prototype.dumpLru = function () {
11845  return this._lruList
11846}
11847
11848LRUCache.prototype.set = function (key, value, maxAge) {
11849  maxAge = maxAge || this._maxAge
11850  var now = maxAge ? Date.now() : 0
11851
11852  if (hOP(this._cache, key)) {
11853    // dispose of the old one before overwriting
11854    if (this._dispose)
11855      this._dispose(key, this._cache[key].value)
11856
11857    this._cache[key].now = now
11858    this._cache[key].maxAge = maxAge
11859    this._cache[key].value = value
11860    this.get(key)
11861    return true
11862  }
11863
11864  var len = this._lengthCalculator(value)
11865  var hit = new Entry(key, value, this._mru++, len, now, maxAge)
11866
11867  // oversized objects fall out of cache automatically.
11868  if (hit.length > this._max) {
11869    if (this._dispose) this._dispose(key, value)
11870    return false
11871  }
11872
11873  this._length += hit.length
11874  this._lruList[hit.lu] = this._cache[key] = hit
11875  this._itemCount ++
11876
11877  if (this._length > this._max)
11878    trim(this)
11879
11880  return true
11881}
11882
11883LRUCache.prototype.has = function (key) {
11884  if (!hOP(this._cache, key)) return false
11885  var hit = this._cache[key]
11886  if (isStale(this, hit)) {
11887    return false
11888  }
11889  return true
11890}
11891
11892LRUCache.prototype.get = function (key) {
11893  return get(this, key, true)
11894}
11895
11896LRUCache.prototype.peek = function (key) {
11897  return get(this, key, false)
11898}
11899
11900LRUCache.prototype.pop = function () {
11901  var hit = this._lruList[this._lru]
11902  del(this, hit)
11903  return hit || null
11904}
11905
11906LRUCache.prototype.del = function (key) {
11907  del(this, this._cache[key])
11908}
11909
11910function get (self, key, doUse) {
11911  var hit = self._cache[key]
11912  if (hit) {
11913    if (isStale(self, hit)) {
11914      del(self, hit)
11915      if (!self._allowStale) hit = undefined
11916    } else {
11917      if (doUse) use(self, hit)
11918    }
11919    if (hit) hit = hit.value
11920  }
11921  return hit
11922}
11923
11924function isStale(self, hit) {
11925  if (!hit || (!hit.maxAge && !self._maxAge)) return false
11926  var stale = false;
11927  var diff = Date.now() - hit.now
11928  if (hit.maxAge) {
11929    stale = diff > hit.maxAge
11930  } else {
11931    stale = self._maxAge && (diff > self._maxAge)
11932  }
11933  return stale;
11934}
11935
11936function use (self, hit) {
11937  shiftLU(self, hit)
11938  hit.lu = self._mru ++
11939  self._lruList[hit.lu] = hit
11940}
11941
11942function trim (self) {
11943  while (self._lru < self._mru && self._length > self._max)
11944    del(self, self._lruList[self._lru])
11945}
11946
11947function shiftLU (self, hit) {
11948  delete self._lruList[ hit.lu ]
11949  while (self._lru < self._mru && !self._lruList[self._lru]) self._lru ++
11950}
11951
11952function del (self, hit) {
11953  if (hit) {
11954    if (self._dispose) self._dispose(hit.key, hit.value)
11955    self._length -= hit.length
11956    self._itemCount --
11957    delete self._cache[ hit.key ]
11958    shiftLU(self, hit)
11959  }
11960}
11961
11962// classy, since V8 prefers predictable objects.
11963function Entry (key, value, lu, length, now, maxAge) {
11964  this.key = key
11965  this.value = value
11966  this.lu = lu
11967  this.length = length
11968  this.now = now
11969  if (maxAge) this.maxAge = maxAge
11970}
11971
11972})()
11973
11974},{}],63:[function(require,module,exports){
11975function dbfHeader(buffer){
11976	var data = new DataView(buffer);
11977	var out = {};
11978	out.lastUpdated = new Date(data.getUint8(1,true)+1900,data.getUint8(2,true),data.getUint8(3,true));
11979	out.records = data.getUint32(4,true);
11980	out.headerLen = data.getUint16(8,true);
11981	out.recLen = data.getUint16(10,true);
11982	return out;
11983}
11984
11985function dbfRowHeader(buffer){
11986	var data = new DataView(buffer);
11987	var out = [];
11988	var offset = 32;
11989	while(true){
11990		out.push({
11991			name : String.fromCharCode.apply(this,(new Uint8Array(buffer,offset,10))).replace(/\0|\s+$/g,''),
11992			dataType : String.fromCharCode(data.getUint8(offset+11)),
11993			len : data.getUint8(offset+16),
11994			decimal : data.getUint8(offset+17)
11995		});
11996		if(data.getUint8(offset+32)===13){
11997			break;
11998		}else{
11999			offset+=32;
12000		}
12001	}
12002	return out;
12003}
12004function rowFuncs(buffer,offset,len,type){
12005	var data = (new Uint8Array(buffer,offset,len));
12006	var textData = String.fromCharCode.apply(this,data).replace(/\0|\s+$/g,'');
12007	switch(type){
12008		case 'N':
12009		case 'F':
12010		case 'O':
12011			return parseFloat(textData,10);
12012		case 'D':
12013			return new Date(textData.slice(0,4), parseInt(textData.slice(4,6),10)-1, textData.slice(6,8));
12014		case 'L':
12015			return textData.toLowerCase() === 'y' || textData.toLowerCase() === 't';
12016		default:
12017			return textData;
12018	}
12019}
12020function parseRow(buffer,offset,rowHeaders){
12021	var out={};
12022	var i = 0;
12023	var len = rowHeaders.length;
12024	var field;
12025	var header;
12026	while(i<len){
12027		header = rowHeaders[i];
12028		field = rowFuncs(buffer,offset,header.len,header.dataType);
12029		offset += header.len;
12030		if(typeof field !== 'undefined'){
12031			out[header.name]=field;
12032		}
12033		i++;
12034	}
12035	return out;
12036}
12037module.exports = function(buffer){
12038	var rowHeaders = dbfRowHeader(buffer);
12039	var header = dbfHeader(buffer);
12040	var offset = ((rowHeaders.length+1)<<5)+2;
12041	var recLen = header.recLen;
12042	var records = header.records;
12043	var out = [];
12044	while(records){
12045		out.push(parseRow(buffer,offset,rowHeaders));
12046		offset += recLen;
12047		records--;
12048	}
12049	return out;
12050};
12051
12052},{}],64:[function(require,module,exports){
12053var mgrs = require('mgrs');
12054
12055function Point(x, y, z) {
12056  if (!(this instanceof Point)) {
12057    return new Point(x, y, z);
12058  }
12059  if (Array.isArray(x)) {
12060    this.x = x[0];
12061    this.y = x[1];
12062    this.z = x[2] || 0.0;
12063  }else if(typeof x === 'object'){
12064    this.x = x.x;
12065    this.y = x.y;
12066    this.z = x.z || 0.0;
12067  } else if (typeof x === 'string' && typeof y === 'undefined') {
12068    var coords = x.split(',');
12069    this.x = parseFloat(coords[0], 10);
12070    this.y = parseFloat(coords[1], 10);
12071    this.z = parseFloat(coords[2], 10) || 0.0;
12072  }
12073  else {
12074    this.x = x;
12075    this.y = y;
12076    this.z = z || 0.0;
12077  }
12078  console.warn('proj4.Point will be removed in version 3, use proj4.toPoint');
12079}
12080
12081Point.fromMGRS = function(mgrsStr) {
12082  return new Point(mgrs.toPoint(mgrsStr));
12083};
12084Point.prototype.toMGRS = function(accuracy) {
12085  return mgrs.forward([this.x, this.y], accuracy);
12086};
12087module.exports = Point;
12088},{"mgrs":131}],65:[function(require,module,exports){
12089var parseCode = require("./parseCode");
12090var extend = require('./extend');
12091var projections = require('./projections');
12092var deriveConstants = require('./deriveConstants');
12093
12094function Projection(srsCode,callback) {
12095  if (!(this instanceof Projection)) {
12096    return new Projection(srsCode);
12097  }
12098  callback = callback || function(error){
12099    if(error){
12100      throw error;
12101    }
12102  };
12103  var json = parseCode(srsCode);
12104  if(typeof json !== 'object'){
12105    callback(srsCode);
12106    return;
12107  }
12108  var modifiedJSON = deriveConstants(json);
12109  var ourProj = Projection.projections.get(modifiedJSON.projName);
12110  if(ourProj){
12111    extend(this, modifiedJSON);
12112    extend(this, ourProj);
12113    this.init();
12114    callback(null, this);
12115  }else{
12116    callback(srsCode);
12117  }
12118}
12119Projection.projections = projections;
12120Projection.projections.start();
12121module.exports = Projection;
12122
12123},{"./deriveConstants":96,"./extend":97,"./parseCode":101,"./projections":103}],66:[function(require,module,exports){
12124module.exports = function(crs, denorm, point) {
12125  var xin = point.x,
12126    yin = point.y,
12127    zin = point.z || 0.0;
12128  var v, t, i;
12129  for (i = 0; i < 3; i++) {
12130    if (denorm && i === 2 && point.z === undefined) {
12131      continue;
12132    }
12133    if (i === 0) {
12134      v = xin;
12135      t = 'x';
12136    }
12137    else if (i === 1) {
12138      v = yin;
12139      t = 'y';
12140    }
12141    else {
12142      v = zin;
12143      t = 'z';
12144    }
12145    switch (crs.axis[i]) {
12146    case 'e':
12147      point[t] = v;
12148      break;
12149    case 'w':
12150      point[t] = -v;
12151      break;
12152    case 'n':
12153      point[t] = v;
12154      break;
12155    case 's':
12156      point[t] = -v;
12157      break;
12158    case 'u':
12159      if (point[t] !== undefined) {
12160        point.z = v;
12161      }
12162      break;
12163    case 'd':
12164      if (point[t] !== undefined) {
12165        point.z = -v;
12166      }
12167      break;
12168    default:
12169      //console.log("ERROR: unknow axis ("+crs.axis[i]+") - check definition of "+crs.projName);
12170      return null;
12171    }
12172  }
12173  return point;
12174};
12175
12176},{}],67:[function(require,module,exports){
12177var HALF_PI = Math.PI/2;
12178var sign = require('./sign');
12179
12180module.exports = function(x) {
12181  return (Math.abs(x) < HALF_PI) ? x : (x - (sign(x) * Math.PI));
12182};
12183},{"./sign":84}],68:[function(require,module,exports){
12184var TWO_PI = Math.PI * 2;
12185// SPI is slightly greater than Math.PI, so values that exceed the -180..180
12186// degree range by a tiny amount don't get wrapped. This prevents points that
12187// have drifted from their original location along the 180th meridian (due to
12188// floating point error) from changing their sign.
12189var SPI = 3.14159265359;
12190var sign = require('./sign');
12191
12192module.exports = function(x) {
12193  return (Math.abs(x) <= SPI) ? x : (x - (sign(x) * TWO_PI));
12194};
12195},{"./sign":84}],69:[function(require,module,exports){
12196module.exports = function(x) {
12197  if (Math.abs(x) > 1) {
12198    x = (x > 1) ? 1 : -1;
12199  }
12200  return Math.asin(x);
12201};
12202},{}],70:[function(require,module,exports){
12203module.exports = function(x) {
12204  return (1 - 0.25 * x * (1 + x / 16 * (3 + 1.25 * x)));
12205};
12206},{}],71:[function(require,module,exports){
12207module.exports = function(x) {
12208  return (0.375 * x * (1 + 0.25 * x * (1 + 0.46875 * x)));
12209};
12210},{}],72:[function(require,module,exports){
12211module.exports = function(x) {
12212  return (0.05859375 * x * x * (1 + 0.75 * x));
12213};
12214},{}],73:[function(require,module,exports){
12215module.exports = function(x) {
12216  return (x * x * x * (35 / 3072));
12217};
12218},{}],74:[function(require,module,exports){
12219module.exports = function(a, e, sinphi) {
12220  var temp = e * sinphi;
12221  return a / Math.sqrt(1 - temp * temp);
12222};
12223},{}],75:[function(require,module,exports){
12224module.exports = function(ml, e0, e1, e2, e3) {
12225  var phi;
12226  var dphi;
12227
12228  phi = ml / e0;
12229  for (var i = 0; i < 15; i++) {
12230    dphi = (ml - (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi))) / (e0 - 2 * e1 * Math.cos(2 * phi) + 4 * e2 * Math.cos(4 * phi) - 6 * e3 * Math.cos(6 * phi));
12231    phi += dphi;
12232    if (Math.abs(dphi) <= 0.0000000001) {
12233      return phi;
12234    }
12235  }
12236
12237  //..reportError("IMLFN-CONV:Latitude failed to converge after 15 iterations");
12238  return NaN;
12239};
12240},{}],76:[function(require,module,exports){
12241var HALF_PI = Math.PI/2;
12242
12243module.exports = function(eccent, q) {
12244  var temp = 1 - (1 - eccent * eccent) / (2 * eccent) * Math.log((1 - eccent) / (1 + eccent));
12245  if (Math.abs(Math.abs(q) - temp) < 1.0E-6) {
12246    if (q < 0) {
12247      return (-1 * HALF_PI);
12248    }
12249    else {
12250      return HALF_PI;
12251    }
12252  }
12253  //var phi = 0.5* q/(1-eccent*eccent);
12254  var phi = Math.asin(0.5 * q);
12255  var dphi;
12256  var sin_phi;
12257  var cos_phi;
12258  var con;
12259  for (var i = 0; i < 30; i++) {
12260    sin_phi = Math.sin(phi);
12261    cos_phi = Math.cos(phi);
12262    con = eccent * sin_phi;
12263    dphi = Math.pow(1 - con * con, 2) / (2 * cos_phi) * (q / (1 - eccent * eccent) - sin_phi / (1 - con * con) + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
12264    phi += dphi;
12265    if (Math.abs(dphi) <= 0.0000000001) {
12266      return phi;
12267    }
12268  }
12269
12270  //console.log("IQSFN-CONV:Latitude failed to converge after 30 iterations");
12271  return NaN;
12272};
12273},{}],77:[function(require,module,exports){
12274module.exports = function(e0, e1, e2, e3, phi) {
12275  return (e0 * phi - e1 * Math.sin(2 * phi) + e2 * Math.sin(4 * phi) - e3 * Math.sin(6 * phi));
12276};
12277},{}],78:[function(require,module,exports){
12278module.exports = function(eccent, sinphi, cosphi) {
12279  var con = eccent * sinphi;
12280  return cosphi / (Math.sqrt(1 - con * con));
12281};
12282},{}],79:[function(require,module,exports){
12283var HALF_PI = Math.PI/2;
12284module.exports = function(eccent, ts) {
12285  var eccnth = 0.5 * eccent;
12286  var con, dphi;
12287  var phi = HALF_PI - 2 * Math.atan(ts);
12288  for (var i = 0; i <= 15; i++) {
12289    con = eccent * Math.sin(phi);
12290    dphi = HALF_PI - 2 * Math.atan(ts * (Math.pow(((1 - con) / (1 + con)), eccnth))) - phi;
12291    phi += dphi;
12292    if (Math.abs(dphi) <= 0.0000000001) {
12293      return phi;
12294    }
12295  }
12296  //console.log("phi2z has NoConvergence");
12297  return -9999;
12298};
12299},{}],80:[function(require,module,exports){
12300var C00 = 1;
12301var C02 = 0.25;
12302var C04 = 0.046875;
12303var C06 = 0.01953125;
12304var C08 = 0.01068115234375;
12305var C22 = 0.75;
12306var C44 = 0.46875;
12307var C46 = 0.01302083333333333333;
12308var C48 = 0.00712076822916666666;
12309var C66 = 0.36458333333333333333;
12310var C68 = 0.00569661458333333333;
12311var C88 = 0.3076171875;
12312
12313module.exports = function(es) {
12314  var en = [];
12315  en[0] = C00 - es * (C02 + es * (C04 + es * (C06 + es * C08)));
12316  en[1] = es * (C22 - es * (C04 + es * (C06 + es * C08)));
12317  var t = es * es;
12318  en[2] = t * (C44 - es * (C46 + es * C48));
12319  t *= es;
12320  en[3] = t * (C66 - es * C68);
12321  en[4] = t * es * C88;
12322  return en;
12323};
12324},{}],81:[function(require,module,exports){
12325var pj_mlfn = require("./pj_mlfn");
12326var EPSLN = 1.0e-10;
12327var MAX_ITER = 20;
12328module.exports = function(arg, es, en) {
12329  var k = 1 / (1 - es);
12330  var phi = arg;
12331  for (var i = MAX_ITER; i; --i) { /* rarely goes over 2 iterations */
12332    var s = Math.sin(phi);
12333    var t = 1 - es * s * s;
12334    //t = this.pj_mlfn(phi, s, Math.cos(phi), en) - arg;
12335    //phi -= t * (t * Math.sqrt(t)) * k;
12336    t = (pj_mlfn(phi, s, Math.cos(phi), en) - arg) * (t * Math.sqrt(t)) * k;
12337    phi -= t;
12338    if (Math.abs(t) < EPSLN) {
12339      return phi;
12340    }
12341  }
12342  //..reportError("cass:pj_inv_mlfn: Convergence error");
12343  return phi;
12344};
12345},{"./pj_mlfn":82}],82:[function(require,module,exports){
12346module.exports = function(phi, sphi, cphi, en) {
12347  cphi *= sphi;
12348  sphi *= sphi;
12349  return (en[0] * phi - cphi * (en[1] + sphi * (en[2] + sphi * (en[3] + sphi * en[4]))));
12350};
12351},{}],83:[function(require,module,exports){
12352module.exports = function(eccent, sinphi) {
12353  var con;
12354  if (eccent > 1.0e-7) {
12355    con = eccent * sinphi;
12356    return ((1 - eccent * eccent) * (sinphi / (1 - con * con) - (0.5 / eccent) * Math.log((1 - con) / (1 + con))));
12357  }
12358  else {
12359    return (2 * sinphi);
12360  }
12361};
12362},{}],84:[function(require,module,exports){
12363module.exports = function(x) {
12364  return x<0 ? -1 : 1;
12365};
12366},{}],85:[function(require,module,exports){
12367module.exports = function(esinp, exp) {
12368  return (Math.pow((1 - esinp) / (1 + esinp), exp));
12369};
12370},{}],86:[function(require,module,exports){
12371module.exports = function (array){
12372  var out = {
12373    x: array[0],
12374    y: array[1]
12375  };
12376  if (array.length>2) {
12377    out.z = array[2];
12378  }
12379  if (array.length>3) {
12380    out.m = array[3];
12381  }
12382  return out;
12383};
12384},{}],87:[function(require,module,exports){
12385var HALF_PI = Math.PI/2;
12386
12387module.exports = function(eccent, phi, sinphi) {
12388  var con = eccent * sinphi;
12389  var com = 0.5 * eccent;
12390  con = Math.pow(((1 - con) / (1 + con)), com);
12391  return (Math.tan(0.5 * (HALF_PI - phi)) / con);
12392};
12393},{}],88:[function(require,module,exports){
12394exports.wgs84 = {
12395  towgs84: "0,0,0",
12396  ellipse: "WGS84",
12397  datumName: "WGS84"
12398};
12399exports.ch1903 = {
12400  towgs84: "674.374,15.056,405.346",
12401  ellipse: "bessel",
12402  datumName: "swiss"
12403};
12404exports.ggrs87 = {
12405  towgs84: "-199.87,74.79,246.62",
12406  ellipse: "GRS80",
12407  datumName: "Greek_Geodetic_Reference_System_1987"
12408};
12409exports.nad83 = {
12410  towgs84: "0,0,0",
12411  ellipse: "GRS80",
12412  datumName: "North_American_Datum_1983"
12413};
12414exports.nad27 = {
12415  nadgrids: "@conus,@alaska,@ntv2_0.gsb,@ntv1_can.dat",
12416  ellipse: "clrk66",
12417  datumName: "North_American_Datum_1927"
12418};
12419exports.potsdam = {
12420  towgs84: "606.0,23.0,413.0",
12421  ellipse: "bessel",
12422  datumName: "Potsdam Rauenberg 1950 DHDN"
12423};
12424exports.carthage = {
12425  towgs84: "-263.0,6.0,431.0",
12426  ellipse: "clark80",
12427  datumName: "Carthage 1934 Tunisia"
12428};
12429exports.hermannskogel = {
12430  towgs84: "653.0,-212.0,449.0",
12431  ellipse: "bessel",
12432  datumName: "Hermannskogel"
12433};
12434exports.ire65 = {
12435  towgs84: "482.530,-130.596,564.557,-1.042,-0.214,-0.631,8.15",
12436  ellipse: "mod_airy",
12437  datumName: "Ireland 1965"
12438};
12439exports.rassadiran = {
12440  towgs84: "-133.63,-157.5,-158.62",
12441  ellipse: "intl",
12442  datumName: "Rassadiran"
12443};
12444exports.nzgd49 = {
12445  towgs84: "59.47,-5.04,187.44,0.47,-0.1,1.024,-4.5993",
12446  ellipse: "intl",
12447  datumName: "New Zealand Geodetic Datum 1949"
12448};
12449exports.osgb36 = {
12450  towgs84: "446.448,-125.157,542.060,0.1502,0.2470,0.8421,-20.4894",
12451  ellipse: "airy",
12452  datumName: "Airy 1830"
12453};
12454exports.s_jtsk = {
12455  towgs84: "589,76,480",
12456  ellipse: 'bessel',
12457  datumName: 'S-JTSK (Ferro)'
12458};
12459exports.beduaram = {
12460  towgs84: '-106,-87,188',
12461  ellipse: 'clrk80',
12462  datumName: 'Beduaram'
12463};
12464exports.gunung_segara = {
12465  towgs84: '-403,684,41',
12466  ellipse: 'bessel',
12467  datumName: 'Gunung Segara Jakarta'
12468};
12469exports.rnb72 = {
12470  towgs84: "106.869,-52.2978,103.724,-0.33657,0.456955,-1.84218,1",
12471  ellipse: "intl",
12472  datumName: "Reseau National Belge 1972"
12473};
12474},{}],89:[function(require,module,exports){
12475exports.MERIT = {
12476  a: 6378137.0,
12477  rf: 298.257,
12478  ellipseName: "MERIT 1983"
12479};
12480exports.SGS85 = {
12481  a: 6378136.0,
12482  rf: 298.257,
12483  ellipseName: "Soviet Geodetic System 85"
12484};
12485exports.GRS80 = {
12486  a: 6378137.0,
12487  rf: 298.257222101,
12488  ellipseName: "GRS 1980(IUGG, 1980)"
12489};
12490exports.IAU76 = {
12491  a: 6378140.0,
12492  rf: 298.257,
12493  ellipseName: "IAU 1976"
12494};
12495exports.airy = {
12496  a: 6377563.396,
12497  b: 6356256.910,
12498  ellipseName: "Airy 1830"
12499};
12500exports.APL4 = {
12501  a: 6378137,
12502  rf: 298.25,
12503  ellipseName: "Appl. Physics. 1965"
12504};
12505exports.NWL9D = {
12506  a: 6378145.0,
12507  rf: 298.25,
12508  ellipseName: "Naval Weapons Lab., 1965"
12509};
12510exports.mod_airy = {
12511  a: 6377340.189,
12512  b: 6356034.446,
12513  ellipseName: "Modified Airy"
12514};
12515exports.andrae = {
12516  a: 6377104.43,
12517  rf: 300.0,
12518  ellipseName: "Andrae 1876 (Den., Iclnd.)"
12519};
12520exports.aust_SA = {
12521  a: 6378160.0,
12522  rf: 298.25,
12523  ellipseName: "Australian Natl & S. Amer. 1969"
12524};
12525exports.GRS67 = {
12526  a: 6378160.0,
12527  rf: 298.2471674270,
12528  ellipseName: "GRS 67(IUGG 1967)"
12529};
12530exports.bessel = {
12531  a: 6377397.155,
12532  rf: 299.1528128,
12533  ellipseName: "Bessel 1841"
12534};
12535exports.bess_nam = {
12536  a: 6377483.865,
12537  rf: 299.1528128,
12538  ellipseName: "Bessel 1841 (Namibia)"
12539};
12540exports.clrk66 = {
12541  a: 6378206.4,
12542  b: 6356583.8,
12543  ellipseName: "Clarke 1866"
12544};
12545exports.clrk80 = {
12546  a: 6378249.145,
12547  rf: 293.4663,
12548  ellipseName: "Clarke 1880 mod."
12549};
12550exports.clrk58 = {
12551  a: 6378293.645208759,
12552  rf: 294.2606763692654,
12553  ellipseName: "Clarke 1858"
12554};
12555exports.CPM = {
12556  a: 6375738.7,
12557  rf: 334.29,
12558  ellipseName: "Comm. des Poids et Mesures 1799"
12559};
12560exports.delmbr = {
12561  a: 6376428.0,
12562  rf: 311.5,
12563  ellipseName: "Delambre 1810 (Belgium)"
12564};
12565exports.engelis = {
12566  a: 6378136.05,
12567  rf: 298.2566,
12568  ellipseName: "Engelis 1985"
12569};
12570exports.evrst30 = {
12571  a: 6377276.345,
12572  rf: 300.8017,
12573  ellipseName: "Everest 1830"
12574};
12575exports.evrst48 = {
12576  a: 6377304.063,
12577  rf: 300.8017,
12578  ellipseName: "Everest 1948"
12579};
12580exports.evrst56 = {
12581  a: 6377301.243,
12582  rf: 300.8017,
12583  ellipseName: "Everest 1956"
12584};
12585exports.evrst69 = {
12586  a: 6377295.664,
12587  rf: 300.8017,
12588  ellipseName: "Everest 1969"
12589};
12590exports.evrstSS = {
12591  a: 6377298.556,
12592  rf: 300.8017,
12593  ellipseName: "Everest (Sabah & Sarawak)"
12594};
12595exports.fschr60 = {
12596  a: 6378166.0,
12597  rf: 298.3,
12598  ellipseName: "Fischer (Mercury Datum) 1960"
12599};
12600exports.fschr60m = {
12601  a: 6378155.0,
12602  rf: 298.3,
12603  ellipseName: "Fischer 1960"
12604};
12605exports.fschr68 = {
12606  a: 6378150.0,
12607  rf: 298.3,
12608  ellipseName: "Fischer 1968"
12609};
12610exports.helmert = {
12611  a: 6378200.0,
12612  rf: 298.3,
12613  ellipseName: "Helmert 1906"
12614};
12615exports.hough = {
12616  a: 6378270.0,
12617  rf: 297.0,
12618  ellipseName: "Hough"
12619};
12620exports.intl = {
12621  a: 6378388.0,
12622  rf: 297.0,
12623  ellipseName: "International 1909 (Hayford)"
12624};
12625exports.kaula = {
12626  a: 6378163.0,
12627  rf: 298.24,
12628  ellipseName: "Kaula 1961"
12629};
12630exports.lerch = {
12631  a: 6378139.0,
12632  rf: 298.257,
12633  ellipseName: "Lerch 1979"
12634};
12635exports.mprts = {
12636  a: 6397300.0,
12637  rf: 191.0,
12638  ellipseName: "Maupertius 1738"
12639};
12640exports.new_intl = {
12641  a: 6378157.5,
12642  b: 6356772.2,
12643  ellipseName: "New International 1967"
12644};
12645exports.plessis = {
12646  a: 6376523.0,
12647  rf: 6355863.0,
12648  ellipseName: "Plessis 1817 (France)"
12649};
12650exports.krass = {
12651  a: 6378245.0,
12652  rf: 298.3,
12653  ellipseName: "Krassovsky, 1942"
12654};
12655exports.SEasia = {
12656  a: 6378155.0,
12657  b: 6356773.3205,
12658  ellipseName: "Southeast Asia"
12659};
12660exports.walbeck = {
12661  a: 6376896.0,
12662  b: 6355834.8467,
12663  ellipseName: "Walbeck"
12664};
12665exports.WGS60 = {
12666  a: 6378165.0,
12667  rf: 298.3,
12668  ellipseName: "WGS 60"
12669};
12670exports.WGS66 = {
12671  a: 6378145.0,
12672  rf: 298.25,
12673  ellipseName: "WGS 66"
12674};
12675exports.WGS7 = {
12676  a: 6378135.0,
12677  rf: 298.26,
12678  ellipseName: "WGS 72"
12679};
12680exports.WGS84 = {
12681  a: 6378137.0,
12682  rf: 298.257223563,
12683  ellipseName: "WGS 84"
12684};
12685exports.sphere = {
12686  a: 6370997.0,
12687  b: 6370997.0,
12688  ellipseName: "Normal Sphere (r=6370997)"
12689};
12690},{}],90:[function(require,module,exports){
12691exports.greenwich = 0.0; //"0dE",
12692exports.lisbon = -9.131906111111; //"9d07'54.862\"W",
12693exports.paris = 2.337229166667; //"2d20'14.025\"E",
12694exports.bogota = -74.080916666667; //"74d04'51.3\"W",
12695exports.madrid = -3.687938888889; //"3d41'16.58\"W",
12696exports.rome = 12.452333333333; //"12d27'8.4\"E",
12697exports.bern = 7.439583333333; //"7d26'22.5\"E",
12698exports.jakarta = 106.807719444444; //"106d48'27.79\"E",
12699exports.ferro = -17.666666666667; //"17d40'W",
12700exports.brussels = 4.367975; //"4d22'4.71\"E",
12701exports.stockholm = 18.058277777778; //"18d3'29.8\"E",
12702exports.athens = 23.7163375; //"23d42'58.815\"E",
12703exports.oslo = 10.722916666667; //"10d43'22.5\"E"
12704},{}],91:[function(require,module,exports){
12705exports.ft = {to_meter: 0.3048};
12706exports['us-ft'] = {to_meter: 1200 / 3937};
12707
12708},{}],92:[function(require,module,exports){
12709var proj = require('./Proj');
12710var transform = require('./transform');
12711var wgs84 = proj('WGS84');
12712
12713function transformer(from, to, coords) {
12714  var transformedArray;
12715  if (Array.isArray(coords)) {
12716    transformedArray = transform(from, to, coords);
12717    if (coords.length === 3) {
12718      return [transformedArray.x, transformedArray.y, transformedArray.z];
12719    }
12720    else {
12721      return [transformedArray.x, transformedArray.y];
12722    }
12723  }
12724  else {
12725    return transform(from, to, coords);
12726  }
12727}
12728
12729function checkProj(item) {
12730  if (item instanceof proj) {
12731    return item;
12732  }
12733  if (item.oProj) {
12734    return item.oProj;
12735  }
12736  return proj(item);
12737}
12738function proj4(fromProj, toProj, coord) {
12739  fromProj = checkProj(fromProj);
12740  var single = false;
12741  var obj;
12742  if (typeof toProj === 'undefined') {
12743    toProj = fromProj;
12744    fromProj = wgs84;
12745    single = true;
12746  }
12747  else if (typeof toProj.x !== 'undefined' || Array.isArray(toProj)) {
12748    coord = toProj;
12749    toProj = fromProj;
12750    fromProj = wgs84;
12751    single = true;
12752  }
12753  toProj = checkProj(toProj);
12754  if (coord) {
12755    return transformer(fromProj, toProj, coord);
12756  }
12757  else {
12758    obj = {
12759      forward: function(coords) {
12760        return transformer(fromProj, toProj, coords);
12761      },
12762      inverse: function(coords) {
12763        return transformer(toProj, fromProj, coords);
12764      }
12765    };
12766    if (single) {
12767      obj.oProj = toProj;
12768    }
12769    return obj;
12770  }
12771}
12772module.exports = proj4;
12773},{"./Proj":65,"./transform":129}],93:[function(require,module,exports){
12774var HALF_PI = Math.PI/2;
12775var PJD_3PARAM = 1;
12776var PJD_7PARAM = 2;
12777var PJD_GRIDSHIFT = 3;
12778var PJD_WGS84 = 4; // WGS84 or equivalent
12779var PJD_NODATUM = 5; // WGS84 or equivalent
12780var SEC_TO_RAD = 4.84813681109535993589914102357e-6;
12781var AD_C = 1.0026000;
12782var COS_67P5 = 0.38268343236508977;
12783var datum = function(proj) {
12784  if (!(this instanceof datum)) {
12785    return new datum(proj);
12786  }
12787  this.datum_type = PJD_WGS84; //default setting
12788  if (!proj) {
12789    return;
12790  }
12791  if (proj.datumCode && proj.datumCode === 'none') {
12792    this.datum_type = PJD_NODATUM;
12793  }
12794  if (proj.datum_params) {
12795    for (var i = 0; i < proj.datum_params.length; i++) {
12796      proj.datum_params[i] = parseFloat(proj.datum_params[i]);
12797    }
12798    if (proj.datum_params[0] !== 0 || proj.datum_params[1] !== 0 || proj.datum_params[2] !== 0) {
12799      this.datum_type = PJD_3PARAM;
12800    }
12801    if (proj.datum_params.length > 3) {
12802      if (proj.datum_params[3] !== 0 || proj.datum_params[4] !== 0 || proj.datum_params[5] !== 0 || proj.datum_params[6] !== 0) {
12803        this.datum_type = PJD_7PARAM;
12804        proj.datum_params[3] *= SEC_TO_RAD;
12805        proj.datum_params[4] *= SEC_TO_RAD;
12806        proj.datum_params[5] *= SEC_TO_RAD;
12807        proj.datum_params[6] = (proj.datum_params[6] / 1000000.0) + 1.0;
12808      }
12809    }
12810  }
12811  // DGR 2011-03-21 : nadgrids support
12812  this.datum_type = proj.grids ? PJD_GRIDSHIFT : this.datum_type;
12813
12814  this.a = proj.a; //datum object also uses these values
12815  this.b = proj.b;
12816  this.es = proj.es;
12817  this.ep2 = proj.ep2;
12818  this.datum_params = proj.datum_params;
12819  if (this.datum_type === PJD_GRIDSHIFT) {
12820    this.grids = proj.grids;
12821  }
12822};
12823datum.prototype = {
12824
12825
12826  /****************************************************************/
12827  // cs_compare_datums()
12828  //   Returns TRUE if the two datums match, otherwise FALSE.
12829  compare_datums: function(dest) {
12830    if (this.datum_type !== dest.datum_type) {
12831      return false; // false, datums are not equal
12832    }
12833    else if (this.a !== dest.a || Math.abs(this.es - dest.es) > 0.000000000050) {
12834      // the tolerence for es is to ensure that GRS80 and WGS84
12835      // are considered identical
12836      return false;
12837    }
12838    else if (this.datum_type === PJD_3PARAM) {
12839      return (this.datum_params[0] === dest.datum_params[0] && this.datum_params[1] === dest.datum_params[1] && this.datum_params[2] === dest.datum_params[2]);
12840    }
12841    else if (this.datum_type === PJD_7PARAM) {
12842      return (this.datum_params[0] === dest.datum_params[0] && this.datum_params[1] === dest.datum_params[1] && this.datum_params[2] === dest.datum_params[2] && this.datum_params[3] === dest.datum_params[3] && this.datum_params[4] === dest.datum_params[4] && this.datum_params[5] === dest.datum_params[5] && this.datum_params[6] === dest.datum_params[6]);
12843    }
12844    else if (this.datum_type === PJD_GRIDSHIFT || dest.datum_type === PJD_GRIDSHIFT) {
12845      //alert("ERROR: Grid shift transformations are not implemented.");
12846      //return false
12847      //DGR 2012-07-29 lazy ...
12848      return this.nadgrids === dest.nadgrids;
12849    }
12850    else {
12851      return true; // datums are equal
12852    }
12853  }, // cs_compare_datums()
12854
12855  /*
12856   * The function Convert_Geodetic_To_Geocentric converts geodetic coordinates
12857   * (latitude, longitude, and height) to geocentric coordinates (X, Y, Z),
12858   * according to the current ellipsoid parameters.
12859   *
12860   *    Latitude  : Geodetic latitude in radians                     (input)
12861   *    Longitude : Geodetic longitude in radians                    (input)
12862   *    Height    : Geodetic height, in meters                       (input)
12863   *    X         : Calculated Geocentric X coordinate, in meters    (output)
12864   *    Y         : Calculated Geocentric Y coordinate, in meters    (output)
12865   *    Z         : Calculated Geocentric Z coordinate, in meters    (output)
12866   *
12867   */
12868  geodetic_to_geocentric: function(p) {
12869    var Longitude = p.x;
12870    var Latitude = p.y;
12871    var Height = p.z ? p.z : 0; //Z value not always supplied
12872    var X; // output
12873    var Y;
12874    var Z;
12875
12876    var Error_Code = 0; //  GEOCENT_NO_ERROR;
12877    var Rn; /*  Earth radius at location  */
12878    var Sin_Lat; /*  Math.sin(Latitude)  */
12879    var Sin2_Lat; /*  Square of Math.sin(Latitude)  */
12880    var Cos_Lat; /*  Math.cos(Latitude)  */
12881
12882    /*
12883     ** Don't blow up if Latitude is just a little out of the value
12884     ** range as it may just be a rounding issue.  Also removed longitude
12885     ** test, it should be wrapped by Math.cos() and Math.sin().  NFW for PROJ.4, Sep/2001.
12886     */
12887    if (Latitude < -HALF_PI && Latitude > -1.001 * HALF_PI) {
12888      Latitude = -HALF_PI;
12889    }
12890    else if (Latitude > HALF_PI && Latitude < 1.001 * HALF_PI) {
12891      Latitude = HALF_PI;
12892    }
12893    else if ((Latitude < -HALF_PI) || (Latitude > HALF_PI)) {
12894      /* Latitude out of range */
12895      //..reportError('geocent:lat out of range:' + Latitude);
12896      return null;
12897    }
12898
12899    if (Longitude > Math.PI) {
12900      Longitude -= (2 * Math.PI);
12901    }
12902    Sin_Lat = Math.sin(Latitude);
12903    Cos_Lat = Math.cos(Latitude);
12904    Sin2_Lat = Sin_Lat * Sin_Lat;
12905    Rn = this.a / (Math.sqrt(1.0e0 - this.es * Sin2_Lat));
12906    X = (Rn + Height) * Cos_Lat * Math.cos(Longitude);
12907    Y = (Rn + Height) * Cos_Lat * Math.sin(Longitude);
12908    Z = ((Rn * (1 - this.es)) + Height) * Sin_Lat;
12909
12910    p.x = X;
12911    p.y = Y;
12912    p.z = Z;
12913    return Error_Code;
12914  }, // cs_geodetic_to_geocentric()
12915
12916
12917  geocentric_to_geodetic: function(p) {
12918    /* local defintions and variables */
12919    /* end-criterium of loop, accuracy of sin(Latitude) */
12920    var genau = 1e-12;
12921    var genau2 = (genau * genau);
12922    var maxiter = 30;
12923
12924    var P; /* distance between semi-minor axis and location */
12925    var RR; /* distance between center and location */
12926    var CT; /* sin of geocentric latitude */
12927    var ST; /* cos of geocentric latitude */
12928    var RX;
12929    var RK;
12930    var RN; /* Earth radius at location */
12931    var CPHI0; /* cos of start or old geodetic latitude in iterations */
12932    var SPHI0; /* sin of start or old geodetic latitude in iterations */
12933    var CPHI; /* cos of searched geodetic latitude */
12934    var SPHI; /* sin of searched geodetic latitude */
12935    var SDPHI; /* end-criterium: addition-theorem of sin(Latitude(iter)-Latitude(iter-1)) */
12936    var At_Pole; /* indicates location is in polar region */
12937    var iter; /* # of continous iteration, max. 30 is always enough (s.a.) */
12938
12939    var X = p.x;
12940    var Y = p.y;
12941    var Z = p.z ? p.z : 0.0; //Z value not always supplied
12942    var Longitude;
12943    var Latitude;
12944    var Height;
12945
12946    At_Pole = false;
12947    P = Math.sqrt(X * X + Y * Y);
12948    RR = Math.sqrt(X * X + Y * Y + Z * Z);
12949
12950    /*      special cases for latitude and longitude */
12951    if (P / this.a < genau) {
12952
12953      /*  special case, if P=0. (X=0., Y=0.) */
12954      At_Pole = true;
12955      Longitude = 0.0;
12956
12957      /*  if (X,Y,Z)=(0.,0.,0.) then Height becomes semi-minor axis
12958       *  of ellipsoid (=center of mass), Latitude becomes PI/2 */
12959      if (RR / this.a < genau) {
12960        Latitude = HALF_PI;
12961        Height = -this.b;
12962        return;
12963      }
12964    }
12965    else {
12966      /*  ellipsoidal (geodetic) longitude
12967       *  interval: -PI < Longitude <= +PI */
12968      Longitude = Math.atan2(Y, X);
12969    }
12970
12971    /* --------------------------------------------------------------
12972     * Following iterative algorithm was developped by
12973     * "Institut for Erdmessung", University of Hannover, July 1988.
12974     * Internet: www.ife.uni-hannover.de
12975     * Iterative computation of CPHI,SPHI and Height.
12976     * Iteration of CPHI and SPHI to 10**-12 radian resp.
12977     * 2*10**-7 arcsec.
12978     * --------------------------------------------------------------
12979     */
12980    CT = Z / RR;
12981    ST = P / RR;
12982    RX = 1.0 / Math.sqrt(1.0 - this.es * (2.0 - this.es) * ST * ST);
12983    CPHI0 = ST * (1.0 - this.es) * RX;
12984    SPHI0 = CT * RX;
12985    iter = 0;
12986
12987    /* loop to find sin(Latitude) resp. Latitude
12988     * until |sin(Latitude(iter)-Latitude(iter-1))| < genau */
12989    do {
12990      iter++;
12991      RN = this.a / Math.sqrt(1.0 - this.es * SPHI0 * SPHI0);
12992
12993      /*  ellipsoidal (geodetic) height */
12994      Height = P * CPHI0 + Z * SPHI0 - RN * (1.0 - this.es * SPHI0 * SPHI0);
12995
12996      RK = this.es * RN / (RN + Height);
12997      RX = 1.0 / Math.sqrt(1.0 - RK * (2.0 - RK) * ST * ST);
12998      CPHI = ST * (1.0 - RK) * RX;
12999      SPHI = CT * RX;
13000      SDPHI = SPHI * CPHI0 - CPHI * SPHI0;
13001      CPHI0 = CPHI;
13002      SPHI0 = SPHI;
13003    }
13004    while (SDPHI * SDPHI > genau2 && iter < maxiter);
13005
13006    /*      ellipsoidal (geodetic) latitude */
13007    Latitude = Math.atan(SPHI / Math.abs(CPHI));
13008
13009    p.x = Longitude;
13010    p.y = Latitude;
13011    p.z = Height;
13012    return p;
13013  }, // cs_geocentric_to_geodetic()
13014
13015  /** Convert_Geocentric_To_Geodetic
13016   * The method used here is derived from 'An Improved Algorithm for
13017   * Geocentric to Geodetic Coordinate Conversion', by Ralph Toms, Feb 1996
13018   */
13019  geocentric_to_geodetic_noniter: function(p) {
13020    var X = p.x;
13021    var Y = p.y;
13022    var Z = p.z ? p.z : 0; //Z value not always supplied
13023    var Longitude;
13024    var Latitude;
13025    var Height;
13026
13027    var W; /* distance from Z axis */
13028    var W2; /* square of distance from Z axis */
13029    var T0; /* initial estimate of vertical component */
13030    var T1; /* corrected estimate of vertical component */
13031    var S0; /* initial estimate of horizontal component */
13032    var S1; /* corrected estimate of horizontal component */
13033    var Sin_B0; /* Math.sin(B0), B0 is estimate of Bowring aux variable */
13034    var Sin3_B0; /* cube of Math.sin(B0) */
13035    var Cos_B0;
13035 /* Math.cos(B0) */
13036    var Sin_p1; /* Math.sin(phi1), phi1 is estimated latitude */
13037    var Cos_p1; /* Math.cos(phi1) */
13038    var Rn; /* Earth radius at location */
13039    var Sum; /* numerator of Math.cos(phi1) */
13040    var At_Pole; /* indicates location is in polar region */
13041
13042    X = parseFloat(X); // cast from string to float
13043    Y = parseFloat(Y);
13044    Z = parseFloat(Z);
13045
13046    At_Pole = false;
13047    if (X !== 0.0) {
13048      Longitude = Math.atan2(Y, X);
13049    }
13050    else {
13051      if (Y > 0) {
13052        Longitude = HALF_PI;
13053      }
13054      else if (Y < 0) {
13055        Longitude = -HALF_PI;
13056      }
13057      else {
13058        At_Pole = true;
13059        Longitude = 0.0;
13060        if (Z > 0.0) { /* north pole */
13061          Latitude = HALF_PI;
13062        }
13063        else if (Z < 0.0) { /* south pole */
13064          Latitude = -HALF_PI;
13065        }
13066        else { /* center of earth */
13067          Latitude = HALF_PI;
13068          Height = -this.b;
13069          return;
13070        }
13071      }
13072    }
13073    W2 = X * X + Y * Y;
13074    W = Math.sqrt(W2);
13075    T0 = Z * AD_C;
13076    S0 = Math.sqrt(T0 * T0 + W2);
13077    Sin_B0 = T0 / S0;
13078    Cos_B0 = W / S0;
13079    Sin3_B0 = Sin_B0 * Sin_B0 * Sin_B0;
13080    T1 = Z + this.b * this.ep2 * Sin3_B0;
13081    Sum = W - this.a * this.es * Cos_B0 * Cos_B0 * Cos_B0;
13082    S1 = Math.sqrt(T1 * T1 + Sum * Sum);
13083    Sin_p1 = T1 / S1;
13084    Cos_p1 = Sum / S1;
13085    Rn = this.a / Math.sqrt(1.0 - this.es * Sin_p1 * Sin_p1);
13086    if (Cos_p1 >= COS_67P5) {
13087      Height = W / Cos_p1 - Rn;
13088    }
13089    else if (Cos_p1 <= -COS_67P5) {
13090      Height = W / -Cos_p1 - Rn;
13091    }
13092    else {
13093      Height = Z / Sin_p1 + Rn * (this.es - 1.0);
13094    }
13095    if (At_Pole === false) {
13096      Latitude = Math.atan(Sin_p1 / Cos_p1);
13097    }
13098
13099    p.x = Longitude;
13100    p.y = Latitude;
13101    p.z = Height;
13102    return p;
13103  }, // geocentric_to_geodetic_noniter()
13104
13105  /****************************************************************/
13106  // pj_geocentic_to_wgs84( p )
13107  //  p = point to transform in geocentric coordinates (x,y,z)
13108  geocentric_to_wgs84: function(p) {
13109
13110    if (this.datum_type === PJD_3PARAM) {
13111      // if( x[io] === HUGE_VAL )
13112      //    continue;
13113      p.x += this.datum_params[0];
13114      p.y += this.datum_params[1];
13115      p.z += this.datum_params[2];
13116
13117    }
13118    else if (this.datum_type === PJD_7PARAM) {
13119      var Dx_BF = this.datum_params[0];
13120      var Dy_BF = this.datum_params[1];
13121      var Dz_BF = this.datum_params[2];
13122      var Rx_BF = this.datum_params[3];
13123      var Ry_BF = this.datum_params[4];
13124      var Rz_BF = this.datum_params[5];
13125      var M_BF = this.datum_params[6];
13126      // if( x[io] === HUGE_VAL )
13127      //    continue;
13128      var x_out = M_BF * (p.x - Rz_BF * p.y + Ry_BF * p.z) + Dx_BF;
13129      var y_out = M_BF * (Rz_BF * p.x + p.y - Rx_BF * p.z) + Dy_BF;
13130      var z_out = M_BF * (-Ry_BF * p.x + Rx_BF * p.y + p.z) + Dz_BF;
13131      p.x = x_out;
13132      p.y = y_out;
13133      p.z = z_out;
13134    }
13135  }, // cs_geocentric_to_wgs84
13136
13137  /****************************************************************/
13138  // pj_geocentic_from_wgs84()
13139  //  coordinate system definition,
13140  //  point to transform in geocentric coordinates (x,y,z)
13141  geocentric_from_wgs84: function(p) {
13142
13143    if (this.datum_type === PJD_3PARAM) {
13144      //if( x[io] === HUGE_VAL )
13145      //    continue;
13146      p.x -= this.datum_params[0];
13147      p.y -= this.datum_params[1];
13148      p.z -= this.datum_params[2];
13149
13150    }
13151    else if (this.datum_type === PJD_7PARAM) {
13152      var Dx_BF = this.datum_params[0];
13153      var Dy_BF = this.datum_params[1];
13154      var Dz_BF = this.datum_params[2];
13155      var Rx_BF = this.datum_params[3];
13156      var Ry_BF = this.datum_params[4];
13157      var Rz_BF = this.datum_params[5];
13158      var M_BF = this.datum_params[6];
13159      var x_tmp = (p.x - Dx_BF) / M_BF;
13160      var y_tmp = (p.y - Dy_BF) / M_BF;
13161      var z_tmp = (p.z - Dz_BF) / M_BF;
13162      //if( x[io] === HUGE_VAL )
13163      //    continue;
13164
13165      p.x = x_tmp + Rz_BF * y_tmp - Ry_BF * z_tmp;
13166      p.y = -Rz_BF * x_tmp + y_tmp + Rx_BF * z_tmp;
13167      p.z = Ry_BF * x_tmp - Rx_BF * y_tmp + z_tmp;
13168    } //cs_geocentric_from_wgs84()
13169  }
13170};
13171
13172/** point object, nothing fancy, just allows values to be
13173    passed back and forth by reference rather than by value.
13174    Other point classes may be used as long as they have
13175    x and y properties, which will get modified in the transform method.
13176*/
13177module.exports = datum;
13178
13179},{}],94:[function(require,module,exports){
13180var PJD_3PARAM = 1;
13181var PJD_7PARAM = 2;
13182var PJD_GRIDSHIFT = 3;
13183var PJD_NODATUM = 5; // WGS84 or equivalent
13184var SRS_WGS84_SEMIMAJOR = 6378137; // only used in grid shift transforms
13185var SRS_WGS84_ESQUARED = 0.006694379990141316; //DGR: 2012-07-29
13186module.exports = function(source, dest, point) {
13187  var wp, i, l;
13188
13189  function checkParams(fallback) {
13190    return (fallback === PJD_3PARAM || fallback === PJD_7PARAM);
13191  }
13192  // Short cut if the datums are identical.
13193  if (source.compare_datums(dest)) {
13194    return point; // in this case, zero is sucess,
13195    // whereas cs_compare_datums returns 1 to indicate TRUE
13196    // confusing, should fix this
13197  }
13198
13199  // Explicitly skip datum transform by setting 'datum=none' as parameter for either source or dest
13200  if (source.datum_type === PJD_NODATUM || dest.datum_type === PJD_NODATUM) {
13201    return point;
13202  }
13203
13204  //DGR: 2012-07-29 : add nadgrids support (begin)
13205  var src_a = source.a;
13206  var src_es = source.es;
13207
13208  var dst_a = dest.a;
13209  var dst_es = dest.es;
13210
13211  var fallback = source.datum_type;
13212  // If this datum requires grid shifts, then apply it to geodetic coordinates.
13213  if (fallback === PJD_GRIDSHIFT) {
13214    if (this.apply_gridshift(source, 0, point) === 0) {
13215      source.a = SRS_WGS84_SEMIMAJOR;
13216      source.es = SRS_WGS84_ESQUARED;
13217    }
13218    else {
13219      // try 3 or 7 params transformation or nothing ?
13220      if (!source.datum_params) {
13221        source.a = src_a;
13222        source.es = source.es;
13223        return point;
13224      }
13225      wp = 1;
13226      for (i = 0, l = source.datum_params.length; i < l; i++) {
13227        wp *= source.datum_params[i];
13228      }
13229      if (wp === 0) {
13230        source.a = src_a;
13231        source.es = source.es;
13232        return point;
13233      }
13234      if (source.datum_params.length > 3) {
13235        fallback = PJD_7PARAM;
13236      }
13237      else {
13238        fallback = PJD_3PARAM;
13239      }
13240    }
13241  }
13242  if (dest.datum_type === PJD_GRIDSHIFT) {
13243    dest.a = SRS_WGS84_SEMIMAJOR;
13244    dest.es = SRS_WGS84_ESQUARED;
13245  }
13246  // Do we need to go through geocentric coordinates?
13247  if (source.es !== dest.es || source.a !== dest.a || checkParams(fallback) || checkParams(dest.datum_type)) {
13248    //DGR: 2012-07-29 : add nadgrids support (end)
13249    // Convert to geocentric coordinates.
13250    source.geodetic_to_geocentric(point);
13251    // CHECK_RETURN;
13252    // Convert between datums
13253    if (checkParams(source.datum_type)) {
13254      source.geocentric_to_wgs84(point);
13255      // CHECK_RETURN;
13256    }
13257    if (checkParams(dest.datum_type)) {
13258      dest.geocentric_from_wgs84(point);
13259      // CHECK_RETURN;
13260    }
13261    // Convert back to geodetic coordinates
13262    dest.geocentric_to_geodetic(point);
13263    // CHECK_RETURN;
13264  }
13265  // Apply grid shift to destination if required
13266  if (dest.datum_type === PJD_GRIDSHIFT) {
13267    this.apply_gridshift(dest, 1, point);
13268    // CHECK_RETURN;
13269  }
13270
13271  source.a = src_a;
13272  source.es = src_es;
13273  dest.a = dst_a;
13274  dest.es = dst_es;
13275
13276  return point;
13277};
13278
13279
13280},{}],95:[function(require,module,exports){
13281var globals = require('./global');
13282var parseProj = require('./projString');
13283var wkt = require('./wkt');
13284
13285function defs(name) {
13286  /*global console*/
13287  var that = this;
13288  if (arguments.length === 2) {
13289    var def = arguments[1];
13290    if (typeof def === 'string') {
13291      if (def.charAt(0) === '+') {
13292        defs[name] = parseProj(arguments[1]);
13293      }
13294      else {
13295        defs[name] = wkt(arguments[1]);
13296      }
13297    } else {
13298      defs[name] = def;
13299    }
13300  }
13301  else if (arguments.length === 1) {
13302    if (Array.isArray(name)) {
13303      return name.map(function(v) {
13304        if (Array.isArray(v)) {
13305          defs.apply(that, v);
13306        }
13307        else {
13308          defs(v);
13309        }
13310      });
13311    }
13312    else if (typeof name === 'string') {
13313      if (name in defs) {
13314        return defs[name];
13315      }
13316    }
13317    else if ('EPSG' in name) {
13318      defs['EPSG:' + name.EPSG] = name;
13319    }
13320    else if ('ESRI' in name) {
13321      defs['ESRI:' + name.ESRI] = name;
13322    }
13323    else if ('IAU2000' in name) {
13324      defs['IAU2000:' + name.IAU2000] = name;
13325    }
13326    else {
13327      console.log(name);
13328    }
13329    return;
13330  }
13331
13332
13333}
13334globals(defs);
13335module.exports = defs;
13336
13337},{"./global":98,"./projString":102,"./wkt":130}],96:[function(require,module,exports){
13338var Datum = require('./constants/Datum');
13339var Ellipsoid = require('./constants/Ellipsoid');
13340var extend = require('./extend');
13341var datum = require('./datum');
13342var EPSLN = 1.0e-10;
13343// ellipoid pj_set_ell.c
13344var SIXTH = 0.1666666666666666667;
13345/* 1/6 */
13346var RA4 = 0.04722222222222222222;
13347/* 17/360 */
13348var RA6 = 0.02215608465608465608;
13349module.exports = function(json) {
13350  // DGR 2011-03-20 : nagrids -> nadgrids
13351  if (json.datumCode && json.datumCode !== 'none') {
13352    var datumDef = Datum[json.datumCode];
13353    if (datumDef) {
13354      json.datum_params = datumDef.towgs84 ? datumDef.towgs84.split(',') : null;
13355      json.ellps = datumDef.ellipse;
13356      json.datumName = datumDef.datumName ? datumDef.datumName : json.datumCode;
13357    }
13358  }
13359  if (!json.a) { // do we have an ellipsoid?
13360    var ellipse = Ellipsoid[json.ellps] ? Ellipsoid[json.ellps] : Ellipsoid.WGS84;
13361    extend(json, ellipse);
13362  }
13363  if (json.rf && !json.b) {
13364    json.b = (1.0 - 1.0 / json.rf) * json.a;
13365  }
13366  if (json.rf === 0 || Math.abs(json.a - json.b) < EPSLN) {
13367    json.sphere = true;
13368    json.b = json.a;
13369  }
13370  json.a2 = json.a * json.a; // used in geocentric
13371  json.b2 = json.b * json.b; // used in geocentric
13372  json.es = (json.a2 - json.b2) / json.a2; // e ^ 2
13373  json.e = Math.sqrt(json.es);
13373 // eccentricity
13374  if (json.R_A) {
13375    json.a *= 1 - json.es * (SIXTH + json.es * (RA4 + json.es * RA6));
13376    json.a2 = json.a * json.a;
13377    json.b2 = json.b * json.b;
13378    json.es = 0;
13379  }
13380  json.ep2 = (json.a2 - json.b2) / json.b2; // used in geocentric
13381  if (!json.k0) {
13382    json.k0 = 1.0; //default value
13383  }
13384  //DGR 2010-11-12: axis
13385  if (!json.axis) {
13386    json.axis = "enu";
13387  }
13388
13389  if (!json.datum) {
13390    json.datum = datum(json);
13391  }
13392  return json;
13393};
13394
13395},{"./constants/Datum":88,"./constants/Ellipsoid":89,"./datum":93,"./extend":97}],97:[function(require,module,exports){
13396module.exports = function(destination, source) {
13397  destination = destination || {};
13398  var value, property;
13399  if (!source) {
13400    return destination;
13401  }
13402  for (property in source) {
13403    value = source[property];
13404    if (value !== undefined) {
13405      destination[property] = value;
13406    }
13407  }
13408  return destination;
13409};
13410
13411},{}],98:[function(require,module,exports){
13412module.exports = function(defs) {
13413  defs('EPSG:4326', "+title=WGS 84 (long/lat) +proj=longlat +ellps=WGS84 +datum=WGS84 +units=degrees");
13414  defs('EPSG:4269', "+title=NAD83 (long/lat) +proj=longlat +a=6378137.0 +b=6356752.31414036 +ellps=GRS80 +datum=NAD83 +units=degrees");
13415  defs('EPSG:3857', "+title=WGS 84 / Pseudo-Mercator +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +no_defs");
13416
13417  defs.WGS84 = defs['EPSG:4326'];
13418  defs['EPSG:3785'] = defs['EPSG:3857']; // maintain backward compat, official code is 3857
13419  defs.GOOGLE = defs['EPSG:3857'];
13420  defs['EPSG:900913'] = defs['EPSG:3857'];
13421  defs['EPSG:102113'] = defs['EPSG:3857'];
13422};
13423
13424},{}],99:[function(require,module,exports){
13425var projs = [
13426  require('./projections/tmerc'),
13427  require('./projections/utm'),
13428  require('./projections/sterea'),
13429  require('./projections/stere'),
13430  require('./projections/somerc'),
13431  require('./projections/omerc'),
13432  require('./projections/lcc'),
13433  require('./projections/krovak'),
13434  require('./projections/cass'),
13435  require('./projections/laea'),
13436  require('./projections/aea'),
13437  require('./projections/gnom'),
13438  require('./projections/cea'),
13439  require('./projections/eqc'),
13440  require('./projections/poly'),
13441  require('./projections/nzmg'),
13442  require('./projections/mill'),
13443  require('./projections/sinu'),
13444  require('./projections/moll'),
13445  require('./projections/eqdc'),
13446  require('./projections/vandg'),
13447  require('./projections/aeqd')
13448];
13449module.exports = function(proj4){
13450  projs.forEach(function(proj){
13451    proj4.Proj.projections.add(proj);
13452  });
13453};
13454},{"./projections/aea":104,"./projections/aeqd":105,"./projections/cass":106,"./projections/cea":107,"./projections/eqc":108,"./projections/eqdc":109,"./projections/gnom":111,"./projections/krovak":112,"./projections/laea":113,"./projections/lcc":114,"./projections/mill":117,"./projections/moll":118,"./projections/nzmg":119,"./projections/omerc":120,"./projections/poly":121,"./projections/sinu":122,"./projections/somerc":123,"./projections/stere":124,"./projections/sterea":125,"./projections/tmerc":126,"./projections/utm":127,"./projections/vandg":128}],100:[function(require,module,exports){
13455var proj4 = require('./core');
13456proj4.defaultDatum = 'WGS84'; //default datum
13457proj4.Proj = require('./Proj');
13458proj4.WGS84 = new proj4.Proj('WGS84');
13459proj4.Point = require('./Point');
13460proj4.toPoint = require("./common/toPoint");
13461proj4.defs = require('./defs');
13462proj4.transform = require('./transform');
13463proj4.mgrs = require('mgrs');
13464proj4.version = require('../package.json').version;
13465require('./includedProjections')(proj4);
13466module.exports = proj4;
13467},{"../package.json":132,"./Point":64,"./Proj":65,"./common/toPoint":86,"./core":92,"./defs":95,"./includedProjections":99,"./transform":129,"mgrs":131}],101:[function(require,module,exports){
13468var defs = require('./defs');
13469var wkt = require('./wkt');
13470var projStr = require('./projString');
13471function testObj(code){
13472  return typeof code === 'string';
13473}
13474function testDef(code){
13475  return code in defs;
13476}
13477function testWKT(code){
13478  var codeWords = ['GEOGCS','GEOCCS','PROJCS','LOCAL_CS'];
13479  return codeWords.reduce(function(a,b){
13480    return a+1+code.indexOf(b);
13481  },0);
13482}
13483function testProj(code){
13484  return code[0] === '+';
13485}
13486function parse(code){
13487  if (testObj(code)) {
13488    //check to see if this is a WKT string
13489    if (testDef(code)) {
13490      return defs[code];
13491    }
13492    else if (testWKT(code)) {
13493      return wkt(code);
13494    }
13495    else if (testProj(code)) {
13496      return projStr(code);
13497    }
13498  }else{
13499    return code;
13500  }
13501}
13502
13503module.exports = parse;
13504},{"./defs":95,"./projString":102,"./wkt":130}],102:[function(require,module,exports){
13505var D2R = 0.01745329251994329577;
13506var PrimeMeridian = require('./constants/PrimeMeridian');
13507var units = require('./constants/units');
13508
13509module.exports = function(defData) {
13510  var self = {};
13511  var paramObj = {};
13512  defData.split("+").map(function(v) {
13513    return v.trim();
13514  }).filter(function(a) {
13515    return a;
13516  }
13516).forEach(function(a) {
13517    var split = a.split("=");
13518    split.push(true);
13519    paramObj[split[0].toLowerCase()] = split[1];
13520  });
13521  var paramName, paramVal, paramOutname;
13522  var params = {
13523    proj: 'projName',
13524    datum: 'datumCode',
13525    rf: function(v) {
13526      self.rf = parseFloat(v);
13527    },
13528    lat_0: function(v) {
13529      self.lat0 = v * D2R;
13530    },
13531    lat_1: function(v) {
13532      self.lat1 = v * D2R;
13533    },
13534    lat_2: function(v) {
13535      self.lat2 = v * D2R;
13536    },
13537    lat_ts: function(v) {
13538      self.lat_ts = v * D2R;
13539    },
13540    lon_0: function(v) {
13541      self.long0 = v * D2R;
13542    },
13543    lon_1: function(v) {
13544      self.long1 = v * D2R;
13545    },
13546    lon_2: function(v) {
13547      self.long2 = v * D2R;
13548    },
13549    alpha: function(v) {
13550      self.alpha = parseFloat(v) * D2R;
13551    },
13552    lonc: function(v) {
13553      self.longc = v * D2R;
13554    },
13555    x_0: function(v) {
13556      self.x0 = parseFloat(v);
13557    },
13558    y_0: function(v) {
13559      self.y0 = parseFloat(v);
13560    },
13561    k_0: function(v) {
13562      self.k0 = parseFloat(v);
13563    },
13564    k: function(v) {
13565      self.k0 = parseFloat(v);
13566    },
13567    a: function(v) {
13568      self.a = parseFloat(v);
13569    },
13570    b: function(v) {
13571      self.b = parseFloat(v);
13572    },
13573    r_a: function() {
13574      self.R_A = true;
13575    },
13576    zone: function(v) {
13577      self.zone = parseInt(v, 10);
13578    },
13579    south: function() {
13580      self.utmSouth = true;
13581    },
13582    towgs84: function(v) {
13583      self.datum_params = v.split(",").map(function(a) {
13584        return parseFloat(a);
13585      });
13586    },
13587    to_meter: function(v) {
13588      self.to_meter = parseFloat(v);
13589    },
13590    units: function(v) {
13591      self.units = v;
13592      if (units[v]) {
13593        self.to_meter = units[v].to_meter;
13594      }
13595    },
13596    from_greenwich: function(v) {
13597      self.from_greenwich = v * D2R;
13598    },
13599    pm: function(v) {
13600      self.from_greenwich = (PrimeMeridian[v] ? PrimeMeridian[v] : parseFloat(v)) * D2R;
13601    },
13602    nadgrids: function(v) {
13603      if (v === '@null') {
13604        self.datumCode = 'none';
13605      }
13606      else {
13607        self.nadgrids = v;
13608      }
13609    },
13610    axis: function(v) {
13611      var legalAxis = "ewnsud";
13612      if (v.length === 3 && legalAxis.indexOf(v.substr(0, 1)) !== -1 && legalAxis.indexOf(v.substr(1, 1)) !== -1 && legalAxis.indexOf(v.substr(2, 1)) !== -1) {
13613        self.axis = v;
13614      }
13615    }
13616  };
13617  for (paramName in paramObj) {
13618    paramVal = paramObj[paramName];
13619    if (paramName in params) {
13620      paramOutname = params[paramName];
13621      if (typeof paramOutname === 'function') {
13622        paramOutname(paramVal);
13623      }
13624      else {
13625        self[paramOutname] = paramVal;
13626      }
13627    }
13628    else {
13629      self[paramName] = paramVal;
13630    }
13631  }
13632  if(typeof self.datumCode === 'string' && self.datumCode !== "WGS84"){
13633    self.datumCode = self.datumCode.toLowerCase();
13634  }
13635  return self;
13636};
13637
13638},{"./constants/PrimeMeridian":90,"./constants/units":91}],103:[function(require,module,exports){
13639var projs = [
13640  require('./projections/merc'),
13641  require('./projections/longlat')
13642];
13643var names = {};
13644var projStore = [];
13645
13646function add(proj, i) {
13647  var len = projStore.length;
13648  if (!proj.names) {
13649    console.log(i);
13650    return true;
13651  }
13652  projStore[len] = proj;
13653  proj.names.forEach(function(n) {
13654    names[n.toLowerCase()] = len;
13655  });
13656  return this;
13657}
13658
13659exports.add = add;
13660
13661exports.get = function(name) {
13662  if (!name) {
13663    return false;
13664  }
13665  var n = name.toLowerCase();
13666  if (typeof names[n] !== 'undefined' && projStore[names[n]]) {
13667    return projStore[names[n]];
13668  }
13669};
13670exports.start = function() {
13671  projs.forEach(add);
13672};
13673
13674},{"./projections/longlat":115,"./projections/merc":116}],104:[function(require,module,exports){
13675var EPSLN = 1.0e-10;
13676var msfnz = require('../common/msfnz');
13677var qsfnz = require('../common/qsfnz');
13678var adjust_lon = require('../common/adjust_lon');
13679var asinz = require('../common/asinz');
13680exports.init = function() {
13681
13682  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
13683    return;
13684  }
13685  this.temp = this.b / this.a;
13686  this.es = 1 - Math.pow(this.temp, 2);
13687  this.e3 = Math.sqrt(this.es);
13688
13689  this.sin_po = Math.sin(this.lat1);
13690  this.cos_po = Math.cos(this.lat1);
13691  this.t1 = this.sin_po;
13692  this.con = this.sin_po;
13693  this.ms1 = msfnz(this.e3, this.sin_po, this.cos_po);
13694  this.qs1 = qsfnz(this.e3, this.sin_po, this.cos_po);
13695
13696  this.sin_po = Math.sin(this.lat2);
13697  this.cos_po = Math.cos(this.lat2);
13698  this.t2 = this.sin_po;
13699  this.ms2 = msfnz(this.e3, this.sin_po, this.cos_po);
13700  this.qs2 = qsfnz(this.e3, this.sin_po, this.cos_po);
13701
13702  this.sin_po = Math.sin(this.lat0);
13703  this.cos_po = Math.cos(this.lat0);
13704  this.t3 = this.sin_po;
13705  this.qs0 = qsfnz(this.e3, this.sin_po, this.cos_po);
13706
13707  if (Math.abs(this.lat1 - this.lat2) > EPSLN) {
13708    this.ns0 = (this.ms1 * this.ms1 - this.ms2 * this.ms2) / (this.qs2 - this.qs1);
13709  }
13710  else {
13711    this.ns0 = this.con;
13712  }
13713  this.c = this.ms1 * this.ms1 + this.ns0 * this.qs1;
13714  this.rh = this.a * Math.sqrt(this.c - this.ns0 * this.qs0) / this.ns0;
13715};
13716
13717/* Albers Conical Equal Area forward equations--mapping lat,long to x,y
13718  -------------------------------------------------------------------*/
13719exports.forward = function(p) {
13720
13721  var lon = p.x;
13722  var lat = p.y;
13723
13724  this.sin_phi = Math.sin(lat);
13725  this.cos_phi = Math.cos(lat);
13726
13727  var qs = qsfnz(this.e3, this.sin_phi, this.cos_phi);
13728  var rh1 = this.a * Math.sqrt(this.c - this.ns0 * qs) / this.ns0;
13729  var theta = this.ns0 * adjust_lon(lon - this.long0);
13730  var x = rh1 * Math.sin(theta) + this.x0;
13731  var y = this.rh - rh1 * Math.cos(theta) + this.y0;
13732
13733  p.x = x;
13734  p.y = y;
13735  return p;
13736};
13737
13738
13739exports.inverse = function(p) {
13740  var rh1, qs, con, theta, lon, lat;
13741
13742  p.x -= this.x0;
13743  p.y = this.rh - p.y + this.y0;
13744  if (this.ns0 >= 0) {
13745    rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
13746    con = 1;
13747  }
13748  else {
vendor: 27,471 bytes, lines 13749-14651
13749    rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
13750    con = -1;
13751  }
13752  theta = 0;
13753  if (rh1 !== 0) {
13754    theta = Math.atan2(con * p.x, con * p.y);
13755  }
13756  con = rh1 * this.ns0 / this.a;
13757  if (this.sphere) {
13758    lat = Math.asin((this.c - con * con) / (2 * this.ns0));
13759  }
13760  else {
13761    qs = (this.c - con * con) / this.ns0;
13762    lat = this.phi1z(this.e3, qs);
13763  }
13764
13765  lon = adjust_lon(theta / this.ns0 + this.long0);
13766  p.x = lon;
13767  p.y = lat;
13768  return p;
13769};
13770
13771/* Function to compute phi1, the latitude for the inverse of the
13772   Albers Conical Equal-Area projection.
13773-------------------------------------------*/
13774exports.phi1z = function(eccent, qs) {
13775  var sinphi, cosphi, con, com, dphi;
13776  var phi = asinz(0.5 * qs);
13777  if (eccent < EPSLN) {
13778    return phi;
13779  }
13780
13781  var eccnts = eccent * eccent;
13782  for (var i = 1; i <= 25; i++) {
13783    sinphi = Math.sin(phi);
13784    cosphi = Math.cos(phi);
13785    con = eccent * sinphi;
13786    com = 1 - con * con;
13787    dphi = 0.5 * com * com / cosphi * (qs / (1 - eccnts) - sinphi / com + 0.5 / eccent * Math.log((1 - con) / (1 + con)));
13788    phi = phi + dphi;
13789    if (Math.abs(dphi) <= 1e-7) {
13790      return phi;
13791    }
13792  }
13793  return null;
13794};
13795exports.names = ["Albers_Conic_Equal_Area", "Albers", "aea"];
13796
13797},{"../common/adjust_lon":68,"../common/asinz":69,"../common/msfnz":78,"../common/qsfnz":83}],105:[function(require,module,exports){
13798var adjust_lon = require('../common/adjust_lon');
13799var HALF_PI = Math.PI/2;
13800var EPSLN = 1.0e-10;
13801var mlfn = require('../common/mlfn');
13802var e0fn = require('../common/e0fn');
13803var e1fn = require('../common/e1fn');
13804var e2fn = require('../common/e2fn');
13805var e3fn = require('../common/e3fn');
13806var gN = require('../common/gN');
13807var asinz = require('../common/asinz');
13808var imlfn = require('../common/imlfn');
13809exports.init = function() {
13810  this.sin_p12 = Math.sin(this.lat0);
13811  this.cos_p12 = Math.cos(this.lat0);
13812};
13813
13814exports.forward = function(p) {
13815  var lon = p.x;
13816  var lat = p.y;
13817  var sinphi = Math.sin(p.y);
13818  var cosphi = Math.cos(p.y);
13819  var dlon = adjust_lon(lon - this.long0);
13820  var e0, e1, e2, e3, Mlp, Ml, tanphi, Nl1, Nl, psi, Az, G, H, GH, Hs, c, kp, cos_c, s, s2, s3, s4, s5;
13821  if (this.sphere) {
13822    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
13823      //North Pole case
13824      p.x = this.x0 + this.a * (HALF_PI - lat) * Math.sin(dlon);
13825      p.y = this.y0 - this.a * (HALF_PI - lat) * Math.cos(dlon);
13826      return p;
13827    }
13828    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
13829      //South Pole case
13830      p.x = this.x0 + this.a * (HALF_PI + lat) * Math.sin(dlon);
13831      p.y = this.y0 + this.a * (HALF_PI + lat) * Math.cos(dlon);
13832      return p;
13833    }
13834    else {
13835      //default case
13836      cos_c = this.sin_p12 * sinphi + this.cos_p12 * cosphi * Math.cos(dlon);
13837      c = Math.acos(cos_c);
13838      kp = c / Math.sin(c);
13839      p.x = this.x0 + this.a * kp * cosphi * Math.sin(dlon);
13840      p.y = this.y0 + this.a * kp * (this.cos_p12 * sinphi - this.sin_p12 * cosphi * Math.cos(dlon));
13841      return p;
13842    }
13843  }
13844  else {
13845    e0 = e0fn(this.es);
13846    e1 = e1fn(this.es);
13847    e2 = e2fn(this.es);
13848    e3 = e3fn(this.es);
13849    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
13850      //North Pole case
13851      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
13852      Ml = this.a * mlfn(e0, e1, e2, e3, lat);
13853      p.x = this.x0 + (Mlp - Ml) * Math.sin(dlon);
13854      p.y = this.y0 - (Mlp - Ml) * Math.cos(dlon);
13855      return p;
13856    }
13857    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
13858      //South Pole case
13859      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
13860      Ml = this.a * mlfn(e0, e1, e2, e3, lat);
13861      p.x = this.x0 + (Mlp + Ml) * Math.sin(dlon);
13862      p.y = this.y0 + (Mlp + Ml) * Math.cos(dlon);
13863      return p;
13864    }
13865    else {
13866      //Default case
13867      tanphi = sinphi / cosphi;
13868      Nl1 = gN(this.a, this.e, this.sin_p12);
13869      Nl = gN(this.a, this.e, sinphi);
13870      psi = Math.atan((1 - this.es) * tanphi + this.es * Nl1 * this.sin_p12 / (Nl * cosphi));
13871      Az = Math.atan2(Math.sin(dlon), this.cos_p12 * Math.tan(psi) - this.sin_p12 * Math.cos(dlon));
13872      if (Az === 0) {
13873        s = Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi));
13874      }
13875      else if (Math.abs(Math.abs(Az) - Math.PI) <= EPSLN) {
13876        s = -Math.asin(this.cos_p12 * Math.sin(psi) - this.sin_p12 * Math.cos(psi));
13877      }
13878      else {
13879        s = Math.asin(Math.sin(dlon) * Math.cos(psi) / Math.sin(Az));
13880      }
13881      G = this.e * this.sin_p12 / Math.sqrt(1 - this.es);
13882      H = this.e * this.cos_p12 * Math.cos(Az) / Math.sqrt(1 - this.es);
13883      GH = G * H;
13884      Hs = H * H;
13885      s2 = s * s;
13886      s3 = s2 * s;
13887      s4 = s3 * s;
13888      s5 = s4 * s;
13889      c = Nl1 * s * (1 - s2 * Hs * (1 - Hs) / 6 + s3 / 8 * GH * (1 - 2 * Hs) + s4 / 120 * (Hs * (4 - 7 * Hs) - 3 * G * G * (1 - 7 * Hs)) - s5 / 48 * GH);
13890      p.x = this.x0 + c * Math.sin(Az);
13891      p.y = this.y0 + c * Math.cos(Az);
13892      return p;
13893    }
13894  }
13895
13896
13897};
13898
13899exports.inverse = function(p) {
13900  p.x -= this.x0;
13901  p.y -= this.y0;
13902  var rh, z, sinz, cosz, lon, lat, con, e0, e1, e2, e3, Mlp, M, N1, psi, Az, cosAz, tmp, A, B, D, Ee, F;
13903  if (this.sphere) {
13904    rh = Math.sqrt(p.x * p.x + p.y * p.y);
13905    if (rh > (2 * HALF_PI * this.a)) {
13906      return;
13907    }
13908    z = rh / this.a;
13909
13910    sinz = Math.sin(z);
13911    cosz = Math.cos(z);
13912
13913    lon = this.long0;
13914    if (Math.abs(rh) <= EPSLN) {
13915      lat = this.lat0;
13916    }
13917    else {
13918      lat = asinz(cosz * this.sin_p12 + (p.y * sinz * this.cos_p12) / rh);
13919      con = Math.abs(this.lat0) - HALF_PI;
13920      if (Math.abs(con) <= EPSLN) {
13921        if (this.lat0 >= 0) {
13922          lon = adjust_lon(this.long0 + Math.atan2(p.x, - p.y));
13923        }
13924        else {
13925          lon = adjust_lon(this.long0 - Math.atan2(-p.x, p.y));
13926        }
13927      }
13928      else {
13929        /*con = cosz - this.sin_p12 * Math.sin(lat);
13930        if ((Math.abs(con) < EPSLN) && (Math.abs(p.x) < EPSLN)) {
13931          //no-op, just keep the lon value as is
13932        } else {
13933          var temp = Math.atan2((p.x * sinz * this.cos_p12), (con * rh));
13934          lon = adjust_lon(this.long0 + Math.atan2((p.x * sinz * this.cos_p12), (con * rh)));
13935        }*/
13936        lon = adjust_lon(this.long0 + Math.atan2(p.x * sinz, rh * this.cos_p12 * cosz - p.y * this.sin_p12 * sinz));
13937      }
13938    }
13939
13940    p.x = lon;
13941    p.y = lat;
13942    return p;
13943  }
13944  else {
13945    e0 = e0fn(this.es);
13946    e1 = e1fn(this.es);
13947    e2 = e2fn(this.es);
13948    e3 = e3fn(this.es);
13949    if (Math.abs(this.sin_p12 - 1) <= EPSLN) {
13950      //North pole case
13951      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
13952      rh = Math.sqrt(p.x * p.x + p.y * p.y);
13953      M = Mlp - rh;
13954      lat = imlfn(M / this.a, e0, e1, e2, e3);
13955      lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y));
13956      p.x = lon;
13957      p.y = lat;
13958      return p;
13959    }
13960    else if (Math.abs(this.sin_p12 + 1) <= EPSLN) {
13961      //South pole case
13962      Mlp = this.a * mlfn(e0, e1, e2, e3, HALF_PI);
13963      rh = Math.sqrt(p.x * p.x + p.y * p.y);
13964      M = rh - Mlp;
13965
13966      lat = imlfn(M / this.a, e0, e1, e2, e3);
13967      lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y));
13968      p.x = lon;
13969      p.y = lat;
13970      return p;
13971    }
13972    else {
13973      //default case
13974      rh = Math.sqrt(p.x * p.x + p.y * p.y);
13975      Az = Math.atan2(p.x, p.y);
13976      N1 = gN(this.a, this.e, this.sin_p12);
13977      cosAz = Math.cos(Az);
13978      tmp = this.e * this.cos_p12 * cosAz;
13979      A = -tmp * tmp / (1 - this.es);
13980      B = 3 * this.es * (1 - A) * this.sin_p12 * this.cos_p12 * cosAz / (1 - this.es);
13981      D = rh / N1;
13982      Ee = D - A * (1 + A) * Math.pow(D, 3) / 6 - B * (1 + 3 * A) * Math.pow(D, 4) / 24;
13983      F = 1 - A * Ee * Ee / 2 - D * Ee * Ee * Ee / 6;
13984      psi = Math.asin(this.sin_p12 * Math.cos(Ee) + this.cos_p12 * Math.sin(Ee) * cosAz);
13985      lon = adjust_lon(this.long0 + Math.asin(Math.sin(Az) * Math.sin(Ee) / Math.cos(psi)));
13986      lat = Math.atan((1 - this.es * F * this.sin_p12 / Math.sin(psi)) * Math.tan(psi) / (1 - this.es));
13987      p.x = lon;
13988      p.y = lat;
13989      return p;
13990    }
13991  }
13992
13993};
13994exports.names = ["Azimuthal_Equidistant", "aeqd"];
13995
13996},{"../common/adjust_lon":68,"../common/asinz":69,"../common/e0fn":70,"../common/e1fn":71,"../common/e2fn":72,"../common/e3fn":73,"../common/gN":74,"../common/imlfn":75,"../common/mlfn":77}],106:[function(require,module,exports){
13997var mlfn = require('../common/mlfn');
13998var e0fn = require('../common/e0fn');
13999var e1fn = require('../common/e1fn');
14000var e2fn = require('../common/e2fn');
14001var e3fn = require('../common/e3fn');
14002var gN = require('../common/gN');
14003var adjust_lon = require('../common/adjust_lon');
14004var adjust_lat = require('../common/adjust_lat');
14005var imlfn = require('../common/imlfn');
14006var HALF_PI = Math.PI/2;
14007var EPSLN = 1.0e-10;
14008exports.init = function() {
14009  if (!this.sphere) {
14010    this.e0 = e0fn(this.es);
14011    this.e1 = e1fn(this.es);
14012    this.e2 = e2fn(this.es);
14013    this.e3 = e3fn(this.es);
14014    this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
14015  }
14016};
14017
14018
14019
14020/* Cassini forward equations--mapping lat,long to x,y
14021  -----------------------------------------------------------------------*/
14022exports.forward = function(p) {
14023
14024  /* Forward equations
14025      -----------------*/
14026  var x, y;
14027  var lam = p.x;
14028  var phi = p.y;
14029  lam = adjust_lon(lam - this.long0);
14030
14031  if (this.sphere) {
14032    x = this.a * Math.asin(Math.cos(phi) * Math.sin(lam));
14033    y = this.a * (Math.atan2(Math.tan(phi), Math.cos(lam)) - this.lat0);
14034  }
14035  else {
14036    //ellipsoid
14037    var sinphi = Math.sin(phi);
14038    var cosphi = Math.cos(phi);
14039    var nl = gN(this.a, this.e, sinphi);
14040    var tl = Math.tan(phi) * Math.tan(phi);
14041    var al = lam * Math.cos(phi);
14042    var asq = al * al;
14043    var cl = this.es * cosphi * cosphi / (1 - this.es);
14044    var ml = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi);
14045
14046    x = nl * al * (1 - asq * tl * (1 / 6 - (8 - tl + 8 * cl) * asq / 120));
14047    y = ml - this.ml0 + nl * sinphi / cosphi * asq * (0.5 + (5 - tl + 6 * cl) * asq / 24);
14048
14049
14050  }
14051
14052  p.x = x + this.x0;
14053  p.y = y + this.y0;
14054  return p;
14055};
14056
14057/* Inverse equations
14058  -----------------*/
14059exports.inverse = function(p) {
14060  p.x -= this.x0;
14061  p.y -= this.y0;
14062  var x = p.x / this.a;
14063  var y = p.y / this.a;
14064  var phi, lam;
14065
14066  if (this.sphere) {
14067    var dd = y + this.lat0;
14068    phi = Math.asin(Math.sin(dd) * Math.cos(x));
14069    lam = Math.atan2(Math.tan(x), Math.cos(dd));
14070  }
14071  else {
14072    /* ellipsoid */
14073    var ml1 = this.ml0 / this.a + y;
14074    var phi1 = imlfn(ml1, this.e0, this.e1, this.e2, this.e3);
14075    if (Math.abs(Math.abs(phi1) - HALF_PI) <= EPSLN) {
14076      p.x = this.long0;
14077      p.y = HALF_PI;
14078      if (y < 0) {
14079        p.y *= -1;
14080      }
14081      return p;
14082    }
14083    var nl1 = gN(this.a, this.e, Math.sin(phi1));
14084
14085    var rl1 = nl1 * nl1 * nl1 / this.a / this.a * (1 - this.es);
14086    var tl1 = Math.pow(Math.tan(phi1), 2);
14087    var dl = x * this.a / nl1;
14088    var dsq = dl * dl;
14089    phi = phi1 - nl1 * Math.tan(phi1) / rl1 * dl * dl * (0.5 - (1 + 3 * tl1) * dl * dl / 24);
14090    lam = dl * (1 - dsq * (tl1 / 3 + (1 + 3 * tl1) * tl1 * dsq / 15)) / Math.cos(phi1);
14091
14092  }
14093
14094  p.x = adjust_lon(lam + this.long0);
14095  p.y = adjust_lat(phi);
14096  return p;
14097
14098};
14099exports.names = ["Cassini", "Cassini_Soldner", "cass"];
14100},{"../common/adjust_lat":67,"../common/adjust_lon":68,"../common/e0fn":70,"../common/e1fn":71,"../common/e2fn":72,"../common/e3fn":73,"../common/gN":74,"../common/imlfn":75,"../common/mlfn":77}],107:[function(require,module,exports){
14101var adjust_lon = require('../common/adjust_lon');
14102var qsfnz = require('../common/qsfnz');
14103var msfnz = require('../common/msfnz');
14104var iqsfnz = require('../common/iqsfnz');
14105/*
14106  reference:  
14107    "Cartographic Projection Procedures for the UNIX Environment-
14108    A User's Manual" by Gerald I. Evenden,
14109    USGS Open File Report 90-284and Release 4 Interim Reports (2003)
14110*/
14111exports.init = function() {
14112  //no-op
14113  if (!this.sphere) {
14114    this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
14115  }
14116};
14117
14118
14119/* Cylindrical Equal Area forward equations--mapping lat,long to x,y
14120    ------------------------------------------------------------*/
14121exports.forward = function(p) {
14122  var lon = p.x;
14123  var lat = p.y;
14124  var x, y;
14125  /* Forward equations
14126      -----------------*/
14127  var dlon = adjust_lon(lon - this.long0);
14128  if (this.sphere) {
14129    x = this.x0 + this.a * dlon * Math.cos(this.lat_ts);
14130    y = this.y0 + this.a * Math.sin(lat) / Math.cos(this.lat_ts);
14131  }
14132  else {
14133    var qs = qsfnz(this.e, Math.sin(lat));
14134    x = this.x0 + this.a * this.k0 * dlon;
14135    y = this.y0 + this.a * qs * 0.5 / this.k0;
14136  }
14137
14138  p.x = x;
14139  p.y = y;
14140  return p;
14141};
14142
14143/* Cylindrical Equal Area inverse equations--mapping x,y to lat/long
14144    ------------------------------------------------------------*/
14145exports.inverse = function(p) {
14146  p.x -= this.x0;
14147  p.y -= this.y0;
14148  var lon, lat;
14149
14150  if (this.sphere) {
14151    lon = adjust_lon(this.long0 + (p.x / this.a) / Math.cos(this.lat_ts));
14152    lat = Math.asin((p.y / this.a) * Math.cos(this.lat_ts));
14153  }
14154  else {
14155    lat = iqsfnz(this.e, 2 * p.y * this.k0 / this.a);
14156    lon = adjust_lon(this.long0 + p.x / (this.a * this.k0));
14157  }
14158
14159  p.x = lon;
14160  p.y = lat;
14161  return p;
14162};
14163exports.names = ["cea"];
14164
14165},{"../common/adjust_lon":68,"../common/iqsfnz":76,"../common/msfnz":78,"../common/qsfnz":83}],108:[function(require,module,exports){
14166var adjust_lon = require('../common/adjust_lon');
14167var adjust_lat = require('../common/adjust_lat');
14168exports.init = function() {
14169
14170  this.x0 = this.x0 || 0;
14171  this.y0 = this.y0 || 0;
14172  this.lat0 = this.lat0 || 0;
14173  this.long0 = this.long0 || 0;
14174  this.lat_ts = this.lat_ts || 0;
14175  this.title = this.title || "Equidistant Cylindrical (Plate Carre)";
14176
14177  this.rc = Math.cos(this.lat_ts);
14178};
14179
14180
14181// forward equations--mapping lat,long to x,y
14182// -----------------------------------------------------------------
14183exports.forward = function(p) {
14184
14185  var lon = p.x;
14186  var lat = p.y;
14187
14188  var dlon = adjust_lon(lon - this.long0);
14189  var dlat = adjust_lat(lat - this.lat0);
14190  p.x = this.x0 + (this.a * dlon * this.rc);
14191  p.y = this.y0 + (this.a * dlat);
14192  return p;
14193};
14194
14195// inverse equations--mapping x,y to lat/long
14196// -----------------------------------------------------------------
14197exports.inverse = function(p) {
14198
14199  var x = p.x;
14200  var y = p.y;
14201
14202  p.x = adjust_lon(this.long0 + ((x - this.x0) / (this.a * this.rc)));
14203  p.y = adjust_lat(this.lat0 + ((y - this.y0) / (this.a)));
14204  return p;
14205};
14206exports.names = ["Equirectangular", "Equidistant_Cylindrical", "eqc"];
14207
14208},{"../common/adjust_lat":67,"../common/adjust_lon":68}],109:[function(require,module,exports){
14209var e0fn = require('../common/e0fn');
14210var e1fn = require('../common/e1fn');
14211var e2fn = require('../common/e2fn');
14212var e3fn = require('../common/e3fn');
14213var msfnz = require('../common/msfnz');
14214var mlfn = require('../common/mlfn');
14215var adjust_lon = require('../common/adjust_lon');
14216var adjust_lat = require('../common/adjust_lat');
14217var imlfn = require('../common/imlfn');
14218var EPSLN = 1.0e-10;
14219exports.init = function() {
14220
14221  /* Place parameters in static storage for common use
14222      -------------------------------------------------*/
14223  // Standard Parallels cannot be equal and on opposite sides of the equator
14224  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
14225    return;
14226  }
14227  this.lat2 = this.lat2 || this.lat1;
14228  this.temp = this.b / this.a;
14229  this.es = 1 - Math.pow(this.temp, 2);
14230  this.e = Math.sqrt(this.es);
14231  this.e0 = e0fn(this.es);
14232  this.e1 = e1fn(this.es);
14233  this.e2 = e2fn(this.es);
14234  this.e3 = e3fn(this.es);
14235
14236  this.sinphi = Math.sin(this.lat1);
14237  this.cosphi = Math.cos(this.lat1);
14238
14239  this.ms1 = msfnz(this.e, this.sinphi, this.cosphi);
14240  this.ml1 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat1);
14241
14242  if (Math.abs(this.lat1 - this.lat2) < EPSLN) {
14243    this.ns = this.sinphi;
14244  }
14245  else {
14246    this.sinphi = Math.sin(this.lat2);
14247    this.cosphi = Math.cos(this.lat2);
14248    this.ms2 = msfnz(this.e, this.sinphi, this.cosphi);
14249    this.ml2 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat2);
14250    this.ns = (this.ms1 - this.ms2) / (this.ml2 - this.ml1);
14251  }
14252  this.g = this.ml1 + this.ms1 / this.ns;
14253  this.ml0 = mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
14254  this.rh = this.a * (this.g - this.ml0);
14255};
14256
14257
14258/* Equidistant Conic forward equations--mapping lat,long to x,y
14259  -----------------------------------------------------------*/
14260exports.forward = function(p) {
14261  var lon = p.x;
14262  var lat = p.y;
14263  var rh1;
14264
14265  /* Forward equations
14266      -----------------*/
14267  if (this.sphere) {
14268    rh1 = this.a * (this.g - lat);
14269  }
14270  else {
14271    var ml = mlfn(this.e0, this.e1, this.e2, this.e3, lat);
14272    rh1 = this.a * (this.g - ml);
14273  }
14274  var theta = this.ns * adjust_lon(lon - this.long0);
14275  var x = this.x0 + rh1 * Math.sin(theta);
14276  var y = this.y0 + this.rh - rh1 * Math.cos(theta);
14277  p.x = x;
14278  p.y = y;
14279  return p;
14280};
14281
14282/* Inverse equations
14283  -----------------*/
14284exports.inverse = function(p) {
14285  p.x -= this.x0;
14286  p.y = this.rh - p.y + this.y0;
14287  var con, rh1, lat, lon;
14288  if (this.ns >= 0) {
14289    rh1 = Math.sqrt(p.x * p.x + p.y * p.y);
14290    con = 1;
14291  }
14292  else {
14293    rh1 = -Math.sqrt(p.x * p.x + p.y * p.y);
14294    con = -1;
14295  }
14296  var theta = 0;
14297  if (rh1 !== 0) {
14298    theta = Math.atan2(con * p.x, con * p.y);
14299  }
14300
14301  if (this.sphere) {
14302    lon = adjust_lon(this.long0 + theta / this.ns);
14303    lat = adjust_lat(this.g - rh1 / this.a);
14304    p.x = lon;
14305    p.y = lat;
14306    return p;
14307  }
14308  else {
14309    var ml = this.g - rh1 / this.a;
14310    lat = imlfn(ml, this.e0, this.e1, this.e2, this.e3);
14311    lon = adjust_lon(this.long0 + theta / this.ns);
14312    p.x = lon;
14313    p.y = lat;
14314    return p;
14315  }
14316
14317};
14318exports.names = ["Equidistant_Conic", "eqdc"];
14319
14320},{"../common/adjust_lat":67,"../common/adjust_lon":68,"../common/e0fn":70,"../common/e1fn":71,"../common/e2fn":72,"../common/e3fn":73,"../common/imlfn":75,"../common/mlfn":77,"../common/msfnz":78}],110:[function(require,module,exports){
14321var FORTPI = Math.PI/4;
14322var srat = require('../common/srat');
14323var HALF_PI = Math.PI/2;
14324var MAX_ITER = 20;
14325exports.init = function() {
14326  var sphi = Math.sin(this.lat0);
14327  var cphi = Math.cos(this.lat0);
14328  cphi *= cphi;
14329  this.rc = Math.sqrt(1 - this.es) / (1 - this.es * sphi * sphi);
14330  this.C = Math.sqrt(1 + this.es * cphi * cphi / (1 - this.es));
14331  this.phic0 = Math.asin(sphi / this.C);
14332  this.ratexp = 0.5 * this.C * this.e;
14333  this.K = Math.tan(0.5 * this.phic0 + FORTPI) / (Math.pow(Math.tan(0.5 * this.lat0 + FORTPI), this.C) * srat(this.e * sphi, this.ratexp));
14334};
14335
14336exports.forward = function(p) {
14337  var lon = p.x;
14338  var lat = p.y;
14339
14340  p.y = 2 * Math.atan(this.K * Math.pow(Math.tan(0.5 * lat + FORTPI), this.C) * srat(this.e * Math.sin(lat), this.ratexp)) - HALF_PI;
14341  p.x = this.C * lon;
14342  return p;
14343};
14344
14345exports.inverse = function(p) {
14346  var DEL_TOL = 1e-14;
14347  var lon = p.x / this.C;
14348  var lat = p.y;
14349  var num = Math.pow(Math.tan(0.5 * lat + FORTPI) / this.K, 1 / this.C);
14350  for (var i = MAX_ITER; i > 0; --i) {
14351    lat = 2 * Math.atan(num * srat(this.e * Math.sin(p.y), - 0.5 * this.e)) - HALF_PI;
14352    if (Math.abs(lat - p.y) < DEL_TOL) {
14353      break;
14354    }
14355    p.y = lat;
14356  }
14357  /* convergence failed */
14358  if (!i) {
14359    return null;
14360  }
14361  p.x = lon;
14362  p.y = lat;
14363  return p;
14364};
14365exports.names = ["gauss"];
14366
14367},{"../common/srat":85}],111:[function(require,module,exports){
14368var adjust_lon = require('../common/adjust_lon');
14369var EPSLN = 1.0e-10;
14370var asinz = require('../common/asinz');
14371
14372/*
14373  reference:
14374    Wolfram Mathworld "Gnomonic Projection"
14375    http://mathworld.wolfram.com/GnomonicProjection.html
14376    Accessed: 12th November 2009
14377  */
14378exports.init = function() {
14379
14380  /* Place parameters in static storage for common use
14381      -------------------------------------------------*/
14382  this.sin_p14 = Math.sin(this.lat0);
14383  this.cos_p14 = Math.cos(this.lat0);
14384  // Approximation for projecting points to the horizon (infinity)
14385  this.infinity_dist = 1000 * this.a;
14386  this.rc = 1;
14387};
14388
14389
14390/* Gnomonic forward equations--mapping lat,long to x,y
14391    ---------------------------------------------------*/
14392exports.forward = function(p) {
14393  var sinphi, cosphi; /* sin and cos value        */
14394  var dlon; /* delta longitude value      */
14395  var coslon; /* cos of longitude        */
14396  var ksp; /* scale factor          */
14397  var g;
14398  var x, y;
14399  var lon = p.x;
14400  var lat = p.y;
14401  /* Forward equations
14402      -----------------*/
14403  dlon = adjust_lon(lon - this.long0);
14404
14405  sinphi = Math.sin(lat);
14406  cosphi = Math.cos(lat);
14407
14408  coslon = Math.cos(dlon);
14409  g = this.sin_p14 * sinphi + this.cos_p14 * cosphi * coslon;
14410  ksp = 1;
14411  if ((g > 0) || (Math.abs(g) <= EPSLN)) {
14412    x = this.x0 + this.a * ksp * cosphi * Math.sin(dlon) / g;
14413    y = this.y0 + this.a * ksp * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon) / g;
14414  }
14415  else {
14416
14417    // Point is in the opposing hemisphere and is unprojectable
14418    // We still need to return a reasonable point, so we project 
14419    // to infinity, on a bearing 
14420    // equivalent to the northern hemisphere equivalent
14421    // This is a reasonable approximation for short shapes and lines that 
14422    // straddle the horizon.
14423
14424    x = this.x0 + this.infinity_dist * cosphi * Math.sin(dlon);
14425    y = this.y0 + this.infinity_dist * (this.cos_p14 * sinphi - this.sin_p14 * cosphi * coslon);
14426
14427  }
14428  p.x = x;
14429  p.y = y;
14430  return p;
14431};
14432
14433
14434exports.inverse = function(p) {
14435  var rh; /* Rho */
14436  var sinc, cosc;
14437  var c;
14438  var lon, lat;
14439
14440  /* Inverse equations
14441      -----------------*/
14442  p.x = (p.x - this.x0) / this.a;
14443  p.y = (p.y - this.y0) / this.a;
14444
14445  p.x /= this.k0;
14446  p.y /= this.k0;
14447
14448  if ((rh = Math.sqrt(p.x * p.x + p.y * p.y))) {
14449    c = Math.atan2(rh, this.rc);
14450    sinc = Math.sin(c);
14451    cosc = Math.cos(c);
14452
14453    lat = asinz(cosc * this.sin_p14 + (p.y * sinc * this.cos_p14) / rh);
14454    lon = Math.atan2(p.x * sinc, rh * this.cos_p14 * cosc - p.y * this.sin_p14 * sinc);
14455    lon = adjust_lon(this.long0 + lon);
14456  }
14457  else {
14458    lat = this.phic0;
14459    lon = 0;
14460  }
14461
14462  p.x = lon;
14463  p.y = lat;
14464  return p;
14465};
14466exports.names = ["gnom"];
14467
14468},{"../common/adjust_lon":68,"../common/asinz":69}],112:[function(require,module,exports){
14469var adjust_lon = require('../common/adjust_lon');
14470exports.init = function() {
14471  this.a = 6377397.155;
14472  this.es = 0.006674372230614;
14473  this.e = Math.sqrt(this.es);
14474  if (!this.lat0) {
14475    this.lat0 = 0.863937979737193;
14476  }
14477  if (!this.long0) {
14478    this.long0 = 0.7417649320975901 - 0.308341501185665;
14479  }
14480  /* if scale not set default to 0.9999 */
14481  if (!this.k0) {
14482    this.k0 = 0.9999;
14483  }
14484  this.s45 = 0.785398163397448; /* 45 */
14485  this.s90 = 2 * this.s45;
14486  this.fi0 = this.lat0;
14487  this.e2 = this.es;
14488  this.e = Math.sqrt(this.e2);
14489  this.alfa = Math.sqrt(1 + (this.e2 * Math.pow(Math.cos(this.fi0), 4)) / (1 - this.e2));
14490  this.uq = 1.04216856380474;
14491  this.u0 = Math.asin(Math.sin(this.fi0) / this.alfa);
14492  this.g = Math.pow((1 + this.e * Math.sin(this.fi0)) / (1 - this.e * Math.sin(this.fi0)), this.alfa * this.e / 2);
14493  this.k = Math.tan(this.u0 / 2 + this.s45) / Math.pow(Math.tan(this.fi0 / 2 + this.s45), this.alfa) * this.g;
14494  this.k1 = this.k0;
14495  this.n0 = this.a * Math.sqrt(1 - this.e2) / (1 - this.e2 * Math.pow(Math.sin(this.fi0), 2));
14496  this.s0 = 1.37008346281555;
14497  this.n = Math.sin(this.s0);
14498  this.ro0 = this.k1 * this.n0 / Math.tan(this.s0);
14499  this.ad = this.s90 - this.uq;
14500};
14501
14502/* ellipsoid */
14503/* calculate xy from lat/lon */
14504/* Constants, identical to inverse transform function */
14505exports.forward = function(p) {
14506  var gfi, u, deltav, s, d, eps, ro;
14507  var lon = p.x;
14508  var lat = p.y;
14509  var delta_lon = adjust_lon(lon - this.long0);
14510  /* Transformation */
14511  gfi = Math.pow(((1 + this.e * Math.sin(lat)) / (1 - this.e * Math.sin(lat))), (this.alfa * this.e / 2));
14512  u = 2 * (Math.atan(this.k * Math.pow(Math.tan(lat / 2 + this.s45), this.alfa) / gfi) - this.s45);
14513  deltav = -delta_lon * this.alfa;
14514  s = Math.asin(Math.cos(this.ad) * Math.sin(u) + Math.sin(this.ad) * Math.cos(u) * Math.cos(deltav));
14515  d = Math.asin(Math.cos(u) * Math.sin(deltav) / Math.cos(s));
14516  eps = this.n * d;
14517  ro = this.ro0 * Math.pow(Math.tan(this.s0 / 2 + this.s45), this.n) / Math.pow(Math.tan(s / 2 + this.s45), this.n);
14518  p.y = ro * Math.cos(eps) / 1;
14519  p.x = ro * Math.sin(eps) / 1;
14520
14521  if (!this.czech) {
14522    p.y *= -1;
14523    p.x *= -1;
14524  }
14525  return (p);
14526};
14527
14528/* calculate lat/lon from xy */
14529exports.inverse = function(p) {
14530  var u, deltav, s, d, eps, ro, fi1;
14531  var ok;
14532
14533  /* Transformation */
14534  /* revert y, x*/
14535  var tmp = p.x;
14536  p.x = p.y;
14537  p.y = tmp;
14538  if (!this.czech) {
14539    p.y *= -1;
14540    p.x *= -1;
14541  }
14542  ro = Math.sqrt(p.x * p.x + p.y * p.y);
14543  eps = Math.atan2(p.y, p.x);
14544  d = eps / Math.sin(this.s0);
14545  s = 2 * (Math.atan(Math.pow(this.ro0 / ro, 1 / this.n) * Math.tan(this.s0 / 2 + this.s45)) - this.s45);
14546  u = Math.asin(Math.cos(this.ad) * Math.sin(s) - Math.sin(this.ad) * Math.cos(s) * Math.cos(d));
14547  deltav = Math.asin(Math.cos(s) * Math.sin(d) / Math.cos(u));
14548  p.x = this.long0 - deltav / this.alfa;
14549  fi1 = u;
14550  ok = 0;
14551  var iter = 0;
14552  do {
14553    p.y = 2 * (Math.atan(Math.pow(this.k, - 1 / this.alfa) * Math.pow(Math.tan(u / 2 + this.s45), 1 / this.alfa) * Math.pow((1 + this.e * Math.sin(fi1)) / (1 - this.e * Math.sin(fi1)), this.e / 2)) - this.s45);
14554    if (Math.abs(fi1 - p.y) < 0.0000000001) {
14555      ok = 1;
14556    }
14557    fi1 = p.y;
14558    iter += 1;
14559  } while (ok === 0 && iter < 15);
14560  if (iter >= 15) {
14561    return null;
14562  }
14563
14564  return (p);
14565};
14566exports.names = ["Krovak", "krovak"];
14567
14568},{"../common/adjust_lon":68}],113:[function(require,module,exports){
14569var HALF_PI = Math.PI/2;
14570var FORTPI = Math.PI/4;
14571var EPSLN = 1.0e-10;
14572var qsfnz = require('../common/qsfnz');
14573var adjust_lon = require('../common/adjust_lon');
14574/*
14575  reference
14576    "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
14577    The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
14578  */
14579
14580exports.S_POLE = 1;
14581exports.N_POLE = 2;
14582exports.EQUIT = 3;
14583exports.OBLIQ = 4;
14584
14585
14586/* Initialize the Lambert Azimuthal Equal Area projection
14587  ------------------------------------------------------*/
14588exports.init = function() {
14589  var t = Math.abs(this.lat0);
14590  if (Math.abs(t - HALF_PI) < EPSLN) {
14591    this.mode = this.lat0 < 0 ? this.S_POLE : this.N_POLE;
14592  }
14593  else if (Math.abs(t) < EPSLN) {
14594    this.mode = this.EQUIT;
14595  }
14596  else {
14597    this.mode = this.OBLIQ;
14598  }
14599  if (this.es > 0) {
14600    var sinphi;
14601
14602    this.qp = qsfnz(this.e, 1);
14603    this.mmf = 0.5 / (1 - this.es);
14604    this.apa = this.authset(this.es);
14605    switch (this.mode) {
14606    case this.N_POLE:
14607      this.dd = 1;
14608      break;
14609    case this.S_POLE:
14610      this.dd = 1;
14611      break;
14612    case this.EQUIT:
14613      this.rq = Math.sqrt(0.5 * this.qp);
14614      this.dd = 1 / this.rq;
14615      this.xmf = 1;
14616      this.ymf = 0.5 * this.qp;
14617      break;
14618    case this.OBLIQ:
14619      this.rq = Math.sqrt(0.5 * this.qp);
14620      sinphi = Math.sin(this.lat0);
14621      this.sinb1 = qsfnz(this.e, sinphi) / this.qp;
14622      this.cosb1 = Math.sqrt(1 - this.sinb1 * this.sinb1);
14623      this.dd = Math.cos(this.lat0) / (Math.sqrt(1 - this.es * sinphi * sinphi) * this.rq * this.cosb1);
14624      this.ymf = (this.xmf = this.rq) / this.dd;
14625      this.xmf *= this.dd;
14626      break;
14627    }
14628  }
14629  else {
14630    if (this.mode === this.OBLIQ) {
14631      this.sinph0 = Math.sin(this.lat0);
14632      this.cosph0 = Math.cos(this.lat0);
14633    }
14634  }
14635};
14636
14637/* Lambert Azimuthal Equal Area forward equations--mapping lat,long to x,y
14638  -----------------------------------------------------------------------*/
14639exports.forward = function(p) {
14640
14641  /* Forward equations
14642      -----------------*/
14643  var x, y, coslam, sinlam, sinphi, q, sinb, cosb, b, cosphi;
14644  var lam = p.x;
14645  var phi = p.y;
14646
14647  lam = adjust_lon(lam - this.long0);
14648
14649  if (this.sphere) {
14650    sinphi = Math.sin(phi);
14651    cosphi = Math.cos(phi);
vendor: 5,559 bytes, lines 14652-14863
14652    coslam = Math.cos(lam);
14653    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
14654      y = (this.mode === this.EQUIT) ? 1 + cosphi * coslam : 1 + this.sinph0 * sinphi + this.cosph0 * cosphi * coslam;
14655      if (y <= EPSLN) {
14656        return null;
14657      }
14658      y = Math.sqrt(2 / y);
14659      x = y * cosphi * Math.sin(lam);
14660      y *= (this.mode === this.EQUIT) ? sinphi : this.cosph0 * sinphi - this.sinph0 * cosphi * coslam;
14661    }
14662    else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
14663      if (this.mode === this.N_POLE) {
14664        coslam = -coslam;
14665      }
14666      if (Math.abs(phi + this.phi0) < EPSLN) {
14667        return null;
14668      }
14669      y = FORTPI - phi * 0.5;
14670      y = 2 * ((this.mode === this.S_POLE) ? Math.cos(y) : Math.sin(y));
14671      x = y * Math.sin(lam);
14672      y *= coslam;
14673    }
14674  }
14675  else {
14676    sinb = 0;
14677    cosb = 0;
14678    b = 0;
14679    coslam = Math.cos(lam);
14680    sinlam = Math.sin(lam);
14681    sinphi = Math.sin(phi);
14682    q = qsfnz(this.e, sinphi);
14683    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
14684      sinb = q / this.qp;
14685      cosb = Math.sqrt(1 - sinb * sinb);
14686    }
14687    switch (this.mode) {
14688    case this.OBLIQ:
14689      b = 1 + this.sinb1 * sinb + this.cosb1 * cosb * coslam;
14690      break;
14691    case this.EQUIT:
14692      b = 1 + cosb * coslam;
14693      break;
14694    case this.N_POLE:
14695      b = HALF_PI + phi;
14696      q = this.qp - q;
14697      break;
14698    case this.S_POLE:
14699      b = phi - HALF_PI;
14700      q = this.qp + q;
14701      break;
14702    }
14703    if (Math.abs(b) < EPSLN) {
14704      return null;
14705    }
14706    switch (this.mode) {
14707    case this.OBLIQ:
14708    case this.EQUIT:
14709      b = Math.sqrt(2 / b);
14710      if (this.mode === this.OBLIQ) {
14711        y = this.ymf * b * (this.cosb1 * sinb - this.sinb1 * cosb * coslam);
14712      }
14713      else {
14714        y = (b = Math.sqrt(2 / (1 + cosb * coslam))) * sinb * this.ymf;
14715      }
14716      x = this.xmf * b * cosb * sinlam;
14717      break;
14718    case this.N_POLE:
14719    case this.S_POLE:
14720      if (q >= 0) {
14721        x = (b = Math.sqrt(q)) * sinlam;
14722        y = coslam * ((this.mode === this.S_POLE) ? b : -b);
14723      }
14724      else {
14725        x = y = 0;
14726      }
14727      break;
14728    }
14729  }
14730
14731  p.x = this.a * x + this.x0;
14732  p.y = this.a * y + this.y0;
14733  return p;
14734};
14735
14736/* Inverse equations
14737  -----------------*/
14738exports.inverse = function(p) {
14739  p.x -= this.x0;
14740  p.y -= this.y0;
14741  var x = p.x / this.a;
14742  var y = p.y / this.a;
14743  var lam, phi, cCe, sCe, q, rho, ab;
14744
14745  if (this.sphere) {
14746    var cosz = 0,
14747      rh, sinz = 0;
14748
14749    rh = Math.sqrt(x * x + y * y);
14750    phi = rh * 0.5;
14751    if (phi > 1) {
14752      return null;
14753    }
14754    phi = 2 * Math.asin(phi);
14755    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
14756      sinz = Math.sin(phi);
14757      cosz = Math.cos(phi);
14758    }
14759    switch (this.mode) {
14760    case this.EQUIT:
14761      phi = (Math.abs(rh) <= EPSLN) ? 0 : Math.asin(y * sinz / rh);
14762      x *= sinz;
14763      y = cosz * rh;
14764      break;
14765    case this.OBLIQ:
14766      phi = (Math.abs(rh) <= EPSLN) ? this.phi0 : Math.asin(cosz * this.sinph0 + y * sinz * this.cosph0 / rh);
14767      x *= sinz * this.cosph0;
14768      y = (cosz - Math.sin(phi) * this.sinph0) * rh;
14769      break;
14770    case this.N_POLE:
14771      y = -y;
14772      phi = HALF_PI - phi;
14773      break;
14774    case this.S_POLE:
14775      phi -= HALF_PI;
14776      break;
14777    }
14778    lam = (y === 0 && (this.mode === this.EQUIT || this.mode === this.OBLIQ)) ? 0 : Math.atan2(x, y);
14779  }
14780  else {
14781    ab = 0;
14782    if (this.mode === this.OBLIQ || this.mode === this.EQUIT) {
14783      x /= this.dd;
14784      y *= this.dd;
14785      rho = Math.sqrt(x * x + y * y);
14786      if (rho < EPSLN) {
14787        p.x = 0;
14788        p.y = this.phi0;
14789        return p;
14790      }
14791      sCe = 2 * Math.asin(0.5 * rho / this.rq);
14792      cCe = Math.cos(sCe);
14793      x *= (sCe = Math.sin(sCe));
14794      if (this.mode === this.OBLIQ) {
14795        ab = cCe * this.sinb1 + y * sCe * this.cosb1 / rho;
14796        q = this.qp * ab;
14797        y = rho * this.cosb1 * cCe - y * this.sinb1 * sCe;
14798      }
14799      else {
14800        ab = y * sCe / rho;
14801        q = this.qp * ab;
14802        y = rho * cCe;
14803      }
14804    }
14805    else if (this.mode === this.N_POLE || this.mode === this.S_POLE) {
14806      if (this.mode === this.N_POLE) {
14807        y = -y;
14808      }
14809      q = (x * x + y * y);
14810      if (!q) {
14811        p.x = 0;
14812        p.y = this.phi0;
14813        return p;
14814      }
14815      ab = 1 - q / this.qp;
14816      if (this.mode === this.S_POLE) {
14817        ab = -ab;
14818      }
14819    }
14820    lam = Math.atan2(x, y);
14821    phi = this.authlat(Math.asin(ab), this.apa);
14822  }
14823
14824
14825  p.x = adjust_lon(this.long0 + lam);
14826  p.y = phi;
14827  return p;
14828};
14829
14830/* determine latitude from authalic latitude */
14831exports.P00 = 0.33333333333333333333;
14832exports.P01 = 0.17222222222222222222;
14833exports.P02 = 0.10257936507936507936;
14834exports.P10 = 0.06388888888888888888;
14835exports.P11 = 0.06640211640211640211;
14836exports.P20 = 0.01641501294219154443;
14837
14838exports.authset = function(es) {
14839  var t;
14840  var APA = [];
14841  APA[0] = es * this.P00;
14842  t = es * es;
14843  APA[0] += t * this.P01;
14844  APA[1] = t * this.P10;
14845  t *= es;
14846  APA[0] += t * this.P02;
14847  APA[1] += t * this.P11;
14848  APA[2] = t * this.P20;
14849  return APA;
14850};
14851
14852exports.authlat = function(beta, APA) {
14853  var t = beta + beta;
14854  return (beta + APA[0] * Math.sin(t) + APA[1] * Math.sin(t + t) + APA[2] * Math.sin(t + t + t));
14855};
14856exports.names = ["Lambert Azimuthal Equal Area", "Lambert_Azimuthal_Equal_Area", "laea"];
14857
14858},{"../common/adjust_lon":68,"../common/qsfnz":83}],114:[function(require,module,exports){
14859var EPSLN = 1.0e-10;
14860var msfnz = require('../common/msfnz');
14861var tsfnz = require('../common/tsfnz');
14862var HALF_PI = Math.PI/2;
14863var sign = require('../common/sign');
vendor: 8,508 bytes, lines 14864-15174
14864var adjust_lon = require('../common/adjust_lon');
14865var phi2z = require('../common/phi2z');
14866exports.init = function() {
14867
14868  // array of:  r_maj,r_min,lat1,lat2,c_lon,c_lat,false_east,false_north
14869  //double c_lat;                   /* center latitude                      */
14870  //double c_lon;                   /* center longitude                     */
14871  //double lat1;                    /* first standard parallel              */
14872  //double lat2;                    /* second standard parallel             */
14873  //double r_maj;                   /* major axis                           */
14874  //double r_min;                   /* minor axis                           */
14875  //double false_east;              /* x offset in meters                   */
14876  //double false_north;             /* y offset in meters                   */
14877
14878  if (!this.lat2) {
14879    this.lat2 = this.lat1;
14880  } //if lat2 is not defined
14881  if (!this.k0) {
14882    this.k0 = 1;
14883  }
14884  this.x0 = this.x0 || 0;
14885  this.y0 = this.y0 || 0;
14886  // Standard Parallels cannot be equal and on opposite sides of the equator
14887  if (Math.abs(this.lat1 + this.lat2) < EPSLN) {
14888    return;
14889  }
14890
14891  var temp = this.b / this.a;
14892  this.e = Math.sqrt(1 - temp * temp);
14893
14894  var sin1 = Math.sin(this.lat1);
14895  var cos1 = Math.cos(this.lat1);
14896  var ms1 = msfnz(this.e, sin1, cos1);
14897  var ts1 = tsfnz(this.e, this.lat1, sin1);
14898
14899  var sin2 = Math.sin(this.lat2);
14900  var cos2 = Math.cos(this.lat2);
14901  var ms2 = msfnz(this.e, sin2, cos2);
14902  var ts2 = tsfnz(this.e, this.lat2, sin2);
14903
14904  var ts0 = tsfnz(this.e, this.lat0, Math.sin(this.lat0));
14905
14906  if (Math.abs(this.lat1 - this.lat2) > EPSLN) {
14907    this.ns = Math.log(ms1 / ms2) / Math.log(ts1 / ts2);
14908  }
14909  else {
14910    this.ns = sin1;
14911  }
14912  if (isNaN(this.ns)) {
14913    this.ns = sin1;
14914  }
14915  this.f0 = ms1 / (this.ns * Math.pow(ts1, this.ns));
14916  this.rh = this.a * this.f0 * Math.pow(ts0, this.ns);
14917  if (!this.title) {
14918    this.title = "Lambert Conformal Conic";
14919  }
14920};
14921
14922
14923// Lambert Conformal conic forward equations--mapping lat,long to x,y
14924// -----------------------------------------------------------------
14925exports.forward = function(p) {
14926
14927  var lon = p.x;
14928  var lat = p.y;
14929
14930  // singular cases :
14931  if (Math.abs(2 * Math.abs(lat) - Math.PI) <= EPSLN) {
14932    lat = sign(lat) * (HALF_PI - 2 * EPSLN);
14933  }
14934
14935  var con = Math.abs(Math.abs(lat) - HALF_PI);
14936  var ts, rh1;
14937  if (con > EPSLN) {
14938    ts = tsfnz(this.e, lat, Math.sin(lat));
14939    rh1 = this.a * this.f0 * Math.pow(ts, this.ns);
14940  }
14941  else {
14942    con = lat * this.ns;
14943    if (con <= 0) {
14944      return null;
14945    }
14946    rh1 = 0;
14947  }
14948  var theta = this.ns * adjust_lon(lon - this.long0);
14949  p.x = this.k0 * (rh1 * Math.sin(theta)) + this.x0;
14950  p.y = this.k0 * (this.rh - rh1 * Math.cos(theta)) + this.y0;
14951
14952  return p;
14953};
14954
14955// Lambert Conformal Conic inverse equations--mapping x,y to lat/long
14956// -----------------------------------------------------------------
14957exports.inverse = function(p) {
14958
14959  var rh1, con, ts;
14960  var lat, lon;
14961  var x = (p.x - this.x0) / this.k0;
14962  var y = (this.rh - (p.y - this.y0) / this.k0);
14963  if (this.ns > 0) {
14964    rh1 = Math.sqrt(x * x + y * y);
14965    con = 1;
14966  }
14967  else {
14968    rh1 = -Math.sqrt(x * x + y * y);
14969    con = -1;
14970  }
14971  var theta = 0;
14972  if (rh1 !== 0) {
14973    theta = Math.atan2((con * x), (con * y));
14974  }
14975  if ((rh1 !== 0) || (this.ns > 0)) {
14976    con = 1 / this.ns;
14977    ts = Math.pow((rh1 / (this.a * this.f0)), con);
14978    lat = phi2z(this.e, ts);
14979    if (lat === -9999) {
14980      return null;
14981    }
14982  }
14983  else {
14984    lat = -HALF_PI;
14985  }
14986  lon = adjust_lon(theta / this.ns + this.long0);
14987
14988  p.x = lon;
14989  p.y = lat;
14990  return p;
14991};
14992
14993exports.names = ["Lambert Tangential Conformal Conic Projection", "Lambert_Conformal_Conic", "Lambert_Conformal_Conic_2SP", "lcc"];
14994
14995},{"../common/adjust_lon":68,"../common/msfnz":78,"../common/phi2z":79,"../common/sign":84,"../common/tsfnz":87}],115:[function(require,module,exports){
14996exports.init = function() {
14997  //no-op for longlat
14998};
14999
15000function identity(pt) {
15001  return pt;
15002}
15003exports.forward = identity;
15004exports.inverse = identity;
15005exports.names = ["longlat", "identity"];
15006
15007},{}],116:[function(require,module,exports){
15008var msfnz = require('../common/msfnz');
15009var HALF_PI = Math.PI/2;
15010var EPSLN = 1.0e-10;
15011var R2D = 57.29577951308232088;
15012var adjust_lon = require('../common/adjust_lon');
15013var FORTPI = Math.PI/4;
15014var tsfnz = require('../common/tsfnz');
15015var phi2z = require('../common/phi2z');
15016exports.init = function() {
15017  var con = this.b / this.a;
15018  this.es = 1 - con * con;
15019  if(!('x0' in this)){
15020    this.x0 = 0;
15021  }
15022  if(!('y0' in this)){
15023    this.y0 = 0;
15024  }
15025  this.e = Math.sqrt(this.es);
15026  if (this.lat_ts) {
15027    if (this.sphere) {
15028      this.k0 = Math.cos(this.lat_ts);
15029    }
15030    else {
15031      this.k0 = msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts));
15032    }
15033  }
15034  else {
15035    if (!this.k0) {
15036      if (this.k) {
15037        this.k0 = this.k;
15038      }
15039      else {
15040        this.k0 = 1;
15041      }
15042    }
15043  }
15044};
15045
15046/* Mercator forward equations--mapping lat,long to x,y
15047  --------------------------------------------------*/
15048
15049exports.forward = function(p) {
15050  var lon = p.x;
15051  var lat = p.y;
15052  // convert to radians
15053  if (lat * R2D > 90 && lat * R2D < -90 && lon * R2D > 180 && lon * R2D < -180) {
15054    return null;
15055  }
15056
15057  var x, y;
15058  if (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN) {
15059    return null;
15060  }
15061  else {
15062    if (this.sphere) {
15063      x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0);
15064      y = this.y0 + this.a * this.k0 * Math.log(Math.tan(FORTPI + 0.5 * lat));
15065    }
15066    else {
15067      var sinphi = Math.sin(lat);
15068      var ts = tsfnz(this.e, lat, sinphi);
15069      x = this.x0 + this.a * this.k0 * adjust_lon(lon - this.long0);
15070      y = this.y0 - this.a * this.k0 * Math.log(ts);
15071    }
15072    p.x = x;
15073    p.y = y;
15074    return p;
15075  }
15076};
15077
15078
15079/* Mercator inverse equations--mapping x,y to lat/long
15080  --------------------------------------------------*/
15081exports.inverse = function(p) {
15082
15083  var x = p.x - this.x0;
15084  var y = p.y - this.y0;
15085  var lon, lat;
15086
15087  if (this.sphere) {
15088    lat = HALF_PI - 2 * Math.atan(Math.exp(-y / (this.a * this.k0)));
15089  }
15090  else {
15091    var ts = Math.exp(-y / (this.a * this.k0));
15092    lat = phi2z(this.e, ts);
15093    if (lat === -9999) {
15094      return null;
15095    }
15096  }
15097  lon = adjust_lon(this.long0 + x / (this.a * this.k0));
15098
15099  p.x = lon;
15100  p.y = lat;
15101  return p;
15102};
15103
15104exports.names = ["Mercator", "Popular Visualisation Pseudo Mercator", "Mercator_1SP", "Mercator_Auxiliary_Sphere", "merc"];
15105
15106},{"../common/adjust_lon":68,"../common/msfnz":78,"../common/phi2z":79,"../common/tsfnz":87}],117:[function(require,module,exports){
15107var adjust_lon = require('../common/adjust_lon');
15108/*
15109  reference
15110    "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
15111    The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
15112  */
15113
15114
15115/* Initialize the Miller Cylindrical projection
15116  -------------------------------------------*/
15117exports.init = function() {
15118  //no-op
15119};
15120
15121
15122/* Miller Cylindrical forward equations--mapping lat,long to x,y
15123    ------------------------------------------------------------*/
15124exports.forward = function(p) {
15125  var lon = p.x;
15126  var lat = p.y;
15127  /* Forward equations
15128      -----------------*/
15129  var dlon = adjust_lon(lon - this.long0);
15130  var x = this.x0 + this.a * dlon;
15131  var y = this.y0 + this.a * Math.log(Math.tan((Math.PI / 4) + (lat / 2.5))) * 1.25;
15132
15133  p.x = x;
15134  p.y = y;
15135  return p;
15136};
15137
15138/* Miller Cylindrical inverse equations--mapping x,y to lat/long
15139    ------------------------------------------------------------*/
15140exports.inverse = function(p) {
15141  p.x -= this.x0;
15142  p.y -= this.y0;
15143
15144  var lon = adjust_lon(this.long0 + p.x / this.a);
15145  var lat = 2.5 * (Math.atan(Math.exp(0.8 * p.y / this.a)) - Math.PI / 4);
15146
15147  p.x = lon;
15148  p.y = lat;
15149  return p;
15150};
15151exports.names = ["Miller_Cylindrical", "mill"];
15152
15153},{"../common/adjust_lon":68}],118:[function(require,module,exports){
15154var adjust_lon = require('../common/adjust_lon');
15155var EPSLN = 1.0e-10;
15156exports.init = function() {};
15157
15158/* Mollweide forward equations--mapping lat,long to x,y
15159    ----------------------------------------------------*/
15160exports.forward = function(p) {
15161
15162  /* Forward equations
15163      -----------------*/
15164  var lon = p.x;
15165  var lat = p.y;
15166
15167  var delta_lon = adjust_lon(lon - this.long0);
15168  var theta = lat;
15169  var con = Math.PI * Math.sin(lat);
15170
15171  /* Iterate using the Newton-Raphson method to find theta
15172      -----------------------------------------------------*/
15173  for (var i = 0; true; i++) {
15174    var delta_theta = -(theta + Math.sin(theta) - con) / (1 + Math.
vendor: 5,851 bytes, lines 15174-15401
15174cos(theta));
15175    theta += delta_theta;
15176    if (Math.abs(delta_theta) < EPSLN) {
15177      break;
15178    }
15179  }
15180  theta /= 2;
15181
15182  /* If the latitude is 90 deg, force the x coordinate to be "0 + false easting"
15183       this is done here because of precision problems with "cos(theta)"
15184       --------------------------------------------------------------------------*/
15185  if (Math.PI / 2 - Math.abs(lat) < EPSLN) {
15186    delta_lon = 0;
15187  }
15188  var x = 0.900316316158 * this.a * delta_lon * Math.cos(theta) + this.x0;
15189  var y = 1.4142135623731 * this.a * Math.sin(theta) + this.y0;
15190
15191  p.x = x;
15192  p.y = y;
15193  return p;
15194};
15195
15196exports.inverse = function(p) {
15197  var theta;
15198  var arg;
15199
15200  /* Inverse equations
15201      -----------------*/
15202  p.x -= this.x0;
15203  p.y -= this.y0;
15204  arg = p.y / (1.4142135623731 * this.a);
15205
15206  /* Because of division by zero problems, 'arg' can not be 1.  Therefore
15207       a number very close to one is used instead.
15208       -------------------------------------------------------------------*/
15209  if (Math.abs(arg) > 0.999999999999) {
15210    arg = 0.999999999999;
15211  }
15212  theta = Math.asin(arg);
15213  var lon = adjust_lon(this.long0 + (p.x / (0.900316316158 * this.a * Math.cos(theta))));
15214  if (lon < (-Math.PI)) {
15215    lon = -Math.PI;
15216  }
15217  if (lon > Math.PI) {
15218    lon = Math.PI;
15219  }
15220  arg = (2 * theta + Math.sin(2 * theta)) / Math.PI;
15221  if (Math.abs(arg) > 1) {
15222    arg = 1;
15223  }
15224  var lat = Math.asin(arg);
15225
15226  p.x = lon;
15227  p.y = lat;
15228  return p;
15229};
15230exports.names = ["Mollweide", "moll"];
15231
15232},{"../common/adjust_lon":68}],119:[function(require,module,exports){
15233var SEC_TO_RAD = 4.84813681109535993589914102357e-6;
15234/*
15235  reference
15236    Department of Land and Survey Technical Circular 1973/32
15237      http://www.linz.govt.nz/docs/miscellaneous/nz-map-definition.pdf
15238    OSG Technical Report 4.1
15239      http://www.linz.govt.nz/docs/miscellaneous/nzmg.pdf
15240  */
15241
15242/**
15243 * iterations: Number of iterations to refine inverse transform.
15244 *     0 -> km accuracy
15245 *     1 -> m accuracy -- suitable for most mapping applications
15246 *     2 -> mm accuracy
15247 */
15248exports.iterations = 1;
15249
15250exports.init = function() {
15251  this.A = [];
15252  this.A[1] = 0.6399175073;
15253  this.A[2] = -0.1358797613;
15254  this.A[3] = 0.063294409;
15255  this.A[4] = -0.02526853;
15256  this.A[5] = 0.0117879;
15257  this.A[6] = -0.0055161;
15258  this.A[7] = 0.0026906;
15259  this.A[8] = -0.001333;
15260  this.A[9] = 0.00067;
15261  this.A[10] = -0.00034;
15262
15263  this.B_re = [];
15264  this.B_im = [];
15265  this.B_re[1] = 0.7557853228;
15266  this.B_im[1] = 0;
15267  this.B_re[2] = 0.249204646;
15268  this.B_im[2] = 0.003371507;
15269  this.B_re[3] = -0.001541739;
15270  this.B_im[3] = 0.041058560;
15271  this.B_re[4] = -0.10162907;
15272  this.B_im[4] = 0.01727609;
15273  this.B_re[5] = -0.26623489;
15274  this.B_im[5] = -0.36249218;
15275  this.B_re[6] = -0.6870983;
15276  this.B_im[6] = -1.1651967;
15277
15278  this.C_re = [];
15279  this.C_im = [];
15280  this.C_re[1] = 1.3231270439;
15281  this.C_im[1] = 0;
15282  this.C_re[2] = -0.577245789;
15283  this.C_im[2] = -0.007809598;
15284  this.C_re[3] = 0.508307513;
15285  this.C_im[3] = -0.112208952;
15286  this.C_re[4] = -0.15094762;
15287  this.C_im[4] = 0.18200602;
15288  this.C_re[5] = 1.01418179;
15289  this.C_im[5] = 1.64497696;
15290  this.C_re[6] = 1.9660549;
15291  this.C_im[6] = 2.5127645;
15292
15293  this.D = [];
15294  this.D[1] = 1.5627014243;
15295  this.D[2] = 0.5185406398;
15296  this.D[3] = -0.03333098;
15297  this.D[4] = -0.1052906;
15298  this.D[5] = -0.0368594;
15299  this.D[6] = 0.007317;
15300  this.D[7] = 0.01220;
15301  this.D[8] = 0.00394;
15302  this.D[9] = -0.0013;
15303};
15304
15305/**
15306    New Zealand Map Grid Forward  - long/lat to x/y
15307    long/lat in radians
15308  */
15309exports.forward = function(p) {
15310  var n;
15311  var lon = p.x;
15312  var lat = p.y;
15313
15314  var delta_lat = lat - this.lat0;
15315  var delta_lon = lon - this.long0;
15316
15317  // 1. Calculate d_phi and d_psi    ...                          // and d_lambda
15318  // For this algorithm, delta_latitude is in seconds of arc x 10-5, so we need to scale to those units. Longitude is radians.
15319  var d_phi = delta_lat / SEC_TO_RAD * 1E-5;
15320  var d_lambda = delta_lon;
15321  var d_phi_n = 1; // d_phi^0
15322
15323  var d_psi = 0;
15324  for (n = 1; n <= 10; n++) {
15325    d_phi_n = d_phi_n * d_phi;
15326    d_psi = d_psi + this.A[n] * d_phi_n;
15327  }
15328
15329  // 2. Calculate theta
15330  var th_re = d_psi;
15331  var th_im = d_lambda;
15332
15333  // 3. Calculate z
15334  var th_n_re = 1;
15335  var th_n_im = 0; // theta^0
15336  var th_n_re1;
15337  var th_n_im1;
15338
15339  var z_re = 0;
15340  var z_im = 0;
15341  for (n = 1; n <= 6; n++) {
15342    th_n_re1 = th_n_re * th_re - th_n_im * th_im;
15343    th_n_im1 = th_n_im * th_re + th_n_re * th_im;
15344    th_n_re = th_n_re1;
15345    th_n_im = th_n_im1;
15346    z_re = z_re + this.B_re[n] * th_n_re - this.B_im[n] * th_n_im;
15347    z_im = z_im + this.B_im[n] * th_n_re + this.B_re[n] * th_n_im;
15348  }
15349
15350  // 4. Calculate easting and northing
15351  p.x = (z_im * this.a) + this.x0;
15352  p.y = (z_re * this.a) + this.y0;
15353
15354  return p;
15355};
15356
15357
15358/**
15359    New Zealand Map Grid Inverse  -  x/y to long/lat
15360  */
15361exports.inverse = function(p) {
15362  var n;
15363  var x = p.x;
15364  var y = p.y;
15365
15366  var delta_x = x - this.x0;
15367  var delta_y = y - this.y0;
15368
15369  // 1. Calculate z
15370  var z_re = delta_y / this.a;
15371  var z_im = delta_x / this.a;
15372
15373  // 2a. Calculate theta - first approximation gives km accuracy
15374  var z_n_re = 1;
15375  var z_n_im = 0; // z^0
15376  var z_n_re1;
15377  var z_n_im1;
15378
15379  var th_re = 0;
15380  var th_im = 0;
15381  for (n = 1; n <= 6; n++) {
15382    z_n_re1 = z_n_re * z_re - z_n_im * z_im;
15383    z_n_im1 = z_n_im * z_re + z_n_re * z_im;
15384    z_n_re = z_n_re1;
15385    z_n_im = z_n_im1;
15386    th_re = th_re + this.C_re[n] * z_n_re - this.C_im[n] * z_n_im;
15387    th_im = th_im + this.C_im[n] * z_n_re + this.C_re[n] * z_n_im;
15388  }
15389
15390  // 2b. Iterate to refine the accuracy of the calculation
15391  //        0 iterations gives km accuracy
15392  //        1 iteration gives m accuracy -- good enough for most mapping applications
15393  //        2 iterations bives mm accuracy
15394  for (var i = 0; i < this.iterations; i++) {
15395    var th_n_re = th_re;
15396    var th_n_im = th_im;
15397    var th_n_re1;
15398    var th_n_im1;
15399
15400    var num_re = z_re;
15401    var num_im = z_im;
15402    for (n = 2; n <= 6; n++) {
15403      th_n_re1 = th_n_re * th_re - th_n_im * th_im;
15404      th_n_im1 = th_n_im * th_re + th_n_re * th_im;
15405      th_n_re = th_n_re1;
15406      th_n_im = th_n_im1;
15407      num_re = num_re + (n - 1) * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
15408      num_im = num_im + (n - 1) * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
15409    }
15410
15411    th_n_re = 1;
15412    th_n_im = 0;
15413    var den_re = this.B_re[1];
15414    var den_im = this.B_im[1];
15415    for (n = 2; n <= 6; n++) {
15416      th_n_re1 = th_n_re * th_re - th_n_im * th_im;
15417      th_n_im1 = th_n_im * th_re + th_n_re * th_im;
15418      th_n_re = th_n_re1;
15419      th_n_im = th_n_im1;
15420      den_re = den_re + n * (this.B_re[n] * th_n_re - this.B_im[n] * th_n_im);
15421      den_im = den_im + n * (this.B_im[n] * th_n_re + this.B_re[n] * th_n_im);
15422    }
15423
15424    // Complex division
15425    var den2 = den_re * den_re + den_im * den_im;
15426    th_re = (num_re * den_re + num_im * den_im) / den2;
15427    th_im = (num_im * den_re - num_re * den_im) / den2;
15428  }
15429
15430  // 3. Calculate d_phi              ...                                    // and d_lambda
15431  var d_psi = th_re;
15432  var d_lambda = th_im;
15433  var d_psi_n = 1; // d_psi^0
15434
15435  var d_phi = 0;
15436  for (n = 1; n <= 9; n++) {
15437    d_psi_n = d_psi_n * d_psi;
15438    d_phi = d_phi + this.D[n] * d_psi_n;
15439  }
15440
15441  // 4. Calculate latitude and longitude
15442  // d_phi is calcuated in second of arc * 10^-5, so we need to scale back to radians. d_lambda is in radians.
15443  var lat = this.lat0 + (d_phi * SEC_TO_RAD * 1E5);
15444  var lon = this.long0 + d_lambda;
15445
15446  p.x = lon;
15447  p.y = lat;
15448
15449  return p;
15450};
15451exports.names = ["New_Zealand_Map_Grid", "nzmg"];
15452},{}],120:[function(require,module,exports){
15453var tsfnz = require('../common/tsfnz');
15454var adjust_lon = require('../common/adjust_lon');
15455var phi2z = require('../common/phi2z');
15456var HALF_PI = Math.PI/2;
15457var FORTPI = Math.PI/4;
15458var EPSLN = 1.0e-10;
15459
15460/* Initialize the Oblique Mercator  projection
15461    ------------------------------------------*/
15462exports.init = function() {
15463  this.no_off = this.no_off || false;
15464  this.no_rot = this.no_rot || false;
15465
15466  if (isNaN(this.k0)) {
15467    this.k0 = 1;
15468  }
15469  var sinlat = Math.sin(this.lat0);
15470  var coslat = Math.cos(this.lat0);
15471  var con = this.e * sinlat;
15472
15473  this.bl = Math.sqrt(1 + this.es / (1 - this.es) * Math.pow(coslat, 4));
15474  this.al = this.a * this.bl * this.k0 * Math.sqrt(1 - this.es) / (1 - con * con);
15475  var t0 = tsfnz(this.e, this.lat0, sinlat);
15476  var dl = this.bl / coslat * Math.sqrt((1 - this.es) / (1 - con * con));
15477  if (dl * dl < 1) {
15478    dl = 1;
15479  }
15480  var fl;
15481  var gl;
15482  if (!isNaN(this.longc)) {
15483    //Central point and azimuth method
15484
15485    if (this.lat0 >= 0) {
15486      fl = dl + Math.sqrt(dl * dl - 1);
15487    }
15488    else {
15489      fl = dl - Math.sqrt(dl * dl - 1);
15490    }
15491    this.el = fl * Math.pow(t0, this.bl);
15492    gl = 0.5 * (fl - 1 / fl);
15493    this.gamma0 = Math.asin(Math.sin(this.alpha) / dl);
15494    this.long0 = this.longc - Math.asin(gl * Math.tan(this.gamma0)) / this.bl;
15495
15496  }
15497  else {
15498    //2 points method
15499    var t1 = tsfnz(this.e, this.lat1, Math.sin(this.lat1));
15500    var t2 = tsfnz(this.e, this.lat2, Math.sin(this.lat2));
15501    if (this.lat0 >= 0) {
15502      this.el = (dl + Math.sqrt(dl * dl - 1)) * Math.pow(t0, this.bl);
15503    }
15504    else {
15505      this.el = (dl - Math.sqrt(dl * dl - 1)) * Math.pow(t0, this.bl);
15506    }
15507    var hl = Math.pow(t1, this.bl);
15508    var ll = Math.pow(t2, this.bl);
15509    fl = this.el / hl;
15510    gl = 0.5 * (fl - 1 / fl);
15511    var jl = (this.el * this.el - ll * hl) / (this.el * this.el + ll * hl);
15512    var pl = (ll - hl) / (ll + hl);
15513    var dlon12 = adjust_lon(this.long1 - this.long2);
15514    this.long0 = 0.5 * (this.long1 + this.long2) - Math.atan(jl * Math.tan(0.5 * this.bl * (dlon12)) / pl) / this.bl;
15515    this.long0 = adjust_lon(this.long0);
15516    var dlon10 = adjust_lon(this.long1 - this.long0);
15517    this.gamma0 = Math.atan(Math.sin(this.bl * (dlon10)) / gl);
15518    this.alpha = Math.asin(dl * Math.sin(this.gamma0));
15519  }
15520
15521  if (this.no_off) {
15522    this.uc = 0;
15523  }
15524  else {
15525    if (this.lat0 >= 0) {
15526      this.uc = this.al / this.bl * Math.atan2(Math.sqrt(dl * dl - 1), Math.cos(this.alpha));
15527    }
15528    else {
15529      this.uc = -1 * this.al / this.bl * Math.atan2(Math.sqrt(dl * dl - 1), Math.cos(this.alpha));
15530    }
15531  }
15532
15533};
15534
15535
15536/* Oblique Mercator forward equations--mapping lat,long to x,y
15537    ----------------------------------------------------------*/
15538exports.forward = function(p) {
15539  var lon = p.x;
15540  var lat = p.y;
15541  var dlon = adjust_lon(lon - this.long0);
15542  var us, vs;
15543  var con;
15544  if (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN) {
15545    if (lat > 0) {
15546      con = -1;
15547    }
15548    else {
15549      con = 1;
15550    }
15551    vs = this.al / this.bl * Math.log(Math.tan(FORTPI + con * this.gamma0 * 0.5));
15552    us = -1 * con * HALF_PI * this.al / this.bl;
15553  }
15554  else {
15555    var t = tsfnz(this.e, lat, Math.sin(lat));
15556    var ql = this.el / Math.pow(t, this.bl);
15557    var sl = 0.5 * (ql - 1 / ql);
15558    var tl = 0.5 * (ql + 1 / ql);
15559    var vl = Math.sin(this.bl * (dlon));
15560    var ul = (sl * Math.sin(this.gamma0) - vl * Math.cos(this.gamma0)) / tl;
15561    if (Math.abs(Math.abs(ul) - 1) <= EPSLN) {
15562      vs = Number.POSITIVE_INFINITY;
15563    }
15564    else {
15565      vs = 0.5 * this.al * Math.log((1 - ul) / (1 + ul)) / this.bl;
15566    }
15567    if (Math.abs(Math.cos(this.bl * (dlon))) <= EPSLN) {
15568      us = this.al * this.bl * (dlon);
15569    }
15570    else {
15571      us = this.al * Math.atan2(sl * Math.cos(this.gamma0) + vl * Math.sin(this.gamma0), Math.cos(this.bl * dlon)) / this.bl;
15572    }
15573  }
15574
15575  if (this.no_rot) {
15576    p.x = this.x0 + us;
15577    p.y = this.y0 + vs;
15578  }
15579  else {
15580
15581    us -= this.uc;
15582    p.x = this.x0 + vs * Math.cos(this.alpha) + us * Math.sin(this.alpha);
15583    p.y = this.y0 + us * Math.cos(this.alpha) - vs * Math.sin(this.alpha);
15584  }
15585  return p;
15586};
15587
15588exports.inverse = function(p) {
15589  var us, vs;
15590  if (this.no_rot) {
15591    vs = p.y - this.y0;
15592    us = p.x - this.x0;
15593  }
15594  else {
15595    vs = (p.x - this.x0) * Math.cos(this.alpha) - (p.y - this.y0) * Math.sin(this.alpha);
15596    us = (p.y - this.y0) * Math.cos(this.alpha) + (p.x - this.x0) * Math.sin(this.alpha);
15597    us += this.uc;
15598  }
15599  var qp = Math.exp(-1 * this.bl * vs / this.al);
15600  var sp = 0.5 * (qp - 1 / qp);
15601  var tp = 0.5 * (qp + 1 / qp);
15602  var vp = Math.sin(this.bl * us / this.al);
15603  var up = (vp * Math.cos(this.gamma0) + sp * Math.sin(this.gamma0)) / tp;
15604  var ts = Math.pow(this.el / Math.sqrt((1 + up) / (1 - up)), 1 / this.bl);
15605  if (Math.abs(up - 1) < EPSLN) {
15606    p.x = this.long0;
15607    p.y = HALF_PI;
15608  }
15609  else if (Math.abs(up + 1) < EPSLN) {
15610    p.x = this.long0;
15611    p.y = -1 * HALF_PI;
15612  }
15613  else {
15614    p.y = phi2z(this.e, ts);
15615    p.x = adjust_lon(this.long0 - Math.atan2(sp * Math.cos(this.gamma0) - vp * Math.sin(this.gamma0), Math.cos(this.bl * us / this.al)) / this.bl);
15616  }
15617  return p;
15618};
15619
15620exports.names = ["Hotine_Oblique_Mercator", "Hotine Oblique Mercator", "Hotine_Oblique_Mercator_Azimuth_Natural_Origin", "Hotine_Oblique_Mercator_Azimuth_Center", "omerc"];
15621},{"../common/adjust_lon":68,"../common/phi2z":79,"../common/tsfnz":87}],121:[function(require,module,exports){
15622var e0fn = require('../common/e0fn');
15623var e1fn = require('../common/e1fn');
15624var e2fn = require('../common/e2fn');
15625var e3fn = require('../common/e3fn');
vendor: 15,343 bytes, lines 15626-16108
15626var adjust_lon = require('../common/adjust_lon');
15627var adjust_lat = require('../common/adjust_lat');
15628var mlfn = require('../common/mlfn');
15629var EPSLN = 1.0e-10;
15630var gN = require('../common/gN');
15631var MAX_ITER = 20;
15632exports.init = function() {
15633  /* Place parameters in static storage for common use
15634      -------------------------------------------------*/
15635  this.temp = this.b / this.a;
15636  this.es = 1 - Math.pow(this.temp, 2); // devait etre dans tmerc.js mais n y est pas donc je commente sinon retour de valeurs nulles
15637  this.e = Math.sqrt(this.es);
15638  this.e0 = e0fn(this.es);
15639  this.e1 = e1fn(this.es);
15640  this.e2 = e2fn(this.es);
15641  this.e3 = e3fn(this.es);
15642  this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0); //si que des zeros le calcul ne se fait pas
15643};
15644
15645
15646/* Polyconic forward equations--mapping lat,long to x,y
15647    ---------------------------------------------------*/
15648exports.forward = function(p) {
15649  var lon = p.x;
15650  var lat = p.y;
15651  var x, y, el;
15652  var dlon = adjust_lon(lon - this.long0);
15653  el = dlon * Math.sin(lat);
15654  if (this.sphere) {
15655    if (Math.abs(lat) <= EPSLN) {
15656      x = this.a * dlon;
15657      y = -1 * this.a * this.lat0;
15658    }
15659    else {
15660      x = this.a * Math.sin(el) / Math.tan(lat);
15661      y = this.a * (adjust_lat(lat - this.lat0) + (1 - Math.cos(el)) / Math.tan(lat));
15662    }
15663  }
15664  else {
15665    if (Math.abs(lat) <= EPSLN) {
15666      x = this.a * dlon;
15667      y = -1 * this.ml0;
15668    }
15669    else {
15670      var nl = gN(this.a, this.e, Math.sin(lat)) / Math.tan(lat);
15671      x = nl * Math.sin(el);
15672      y = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, lat) - this.ml0 + nl * (1 - Math.cos(el));
15673    }
15674
15675  }
15676  p.x = x + this.x0;
15677  p.y = y + this.y0;
15678  return p;
15679};
15680
15681
15682/* Inverse equations
15683  -----------------*/
15684exports.inverse = function(p) {
15685  var lon, lat, x, y, i;
15686  var al, bl;
15687  var phi, dphi;
15688  x = p.x - this.x0;
15689  y = p.y - this.y0;
15690
15691  if (this.sphere) {
15692    if (Math.abs(y + this.a * this.lat0) <= EPSLN) {
15693      lon = adjust_lon(x / this.a + this.long0);
15694      lat = 0;
15695    }
15696    else {
15697      al = this.lat0 + y / this.a;
15698      bl = x * x / this.a / this.a + al * al;
15699      phi = al;
15700      var tanphi;
15701      for (i = MAX_ITER; i; --i) {
15702        tanphi = Math.tan(phi);
15703        dphi = -1 * (al * (phi * tanphi + 1) - phi - 0.5 * (phi * phi + bl) * tanphi) / ((phi - al) / tanphi - 1);
15704        phi += dphi;
15705        if (Math.abs(dphi) <= EPSLN) {
15706          lat = phi;
15707          break;
15708        }
15709      }
15710      lon = adjust_lon(this.long0 + (Math.asin(x * Math.tan(phi) / this.a)) / Math.sin(lat));
15711    }
15712  }
15713  else {
15714    if (Math.abs(y + this.ml0) <= EPSLN) {
15715      lat = 0;
15716      lon = adjust_lon(this.long0 + x / this.a);
15717    }
15718    else {
15719
15720      al = (this.ml0 + y) / this.a;
15721      bl = x * x / this.a / this.a + al * al;
15722      phi = al;
15723      var cl, mln, mlnp, ma;
15724      var con;
15725      for (i = MAX_ITER; i; --i) {
15726        con = this.e * Math.sin(phi);
15727        cl = Math.sqrt(1 - con * con) * Math.tan(phi);
15728        mln = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, phi);
15729        mlnp = this.e0 - 2 * this.e1 * Math.cos(2 * phi) + 4 * this.e2 * Math.cos(4 * phi) - 6 * this.e3 * Math.cos(6 * phi);
15730        ma = mln / this.a;
15731        dphi = (al * (cl * ma + 1) - ma - 0.5 * cl * (ma * ma + bl)) / (this.es * Math.sin(2 * phi) * (ma * ma + bl - 2 * al * ma) / (4 * cl) + (al - ma) * (cl * mlnp - 2 / Math.sin(2 * phi)) - mlnp);
15732        phi -= dphi;
15733        if (Math.abs(dphi) <= EPSLN) {
15734          lat = phi;
15735          break;
15736        }
15737      }
15738
15739      //lat=phi4z(this.e,this.e0,this.e1,this.e2,this.e3,al,bl,0,0);
15740      cl = Math.sqrt(1 - this.es * Math.pow(Math.sin(lat), 2)) * Math.tan(lat);
15741      lon = adjust_lon(this.long0 + Math.asin(x * cl / this.a) / Math.sin(lat));
15742    }
15743  }
15744
15745  p.x = lon;
15746  p.y = lat;
15747  return p;
15748};
15749exports.names = ["Polyconic", "poly"];
15750},{"../common/adjust_lat":67,"../common/adjust_lon":68,"../common/e0fn":70,"../common/e1fn":71,"../common/e2fn":72,"../common/e3fn":73,"../common/gN":74,"../common/mlfn":77}],122:[function(require,module,exports){
15751var adjust_lon = require('../common/adjust_lon');
15752var adjust_lat = require('../common/adjust_lat');
15753var pj_enfn = require('../common/pj_enfn');
15754var MAX_ITER = 20;
15755var pj_mlfn = require('../common/pj_mlfn');
15756var pj_inv_mlfn = require('../common/pj_inv_mlfn');
15757var HALF_PI = Math.PI/2;
15758var EPSLN = 1.0e-10;
15759var asinz = require('../common/asinz');
15760exports.init = function() {
15761  /* Place parameters in static storage for common use
15762    -------------------------------------------------*/
15763
15764
15765  if (!this.sphere) {
15766    this.en = pj_enfn(this.es);
15767  }
15768  else {
15769    this.n = 1;
15770    this.m = 0;
15771    this.es = 0;
15772    this.C_y = Math.sqrt((this.m + 1) / this.n);
15773    this.C_x = this.C_y / (this.m + 1);
15774  }
15775
15776};
15777
15778/* Sinusoidal forward equations--mapping lat,long to x,y
15779  -----------------------------------------------------*/
15780exports.forward = function(p) {
15781  var x, y;
15782  var lon = p.x;
15783  var lat = p.y;
15784  /* Forward equations
15785    -----------------*/
15786  lon = adjust_lon(lon - this.long0);
15787
15788  if (this.sphere) {
15789    if (!this.m) {
15790      lat = this.n !== 1 ? Math.asin(this.n * Math.sin(lat)) : lat;
15791    }
15792    else {
15793      var k = this.n * Math.sin(lat);
15794      for (var i = MAX_ITER; i; --i) {
15795        var V = (this.m * lat + Math.sin(lat) - k) / (this.m + Math.cos(lat));
15796        lat -= V;
15797        if (Math.abs(V) < EPSLN) {
15798          break;
15799        }
15800      }
15801    }
15802    x = this.a * this.C_x * lon * (this.m + Math.cos(lat));
15803    y = this.a * this.C_y * lat;
15804
15805  }
15806  else {
15807
15808    var s = Math.sin(lat);
15809    var c = Math.cos(lat);
15810    y = this.a * pj_mlfn(lat, s, c, this.en);
15811    x = this.a * lon * c / Math.sqrt(1 - this.es * s * s);
15812  }
15813
15814  p.x = x;
15815  p.y = y;
15816  return p;
15817};
15818
15819exports.inverse = function(p) {
15820  var lat, temp, lon, s;
15821
15822  p.x -= this.x0;
15823  lon = p.x / this.a;
15824  p.y -= this.y0;
15825  lat = p.y / this.a;
15826
15827  if (this.sphere) {
15828    lat /= this.C_y;
15829    lon = lon / (this.C_x * (this.m + Math.cos(lat)));
15830    if (this.m) {
15831      lat = asinz((this.m * lat + Math.sin(lat)) / this.n);
15832    }
15833    else if (this.n !== 1) {
15834      lat = asinz(Math.sin(lat) / this.n);
15835    }
15836    lon = adjust_lon(lon + this.long0);
15837    lat = adjust_lat(lat);
15838  }
15839  else {
15840    lat = pj_inv_mlfn(p.y / this.a, this.es, this.en);
15841    s = Math.abs(lat);
15842    if (s < HALF_PI) {
15843      s = Math.sin(lat);
15844      temp = this.long0 + p.x * Math.sqrt(1 - this.es * s * s) / (this.a * Math.cos(lat));
15845      //temp = this.long0 + p.x / (this.a * Math.cos(lat));
15846      lon = adjust_lon(temp);
15847    }
15848    else if ((s - EPSLN) < HALF_PI) {
15849      lon = this.long0;
15850    }
15851  }
15852  p.x = lon;
15853  p.y = lat;
15854  return p;
15855};
15856exports.names = ["Sinusoidal", "sinu"];
15857},{"../common/adjust_lat":67,"../common/adjust_lon":68,"../common/asinz":69,"../common/pj_enfn":80,"../common/pj_inv_mlfn":81,"../common/pj_mlfn":82}],123:[function(require,module,exports){
15858/*
15859  references:
15860    Formules et constantes pour le Calcul pour la
15861    projection cylindrique conforme à axe oblique et pour la transformation entre
15862    des systèmes de référence.
15863    http://www.swisstopo.admin.ch/internet/swisstopo/fr/home/topics/survey/sys/refsys/switzerland.parsysrelated1.31216.downloadList.77004.DownloadFile.tmp/swissprojectionfr.pdf
15864  */
15865exports.init = function() {
15866  var phy0 = this.lat0;
15867  this.lambda0 = this.long0;
15868  var sinPhy0 = Math.sin(phy0);
15869  var semiMajorAxis = this.a;
15870  var invF = this.rf;
15871  var flattening = 1 / invF;
15872  var e2 = 2 * flattening - Math.pow(flattening, 2);
15873  var e = this.e = Math.sqrt(e2);
15874  this.R = this.k0 * semiMajorAxis * Math.sqrt(1 - e2) / (1 - e2 * Math.pow(sinPhy0, 2));
15875  this.alpha = Math.sqrt(1 + e2 / (1 - e2) * Math.pow(Math.cos(phy0), 4));
15876  this.b0 = Math.asin(sinPhy0 / this.alpha);
15877  var k1 = Math.log(Math.tan(Math.PI / 4 + this.b0 / 2));
15878  var k2 = Math.log(Math.tan(Math.PI / 4 + phy0 / 2));
15879  var k3 = Math.log((1 + e * sinPhy0) / (1 - e * sinPhy0));
15880  this.K = k1 - this.alpha * k2 + this.alpha * e / 2 * k3;
15881};
15882
15883
15884exports.forward = function(p) {
15885  var Sa1 = Math.log(Math.tan(Math.PI / 4 - p.y / 2));
15886  var Sa2 = this.e / 2 * Math.log((1 + this.e * Math.sin(p.y)) / (1 - this.e * Math.sin(p.y)));
15887  var S = -this.alpha * (Sa1 + Sa2) + this.K;
15888
15889  // spheric latitude
15890  var b = 2 * (Math.atan(Math.exp(S)) - Math.PI / 4);
15891
15892  // spheric longitude
15893  var I = this.alpha * (p.x - this.lambda0);
15894
15895  // psoeudo equatorial rotation
15896  var rotI = Math.atan(Math.sin(I) / (Math.sin(this.b0) * Math.tan(b) + Math.cos(this.b0) * Math.cos(I)));
15897
15898  var rotB = Math.asin(Math.cos(this.b0) * Math.sin(b) - Math.sin(this.b0) * Math.cos(b) * Math.cos(I));
15899
15900  p.y = this.R / 2 * Math.log((1 + Math.sin(rotB)) / (1 - Math.sin(rotB))) + this.y0;
15901  p.x = this.R * rotI + this.x0;
15902  return p;
15903};
15904
15905exports.inverse = function(p) {
15906  var Y = p.x - this.x0;
15907  var X = p.y - this.y0;
15908
15909  var rotI = Y / this.R;
15910  var rotB = 2 * (Math.atan(Math.exp(X / this.R)) - Math.PI / 4);
15911
15912  var b = Math.asin(Math.cos(this.b0) * Math.sin(rotB) + Math.sin(this.b0) * Math.cos(rotB) * Math.cos(rotI));
15913  var I = Math.atan(Math.sin(rotI) / (Math.cos(this.b0) * Math.cos(rotI) - Math.sin(this.b0) * Math.tan(rotB)));
15914
15915  var lambda = this.lambda0 + I / this.alpha;
15916
15917  var S = 0;
15918  var phy = b;
15919  var prevPhy = -1000;
15920  var iteration = 0;
15921  while (Math.abs(phy - prevPhy) > 0.0000001) {
15922    if (++iteration > 20) {
15923      //...reportError("omercFwdInfinity");
15924      return;
15925    }
15926    //S = Math.log(Math.tan(Math.PI / 4 + phy / 2));
15927    S = 1 / this.alpha * (Math.log(Math.tan(Math.PI / 4 + b / 2)) - this.K) + this.e * Math.log(Math.tan(Math.PI / 4 + Math.asin(this.e * Math.sin(phy)) / 2));
15928    prevPhy = phy;
15929    phy = 2 * Math.atan(Math.exp(S)) - Math.PI / 2;
15930  }
15931
15932  p.x = lambda;
15933  p.y = phy;
15934  return p;
15935};
15936
15937exports.names = ["somerc"];
15938
15939},{}],124:[function(require,module,exports){
15940var HALF_PI = Math.PI/2;
15941var EPSLN = 1.0e-10;
15942var sign = require('../common/sign');
15943var msfnz = require('../common/msfnz');
15944var tsfnz = require('../common/tsfnz');
15945var phi2z = require('../common/phi2z');
15946var adjust_lon = require('../common/adjust_lon');
15947exports.ssfn_ = function(phit, sinphi, eccen) {
15948  sinphi *= eccen;
15949  return (Math.tan(0.5 * (HALF_PI + phit)) * Math.pow((1 - sinphi) / (1 + sinphi), 0.5 * eccen));
15950};
15951
15952exports.init = function() {
15953  this.coslat0 = Math.cos(this.lat0);
15954  this.sinlat0 = Math.sin(this.lat0);
15955  if (this.sphere) {
15956    if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) {
15957      this.k0 = 0.5 * (1 + sign(this.lat0) * Math.sin(this.lat_ts));
15958    }
15959  }
15960  else {
15961    if (Math.abs(this.coslat0) <= EPSLN) {
15962      if (this.lat0 > 0) {
15963        //North pole
15964        //trace('stere:north pole');
15965        this.con = 1;
15966      }
15967      else {
15968        //South pole
15969        //trace('stere:south pole');
15970        this.con = -1;
15971      }
15972    }
15973    this.cons = Math.sqrt(Math.pow(1 + this.e, 1 + this.e) * Math.pow(1 - this.e, 1 - this.e));
15974    if (this.k0 === 1 && !isNaN(this.lat_ts) && Math.abs(this.coslat0) <= EPSLN) {
15975      this.k0 = 0.5 * this.cons * msfnz(this.e, Math.sin(this.lat_ts), Math.cos(this.lat_ts)) / tsfnz(this.e, this.con * this.lat_ts, this.con * Math.sin(this.lat_ts));
15976    }
15977    this.ms1 = msfnz(this.e, this.sinlat0, this.coslat0);
15978    this.X0 = 2 * Math.atan(this.ssfn_(this.lat0, this.sinlat0, this.e)) - HALF_PI;
15979    this.cosX0 = Math.cos(this.X0);
15980    this.sinX0 = Math.sin(this.X0);
15981  }
15982};
15983
15984// Stereographic forward equations--mapping lat,long to x,y
15985exports.forward = function(p) {
15986  var lon = p.x;
15987  var lat = p.y;
15988  var sinlat = Math.sin(lat);
15989  var coslat = Math.cos(lat);
15990  var A, X, sinX, cosX, ts, rh;
15991  var dlon = adjust_lon(lon - this.long0);
15992
15993  if (Math.abs(Math.abs(lon - this.long0) - Math.PI) <= EPSLN && Math.abs(lat + this.lat0) <= EPSLN) {
15994    //case of the origine point
15995    //trace('stere:this is the origin point');
15996    p.x = NaN;
15997    p.y = NaN;
15998    return p;
15999  }
16000  if (this.sphere) {
16001    //trace('stere:sphere case');
16002    A = 2 * this.k0 / (1 + this.sinlat0 * sinlat + this.coslat0 * coslat * Math.cos(dlon));
16003    p.x = this.a * A * coslat * Math.sin(dlon) + this.x0;
16004    p.y = this.a * A * (this.coslat0 * sinlat - this.sinlat0 * coslat * Math.cos(dlon)) + this.y0;
16005    return p;
16006  }
16007  else {
16008    X = 2 * Math.atan(this.ssfn_(lat, sinlat, this.e)) - HALF_PI;
16009    cosX = Math.cos(X);
16010    sinX = Math.sin(X);
16011    if (Math.abs(this.coslat0) <= EPSLN) {
16012      ts = tsfnz(this.e, lat * this.con, this.con * sinlat);
16013      rh = 2 * this.a * this.k0 * ts / this.cons;
16014      p.x = this.x0 + rh * Math.sin(lon - this.long0);
16015      p.y = this.y0 - this.con * rh * Math.cos(lon - this.long0);
16016      //trace(p.toString());
16017      return p;
16018    }
16019    else if (Math.abs(this.sinlat0) < EPSLN) {
16020      //Eq
16021      //trace('stere:equateur');
16022      A = 2 * this.a * this.k0 / (1 + cosX * Math.cos(dlon));
16023      p.y = A * sinX;
16024    }
16025    else {
16026      //other case
16027      //trace('stere:normal case');
16028      A = 2 * this.a * this.k0 * this.ms1 / (this.cosX0 * (1 + this.sinX0 * sinX + this.cosX0 * cosX * Math.cos(dlon)));
16029      p.y = A * (this.cosX0 * sinX - this.sinX0 * cosX * Math.cos(dlon)) + this.y0;
16030    }
16031    p.x = A * cosX * Math.sin(dlon) + this.x0;
16032  }
16033  //trace(p.toString());
16034  return p;
16035};
16036
16037
16038//* Stereographic inverse equations--mapping x,y to lat/long
16039exports.inverse = function(p) {
16040  p.x -= this.x0;
16041  p.y -= this.y0;
16042  var lon, lat, ts, ce, Chi;
16043  var rh = Math.sqrt(p.x * p.x + p.y * p.y);
16044  if (this.sphere) {
16045    var c = 2 * Math.atan(rh / (0.5 * this.a * this.k0));
16046    lon = this.long0;
16047    lat = this.lat0;
16048    if (rh <= EPSLN) {
16049      p.x = lon;
16050      p.y = lat;
16051      return p;
16052    }
16053    lat = Math.asin(Math.cos(c) * this.sinlat0 + p.y * Math.sin(c) * this.coslat0 / rh);
16054    if (Math.abs(this.coslat0) < EPSLN) {
16055      if (this.lat0 > 0) {
16056        lon = adjust_lon(this.long0 + Math.atan2(p.x, - 1 * p.y));
16057      }
16058      else {
16059        lon = adjust_lon(this.long0 + Math.atan2(p.x, p.y));
16060      }
16061    }
16062    else {
16063      lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(c), rh * this.coslat0 * Math.cos(c) - p.y * this.sinlat0 * Math.sin(c)));
16064    }
16065    p.x = lon;
16066    p.y = lat;
16067    return p;
16068  }
16069  else {
16070    if (Math.abs(this.coslat0) <= EPSLN) {
16071      if (rh <= EPSLN) {
16072        lat = this.lat0;
16073        lon = this.long0;
16074        p.x = lon;
16075        p.y = lat;
16076        //trace(p.toString());
16077        return p;
16078      }
16079      p.x *= this.con;
16080      p.y *= this.con;
16081      ts = rh * this.cons / (2 * this.a * this.k0);
16082      lat = this.con * phi2z(this.e, ts);
16083      lon = this.con * adjust_lon(this.con * this.long0 + Math.atan2(p.x, - 1 * p.y));
16084    }
16085    else {
16086      ce = 2 * Math.atan(rh * this.cosX0 / (2 * this.a * this.k0 * this.ms1));
16087      lon = this.long0;
16088      if (rh <= EPSLN) {
16089        Chi = this.X0;
16090      }
16091      else {
16092        Chi = Math.asin(Math.cos(ce) * this.sinX0 + p.y * Math.sin(ce) * this.cosX0 / rh);
16093        lon = adjust_lon(this.long0 + Math.atan2(p.x * Math.sin(ce), rh * this.cosX0 * Math.cos(ce) - p.y * this.sinX0 * Math.sin(ce)));
16094      }
16095      lat = -1 * phi2z(this.e, Math.tan(0.5 * (HALF_PI + Chi)));
16096    }
16097  }
16098  p.x = lon;
16099  p.y = lat;
16100
16101  //trace(p.toString());
16102  return p;
16103
16104};
16105exports.names = ["stere", "Stereographic_South_Pole", "Polar Stereographic (variant B)"];
16106
16107},{"../common/adjust_lon":68,"../common/msfnz":78,"../common/phi2z":79,"../common/sign":84,"../common/tsfnz":87}],125:[function(require,module,exports){
16108var gauss = require('./gauss');
16109var adjust_lon = require('../common/adjust_lon');
16110exports.init = function() {
16111  gauss.init.apply(this);
16112  if (!this.rc) {
16113    return;
16114  }
16115  this.sinc0 = Math.sin(this.phic0);
16116  this.cosc0 = Math.cos(this.phic0);
16117  this.R2 = 2 * this.rc;
16118  if (!this.title) {
16119    this.title = "Oblique Stereographic Alternative";
16120  }
16121};
16122
16123exports.forward = function(p) {
16124  var sinc, cosc, cosl, k;
16125  p.x = adjust_lon(p.x - this.long0);
16126  gauss.forward.apply(this, [p]);
16127  sinc = Math.sin(p.y);
16128  cosc = Math.cos(p.y);
16129  cosl = Math.cos(p.x);
16130  k = this.k0 * this.R2 / (1 + this.sinc0 * sinc + this.cosc0 * cosc * cosl);
16131  p.x = k * cosc * Math.sin(p.x);
16132  p.y = k * (this.cosc0 * sinc - this.sinc0 * cosc * cosl);
16133  p.x = this.a * p.x + this.x0;
16134  p.y = this.a * p.y + this.y0;
16135  return p;
16136};
16137
16138exports.inverse = function(p) {
16139  var sinc, cosc, lon, lat, rho;
16140  p.x = (p.x - this.x0) / this.a;
16141  p.y = (p.y - this.y0) / this.a;
16142
16143  p.x /= this.k0;
16144  p.y /= this.k0;
16145  if ((rho = Math.sqrt(p.x * p.x + p.y * p.y))) {
16146    var c = 2 * Math.atan2(rho, this.R2);
16147    sinc = Math.sin(c);
16148    cosc = Math.cos(c);
16149    lat = Math.asin(cosc * this.sinc0 + p.y * sinc * this.cosc0 / rho);
16150    lon = Math.atan2(p.x * sinc, rho * this.cosc0 * cosc - p.y * this.sinc0 * sinc);
16151  }
16152  else {
16153    lat = this.phic0;
16154    lon = 0;
16155  }
16156
16157  p.x = lon;
16158  p.y = lat;
16159  gauss.inverse.apply(this, [p]);
16160  p.x = adjust_lon(p.x + this.long0);
16161  return p;
16162};
16163
16164exports.names = ["Stereographic_North_Pole", "Oblique_Stereographic", "Polar_Stereographic", "sterea","Oblique Stereographic Alternative"];
16165
16166},{"../common/adjust_lon":68,"./gauss":110}],126:[function(require,module,exports){
16167var e0fn = require('../common/e0fn');
16168var e1fn = require('../common/e1fn');
16169var e2fn = require('../common/e2fn');
16170var e3fn = require('../common/e3fn');
16171var mlfn = require('../common/mlfn');
16172var adjust_lon = require('../common/adjust_lon');
16173var HALF_PI = Math.PI/2;
16174var EPSLN = 1.0e-10;
16175var sign = require('../common/sign');
16176var asinz = require('../common/asinz');
16177
16178exports.init = function() {
16179  this.e0 = e0fn(this.es);
16180  this.e1 = e1fn(this.es);
16181  this.e2 = e2fn(this.es);
16182  this.e3 = e3fn(this.es);
16183  this.ml0 = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, this.lat0);
16184};
16185
16186/**
16187    Transverse Mercator Forward  - long/lat to x/y
16188    long/lat in radians
16189  */
16190exports.forward = function(p) {
16191  var lon = p.x;
16192  var lat = p.y;
16193
16194  var delta_lon = adjust_lon(lon - this.long0);
16195  var con;
16196  var x, y;
16197  var sin_phi = Math.sin(lat);
16198  var cos_phi = Math.cos(lat);
16199
16200  if (this.sphere) {
16201    var b = cos_phi * Math.sin(delta_lon);
16202    if ((Math.abs(Math.abs(b) - 1)) < 0.0000000001) {
16203      return (93);
16204    }
16205    else {
16206      x = 0.5 * this.a * this.k0 * Math.log((1 + b) / (1 - b));
16207      con = Math.acos(cos_phi * Math.cos(delta_lon) / Math.sqrt(1 - b * b));
16208      if (lat < 0) {
16209        con = -con;
16210      }
16211      y = this.a * this.k0 * (con - this.lat0);
16212    }
16213  }
16214  else {
16215    var al = cos_phi * delta_lon;
16216    var als = Math.pow(al, 2);
16217    var c = this.ep2 * Math.pow(cos_phi, 2);
16218    var tq = Math.tan(lat);
16219    var t = Math.pow(tq, 2);
16220    con = 1 - this.es * Math.pow(sin_phi, 2);
16221    var n = this.a / Math.sqrt(con);
16222    var ml = this.a * mlfn(this.e0, this.e1, this.e2, this.e3, lat);
16223
16224    x = this.k0 * n * al * (1 + als / 6 * (1 - t + c + als / 20 * (5 - 18 * t + Math.pow(t, 2) + 72 * c - 58 * this.ep2))) + this.x0;
16225    y = this.k0 * (ml - this.ml0 + n * tq * (als * (0.5 + als / 24 * (5 - t + 9 * c + 4 * Math.pow(c, 2) + als / 30 * (61 - 58 * t + Math.pow(t, 2) + 600 * c - 330 * this.ep2))))) + this.y0;
16226
16227  }
16228  p.x = x;
16229  p.y = y;
16230  return p;
16231};
16232
16233/**
16234    Transverse Mercator Inverse  -  x/y to long/lat
16235  */
16236exports.inverse = function(p) {
16237  var con, phi;
16238  var delta_phi;
16239  var i;
16240  var max_iter = 6;
16241  var lat, lon;
16242
16243  if (this.sphere) {
16244    var f = Math.exp(p.x / (this.a * this.k0));
16245    var g = 0.5 * (f - 1 / f);
16246    var temp = this.lat0 + p.y / (this.a * this.k0);
16247    var h = Math.cos(temp);
16248    con = Math.sqrt((1 - h * h) / (1 + g * g));
16249    lat = asinz(con);
16250    if (temp < 0) {
16251      lat = -lat;
16252    }
16253    if ((g === 0) && (h === 0)) {
16254      lon = this.long0;
16255    }
16256    else {
16257      lon = adjust_lon(Math.atan2(g, h) + this.long0);
16258    }
16259  }
16260  else { // ellipsoidal form
16261    var x = p.x - this.x0;
16262    var y = p.y - this.y0;
16263
16264    con = (this.ml0 + y / this.k0) / this.a;
16265    phi = con;
16266    for (i = 0; true; i++) {
16267      delta_phi = ((con + this.e1 * Math.sin(2 * phi) - this.e2 * Math.sin(4 * phi) + this.e3 * Math.sin(6 * phi)) / this.e0) - phi;
16268      phi += delta_phi;
16269      if (Math.abs(delta_phi) <= EPSLN) {
16270        break;
16271      }
16272      if (i >= max_iter) {
16273        return (95);
16274      }
16275    } // for()
16276    if (Math.abs(phi) < HALF_PI) {
16277      var sin_phi = Math.sin(phi);
16278      var cos_phi = Math.cos(phi);
16279      var tan_phi = Math.tan(phi);
16280      var c = this.ep2 * Math.pow(cos_phi, 2);
16281      var cs = Math.pow(c, 2);
16282      var t = Math.pow(tan_phi, 2);
16283      var ts = Math.pow(t, 2);
16284      con = 1 - this.es * Math.pow(sin_phi, 2);
16285      var n = this.a / Math.sqrt(con);
16286      var r = n * (1 - this.es) / con;
16287      var d = x / (n * this.k0);
16288      var ds = Math.pow(d, 2);
16289      lat = phi - (n * tan_phi * ds / r) * (0.5 - ds / 24 * (5 + 3 * t + 10 * c - 4 * cs - 9 * this.ep2 - ds / 30 * (61 + 90 * t + 298 * c + 45 * ts - 252 * this.ep2 - 3 * cs)));
16290      lon = adjust_lon(this.long0 + (d * (1 - ds / 6 * (1 + 2 * t + c - ds / 20 * (5 - 2 * c + 28 * t - 3 * cs + 8 * this.ep2 + 24 * ts))) / cos_phi));
16291    }
16292    else {
16293      lat = HALF_PI * sign(y);
16294      lon = this.long0;
16295    }
16296  }
16297  p.x = lon;
16298  p.y = lat;
16299  return p;
16300};
16301exports.names = ["Transverse_Mercator", "Transverse Mercator", "tmerc"];
16302
16303},{"../common/adjust_lon":68,"../common/asinz":69,"../common/e0fn":70,"../common/e1fn":71,"../common/e2fn":72,"../common/e3fn":73,"../common/mlfn":77,"../common/sign":84}],127:[function(require,module,exports){
16304var D2R = 0.01745329251994329577;
16305var tmerc = require('./tmerc');
16306exports.dependsOn = 'tmerc';
16307exports.init = function() {
16308  if (!this.zone) {
16309    return;
16310  }
16311  this.lat0 = 0;
16312  this.long0 = ((6 * Math.abs(this.zone)) - 183) * D2R;
16313  this.x0 = 500000;
16314  this.y0 = this.utmSouth ? 10000000 : 0;
16315  this.k0 = 0.9996;
16316
16317  tmerc.init.apply(this);
16318  this.forward = tmerc.forward;
16319  this.inverse = tmerc.inverse;
16320};
16321exports.names = ["Universal Transverse Mercator System", "utm"];
16322
16323},{"./tmerc":126}],128:[function(require,module,exports){
16324var adjust_lon = require('../common/adjust_lon');
16325var HALF_PI = Math.PI/2;
16326var EPSLN = 1.0e-10;
16327var asinz = require('../common/asinz');
16328/* Initialize the Van Der Grinten projection
16329  ----------------------------------------*/
16330exports.init = function() {
16331  //this.R = 6370997; //Radius of earth
16332  this.R = this.a;
16333};
16334
16335exports.forward = function(p) {
16336
16337  var lon = p.x;
16338  var lat = p.y;
16339
16340  /* Forward equations
16341    -----------------*/
16342  var dlon = adjust_lon(lon - this.long0);
16343  var x, y;
16344
16345  if (Math.abs(lat) <= EPSLN) {
16346    x = this.x0 + this.R * dlon;
16347    y = this.y0;
16348  }
16349  var theta = asinz(2 * Math.abs(lat / Math.PI));
16350  if ((Math.abs(dlon) <= EPSLN) || (Math.abs(Math.abs(lat) - HALF_PI) <= EPSLN)) {
16351    x = this.x0;
16352    if (lat >= 0) {
16353      y = this.y0 + Math.PI * this.R * Math.tan(0.5 * theta);
16354    }
16355    else {
16356      y = this.y0 + Math.PI * this.R * -Math.tan(0.5 * theta);
16357    }
16358    //  return(OK);
16359  }
16360  var al = 0.5 * Math.abs((Math.PI / dlon) - (dlon / Math.PI));
16361  var asq = al * al;
16362  var sinth = Math.sin(theta);
16363  var costh = Math.cos(theta);
16364
16365  var g = costh / (sinth + costh - 1);
16366  var gsq = g * g;
16367  var m = g * (2 / sinth - 1);
16368  var msq = m * m;
16369  var con = Math.PI * this.R * (al * (g - msq) + Math.sqrt(asq * (g - msq) * (g - msq) - (msq + asq) * (gsq - msq))) / (msq + asq);
16370  if (dlon < 0) {
16371    con = -con;
16372  }
16373  x = this.x0 + con;
16374  //con = Math.abs(con / (Math.PI * this.R));
16375  var q = asq + g;
16376  con = Math.PI * this.R * (m * q - al * Math.sqrt((msq + asq) * (asq + 1) - q * q)) / (msq + asq);
16377  if (lat >= 0) {
16378    //y = this.y0 + Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
16379    y = this.y0 + con;
16380  }
16381  else {
16382    //y = this.y0 - Math.PI * this.R * Math.sqrt(1 - con * con - 2 * al * con);
16383    y = this.y0 - con;
16384  }
16385  p.x = x;
16386  p.y = y;
16387  return p;
16388};
16389
16390/* Van Der Grinten inverse equations--mapping x,y to lat/long
16391  ---------------------------------------------------------*/
16392exports.inverse = function(p) {
16393  var lon, lat;
16394  var xx, yy, xys, c1, c2, c3;
16395  var a1;
16396  var m1;
16397  var con;
16398  var th1;
16399  var d;
16400
16401  /* inverse equations
16402    -----------------*/
16403  p.x -= this.x0;
16404  p.y -= this.y0;
16405  con = Math.PI * this.R;
16406  xx = p.x / con;
16407  yy = p.y / con;
16408  xys = xx * xx + yy * yy;
16409  c1 = -Math.abs(yy) * (1 + xys);
16410  c2 = c1 - 2 * yy * yy + xx * xx;
16411  c3 = -2 * c1 + 1 + 2 * yy * yy + xys * xys;
16412  d = yy * yy / c3 + (2 * c2 * c2 * c2 / c3 / c3 / c3 - 9 * c1 * c2 / c3 / c3) / 27;
16413  a1 = (c1 - c2 * c2 / 3 / c3) / c3;
16414  m1 = 2 * Math.sqrt(-a1 / 3);
16415  con = ((3 * d) / a1) / m1;
16416  if (Math.abs(con) > 1) {
16417    if (con >= 0) {
16418      con = 1;
16419    }
16420    else {
16421      con = -1;
16422    }
16423  }
16424  th1 = Math.acos(con) / 3;
16425  if (p.y >= 0) {
16426    lat = (-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
16427  }
16428  else {
16429    lat = -(-m1 * Math.cos(th1 + Math.PI / 3) - c2 / 3 / c3) * Math.PI;
16430  }
16431
16432  if (Math.abs(xx) < EPSLN) {
16433    lon = this.long0;
16434  }
16435  else {
16436    lon = adjust_lon(this.long0 + Math.PI * (xys - 1 + Math.sqrt(1 + 2 * (xx * xx - yy * yy) + xys * xys)) / 2 / xx);
16437  }
16438
16439  p.x = lon;
16440  p.y = lat;
16441  return p;
16442};
16443exports.names = ["Van_der_Grinten_I", "VanDerGrinten", "vandg"];
16444},{"../common/adjust_lon":68,"../common/asinz":69}],129:[function(require,module,exports){
16445var D2R = 0.01745329251994329577;
16446var R2D = 57.29577951308232088;
16447var PJD_3PARAM = 1;
16448var PJD_7PARAM = 2;
16449var datum_transform = require('./datum_transform');
16450var adjust_axis = require('./adjust_axis');
16451var proj = require('./Proj');
16452var toPoint = require('./common/toPoint');
16453module.exports = function transform(source, dest, point) {
16454  var wgs84;
16455  if (Array.isArray(point)) {
16456    point = toPoint(point);
16457  }
16458  function checkNotWGS(source, dest) {
16459    return ((source.datum.datum_type === PJD_3PARAM || source.datum.datum_type === PJD_7PARAM) && dest.datumCode !== "WGS84");
16460  }
16461
16462  // Workaround for datum shifts towgs84, if either source or destination projection is not wgs84
16463  if (source.datum && dest.datum && (checkNotWGS(source, dest) || checkNotWGS(dest, source))) {
16464    wgs84 = new proj('WGS84');
16465    transform(source, wgs84, point);
16466    source = wgs84;
16467  }
16468  // DGR, 2010/11/12
16469  if (source.axis !== "enu") {
16470    adjust_axis(source, false, point);
16471  }
16472  // Transform source points to long/lat, if they aren't already.
16473  if (source.projName === "longlat") {
16474    point.x *= D2R; // convert degrees to radians
16475    point.y *= D2R;
16476  }
16477  else {
16478    if (source.to_meter) {
16479      point.x *= source.to_meter;
16480      point.y *= source.to_meter;
16481    }
16482    source.inverse(point); // Convert Cartesian to longlat
16483  }
16484  // Adjust for the prime meridian if necessary
16485  if (source.from_greenwich) {
16486    point.x += source.from_greenwich;
16487  }
16488
16489  // Convert datums if needed, and if possible.
16490  point = datum_transform(source.datum, dest.datum, point);
16491
16492  // Adjust for the prime meridian if necessary
16493  if (dest.from_greenwich) {
16494    point.x -= dest.from_greenwich;
16495  }
16496
16497  if (dest.projName === "longlat") {
16498    // convert radians to decimal degrees
16499    point.x *= R2D;
16500    point.y *= R2D;
16501  }
16502  else { // else project
16503    dest.forward(point);
16504    if (dest.to_meter) {
16505      point.x /= dest.to_meter;
16506      point.y /= dest.to_meter;
16507    }
16508  }
16509
16510  // DGR, 2010/11/12
16511  if (dest.axis !== "enu") {
16512    adjust_axis(dest, true, point);
16513  }
16514
16515  return point;
16516};
16517},{"./Proj":65,"./adjust_axis":66,"./common/toPoint":86,"./datum_transform":94}],130:[function(require,module,exports){
16518var D2R = 0.01745329251994329577;
16519var extend = require('./extend');
16520
16521function mapit(obj, key, v) {
16522  obj[key] = v.map(function(aa) {
16523    var o = {};
16524    sExpr(aa, o);
16525    return o;
16526  }).reduce(function(a, b) {
16527    return extend(a, b);
16528  }, {});
16529}
16530
16531function sExpr(v, obj) {
16532  var key;
16533  if (!Array.isArray(v)) {
16534    obj[v] = true;
16535    return;
16536  }
16537  else {
16538    key = v.shift();
16539    if (key === 'PARAMETER') {
16540      key = v.shift();
16541    }
16542    if (v.length === 1) {
16543      if (Array.isArray(v[0])) {
16544        obj[key] = {};
16545        sExpr(v[0], obj[key]);
16546      }
16547      else {
16548        obj[key] = v[0];
16549      }
16550    }
16551    else if (!v.length) {
16552      obj[key] = true;
16553    }
16554    else if (key === 'TOWGS84') {
16555      obj[key] = v;
16556    }
16557    else {
16558      obj[key] = {};
16559      if (['UNIT', 'PRIMEM', 'VERT_DATUM'].indexOf(key) > -1) {
16560        obj[key] = {
16561          name: v[0].toLowerCase(),
16562          convert: v[1]
16563        };
16564        if (v.length === 3) {
16565          obj[key].auth = v[2];
16566        }
16567      }
16568      else if (key === 'SPHEROID') {
16569        obj[key] = {
16570          name: v[0],
16571          a: v[1],
16572          rf: v[2]
16573        };
16574        if (v.length === 4) {
16575          obj[key].auth = v[3];
16576        }
16577      }
16578      else if (['GEOGCS', 'GEOCCS', 'DATUM', 'VERT_CS', 'COMPD_CS', 'LOCAL_CS', 'FITTED_CS', 'LOCAL_DATUM'].indexOf(key) > -1) {
16579        v[0] = ['name', v[0]];
16580        mapit(obj, key, v);
16581      }
16582      else if (v.every(function(aa) {
16583        return Array.isArray(aa);
16584      })) {
16585        mapit(obj, key, v);
16586      }
16587      else {
16588        sExpr(v, obj[key]);
16589      }
16590    }
16591  }
16592}
16593
16594function rename(obj, params) {
16595  var outName = params[0];
16596  var inName = params[1];
16597  if (!(outName in obj) && (inName in obj)) {
16598    obj[outName] = obj[inName];
16599    if (params.length === 3) {
16600      obj[outName] = params[2](obj[outName]);
16601    }
16602  }
16603}
16604
16605function d2r(input) {
16606  return input * D2R;
16607}
16608
16609function cleanWKT(wkt) {
16610  if (wkt.type === 'GEOGCS') {
16611    wkt.projName = 'longlat';
16612  }
16613  else if (wkt.type === 'LOCAL_CS') {
16614    wkt.projName = 'identity';
16615    wkt.local = true;
16616  }
16617  else {
16618    if (typeof wkt.PROJECTION === "object") {
16619      wkt.projName = Object.keys(wkt.PROJECTION)[0];
16620    }
16621    else {
16622      wkt.projName = wkt.PROJECTION;
16623    }
16624  }
16625  if (wkt.UNIT) {
16626    wkt.units = wkt.UNIT.name.toLowerCase();
16627    if (wkt.units === 'metre') {
16628      wkt.units = 'meter';
16629    }
16630    if (wkt.UNIT.convert) {
16631      wkt.to_meter = parseFloat(wkt.UNIT.convert, 10);
16632    }
16633  }
16634
16635  if (wkt.GEOGCS) {
16636    //if(wkt.GEOGCS.PRIMEM&&wkt.GEOGCS.PRIMEM.convert){
16637    //  wkt.from_greenwich=wkt.GEOGCS.PRIMEM.convert*D2R;
16638    //}
16639    if (wkt.GEOGCS.DATUM) {
16640      wkt.datumCode = wkt.GEOGCS.DATUM.name.toLowerCase();
16641    }
16642    else {
16643      wkt.datumCode = wkt.GEOGCS.name.toLowerCase();
16644    }
16645    if (wkt.datumCode.slice(0, 2) === 'd_') {
16646      wkt.datumCode = wkt.datumCode.slice(2);
16647    }
16648    if (wkt.datumCode === 'new_zealand_geodetic_datum_1949' || wkt.datumCode === 'new_zealand_1949') {
16649      wkt.datumCode = 'nzgd49';
16650    }
16651    if (wkt.datumCode === "wgs_1984") {
16652      if (wkt.PROJECTION === 'Mercator_Auxiliary_Sphere') {
16653        wkt.sphere = true;
16654      }
16655      wkt.datumCode = 'wgs84';
16656    }
16657    if (wkt.datumCode.slice(-6) === '_ferro') {
16658      wkt.datumCode = wkt.datumCode.slice(0, - 6);
16659    }
16660    if (wkt.datumCode.slice(-8) === '_jakarta') {
16661      wkt.datumCode = wkt.datumCode.slice(0, - 8);
16662    }
16663    if (~wkt.datumCode.indexOf('belge')) {
16664      wkt.datumCode = "rnb72";
16665    }
16666    if (wkt.GEOGCS.DATUM && wkt.GEOGCS.DATUM.SPHEROID) {
16667      wkt.ellps = wkt.GEOGCS.DATUM.SPHEROID.name.replace('_19', '').replace(/[Cc]larke\_18/, 'clrk');
16668      if (wkt.ellps.toLowerCase().slice(0, 13) === "international") {
16669        wkt.ellps = 'intl';
16670      }
16671
16672      wkt.a = wkt.GEOGCS.DATUM.SPHEROID.a;
16673      wkt.rf = parseFloat(wkt.GEOGCS.DATUM.SPHEROID.rf, 10);
16674    }
16675    if (~wkt.datumCode.indexOf('osgb_1936')) {
16676      wkt.datumCode = "osgb36";
16677    }
16678  }
16679  if (wkt.b && !isFinite(wkt.b)) {
16680    wkt.b = wkt.a;
16681  }
16682
16683  function toMeter(input) {
16684    var ratio = wkt.to_meter || 1;
16685    return parseFloat(input, 10) * ratio;
16686  }
16687  var renamer = function(a) {
16688    return rename(wkt, a);
16689  };
16690  var list = [
16691    ['standard_parallel_1', 'Standard_Parallel_1'],
16692    ['standard_parallel_2', 'Standard_Parallel_2'],
16693    ['false_easting', 'False_Easting'],
16694    ['false_northing', 'False_Northing'],
16695    ['central_meridian', 'Central_Meridian'],
16696    ['latitude_of_origin', 'Latitude_Of_Origin'],
16697    ['latitude_of_origin', 'Central_Parallel'],
16698    ['scale_factor', 'Scale_Factor'],
16699    ['k0', 'scale_factor'],
16700    ['latitude_of_center', 'Latitude_of_center'],
16701    ['lat0', 'latitude_of_center', d2r],
16702    ['longitude_of_center', 'Longitude_Of_Center'],
16703    ['longc', 'longitude_of_center', d2r],
16704    ['x0', 'false_easting', toMeter],
16705    ['y0', 'false_northing', toMeter],
16706    ['long0', 'central_meridian', d2r],
16707    ['lat0', 'latitude_of_origin', d2r],
16708    ['lat0', 'standard_parallel_1', d2r],
16709    ['lat1', 'standard_parallel_1', d2r],
16710    ['lat2', 'standard_parallel_2', d2r],
16711    ['alpha', 'azimuth', d2r],
16712    ['srsCode', 'name']
16713  ];
16714  list.forEach(renamer);
16715  if (!wkt.long0 && wkt.longc && (wkt.projName === 'Albers_Conic_Equal_Area' || wkt.projName === "Lambert_Azimuthal_Equal_Area")) {
16716    wkt.long0 = wkt.longc;
16717  }
16718  if (!wkt.lat_ts && wkt.lat1 && (wkt.projName === 'Stereographic_South_Pole' || wkt.projName === 'Polar Stereographic (variant B)')) {
16719    wkt.lat0 = d2r(wkt.lat1 > 0 ? 90 : -90);
16720    wkt.lat_ts = wkt.lat1;
16721  }
16722}
16723module.exports = function(wkt, self) {
16724  var lisp = JSON.parse(("," + wkt).replace(/\s*\,\s*([A-Z_0-9]+?)(\[)/g, ',["$1",').slice(1).replace(/\s*\,\s*([A-Z_0-9]+?)\]/g, ',"$1"]').replace(/,\["VERTCS".+/,''));
16725  var type = lisp.shift();
16726  var name = lisp.shift();
16727  lisp.unshift(['name', name]);
16728  lisp.unshift(['type', type]);
16729  lisp.unshift('output');
16730  var obj = {};
16731  sExpr(lisp, obj);
16732  cleanWKT(obj.output);
16733  return extend(self, obj.output);
16734};
16735
16736},{"./extend":97}
16736],131:[function(require,module,exports){
16737
16738
16739
16740/**
16741 * UTM zones are grouped, and assigned to one of a group of 6
16742 * sets.
16743 *
16744 * {int} @private
16745 */
16746var NUM_100K_SETS = 6;
16747
16748/**
16749 * The column letters (for easting) of the lower left value, per
16750 * set.
16751 *
16752 * {string} @private
16753 */
16754var SET_ORIGIN_COLUMN_LETTERS = 'AJSAJS';
16755
16756/**
16757 * The row letters (for northing) of the lower left value, per
16758 * set.
16759 *
16760 * {string} @private
16761 */
16762var SET_ORIGIN_ROW_LETTERS = 'AFAFAF';
16763
16764var A = 65; // A
16765var I = 73; // I
16766var O = 79; // O
16767var V = 86; // V
16768var Z = 90; // Z
16769
16770/**
16771 * Conversion of lat/lon to MGRS.
16772 *
16773 * @param {object} ll Object literal with lat and lon properties on a
16774 *     WGS84 ellipsoid.
16775 * @param {int} accuracy Accuracy in digits (5 for 1 m, 4 for 10 m, 3 for
16776 *      100 m, 2 for 1000 m or 1 for 10000 m). Optional, default is 5.
16777 * @return {string} the MGRS string for the given location and accuracy.
16778 */
16779exports.forward = function(ll, accuracy) {
16780  accuracy = accuracy || 5; // default accuracy 1m
16781  return encode(LLtoUTM({
16782    lat: ll[1],
16783    lon: ll[0]
16784  }), accuracy);
16785};
16786
16787/**
16788 * Conversion of MGRS to lat/lon.
16789 *
16790 * @param {string} mgrs MGRS string.
16791 * @return {array} An array with left (longitude), bottom (latitude), right
16792 *     (longitude) and top (latitude) values in WGS84, representing the
16793 *     bounding box for the provided MGRS reference.
16794 */
16795exports.inverse = function(mgrs) {
16796  var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
16797  if (bbox.lat && bbox.lon) {
16798    return [bbox.lon, bbox.lat, bbox.lon, bbox.lat];
16799  }
16800  return [bbox.left, bbox.bottom, bbox.right, bbox.top];
16801};
16802
16803exports.toPoint = function(mgrs) {
16804  var bbox = UTMtoLL(decode(mgrs.toUpperCase()));
16805  if (bbox.lat && bbox.lon) {
16806    return [bbox.lon, bbox.lat];
16807  }
16808  return [(bbox.left + bbox.right) / 2, (bbox.top + bbox.bottom) / 2];
16809};
vendor: 13,875 bytes, lines 16810-17267
16810/**
16811 * Conversion from degrees to radians.
16812 *
16813 * @private
16814 * @param {number} deg the angle in degrees.
16815 * @return {number} the angle in radians.
16816 */
16817function degToRad(deg) {
16818  return (deg * (Math.PI / 180.0));
16819}
16820
16821/**
16822 * Conversion from radians to degrees.
16823 *
16824 * @private
16825 * @param {number} rad the angle in radians.
16826 * @return {number} the angle in degrees.
16827 */
16828function radToDeg(rad) {
16829  return (180.0 * (rad / Math.PI));
16830}
16831
16832/**
16833 * Converts a set of Longitude and Latitude co-ordinates to UTM
16834 * using the WGS84 ellipsoid.
16835 *
16836 * @private
16837 * @param {object} ll Object literal with lat and lon properties
16838 *     representing the WGS84 coordinate to be converted.
16839 * @return {object} Object literal containing the UTM value with easting,
16840 *     northing, zoneNumber and zoneLetter properties, and an optional
16841 *     accuracy property in digits. Returns null if the conversion failed.
16842 */
16843function LLtoUTM(ll) {
16844  var Lat = ll.lat;
16845  var Long = ll.lon;
16846  var a = 6378137.0; //ellip.radius;
16847  var eccSquared = 0.00669438; //ellip.eccsq;
16848  var k0 = 0.9996;
16849  var LongOrigin;
16850  var eccPrimeSquared;
16851  var N, T, C, A, M;
16852  var LatRad = degToRad(Lat);
16853  var LongRad = degToRad(Long);
16854  var LongOriginRad;
16855  var ZoneNumber;
16856  // (int)
16857  ZoneNumber = Math.floor((Long + 180) / 6) + 1;
16858
16859  //Make sure the longitude 180.00 is in Zone 60
16860  if (Long === 180) {
16861    ZoneNumber = 60;
16862  }
16863
16864  // Special zone for Norway
16865  if (Lat >= 56.0 && Lat < 64.0 && Long >= 3.0 && Long < 12.0) {
16866    ZoneNumber = 32;
16867  }
16868
16869  // Special zones for Svalbard
16870  if (Lat >= 72.0 && Lat < 84.0) {
16871    if (Long >= 0.0 && Long < 9.0) {
16872      ZoneNumber = 31;
16873    }
16874    else if (Long >= 9.0 && Long < 21.0) {
16875      ZoneNumber = 33;
16876    }
16877    else if (Long >= 21.0 && Long < 33.0) {
16878      ZoneNumber = 35;
16879    }
16880    else if (Long >= 33.0 && Long < 42.0) {
16881      ZoneNumber = 37;
16882    }
16883  }
16884
16885  LongOrigin = (ZoneNumber - 1) * 6 - 180 + 3; //+3 puts origin
16886  // in middle of
16887  // zone
16888  LongOriginRad = degToRad(LongOrigin);
16889
16890  eccPrimeSquared = (eccSquared) / (1 - eccSquared);
16891
16892  N = a / Math.sqrt(1 - eccSquared * Math.sin(LatRad) * Math.sin(LatRad));
16893  T = Math.tan(LatRad) * Math.tan(LatRad);
16894  C = eccPrimeSquared * Math.cos(LatRad) * Math.cos(LatRad);
16895  A = Math.cos(LatRad) * (LongRad - LongOriginRad);
16896
16897  M = a * ((1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256) * LatRad - (3 * eccSquared / 8 + 3 * eccSquared * eccSquared / 32 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(2 * LatRad) + (15 * eccSquared * eccSquared / 256 + 45 * eccSquared * eccSquared * eccSquared / 1024) * Math.sin(4 * LatRad) - (35 * eccSquared * eccSquared * eccSquared / 3072) * Math.sin(6 * LatRad));
16898
16899  var UTMEasting = (k0 * N * (A + (1 - T + C) * A * A * A / 6.0 + (5 - 18 * T + T * T + 72 * C - 58 * eccPrimeSquared) * A * A * A * A * A / 120.0) + 500000.0);
16900
16901  var UTMNorthing = (k0 * (M + N * Math.tan(LatRad) * (A * A / 2 + (5 - T + 9 * C + 4 * C * C) * A * A * A * A / 24.0 + (61 - 58 * T + T * T + 600 * C - 330 * eccPrimeSquared) * A * A * A * A * A * A / 720.0)));
16902  if (Lat < 0.0) {
16903    UTMNorthing += 10000000.0; //10000000 meter offset for
16904    // southern hemisphere
16905  }
16906
16907  return {
16908    northing: Math.round(UTMNorthing),
16909    easting: Math.round(UTMEasting),
16910    zoneNumber: ZoneNumber,
16911    zoneLetter: getLetterDesignator(Lat)
16912  };
16913}
16914
16915/**
16916 * Converts UTM coords to lat/long, using the WGS84 ellipsoid. This is a convenience
16917 * class where the Zone can be specified as a single string eg."60N" which
16918 * is then broken down into the ZoneNumber and ZoneLetter.
16919 *
16920 * @private
16921 * @param {object} utm An object literal with northing, easting, zoneNumber
16922 *     and zoneLetter properties. If an optional accuracy property is
16923 *     provided (in meters), a bounding box will be returned instead of
16924 *     latitude and longitude.
16925 * @return {object} An object literal containing either lat and lon values
16926 *     (if no accuracy was provided), or top, right, bottom and left values
16927 *     for the bounding box calculated according to the provided accuracy.
16928 *     Returns null if the conversion failed.
16929 */
16930function UTMtoLL(utm) {
16931
16932  var UTMNorthing = utm.northing;
16933  var UTMEasting = utm.easting;
16934  var zoneLetter = utm.zoneLetter;
16935  var zoneNumber = utm.zoneNumber;
16936  // check the ZoneNummber is valid
16937  if (zoneNumber < 0 || zoneNumber > 60) {
16938    return null;
16939  }
16940
16941  var k0 = 0.9996;
16942  var a = 6378137.0; //ellip.radius;
16943  var eccSquared = 0.00669438; //ellip.eccsq;
16944  var eccPrimeSquared;
16945  var e1 = (1 - Math.sqrt(1 - eccSquared)) / (1 + Math.sqrt(1 - eccSquared));
16946  var N1, T1, C1, R1, D, M;
16947  var LongOrigin;
16948  var mu, phi1Rad;
16949
16950  // remove 500,000 meter offset for longitude
16951  var x = UTMEasting - 500000.0;
16952  var y = UTMNorthing;
16953
16954  // We must know somehow if we are in the Northern or Southern
16955  // hemisphere, this is the only time we use the letter So even
16956  // if the Zone letter isn't exactly correct it should indicate
16957  // the hemisphere correctly
16958  if (zoneLetter < 'N') {
16959    y -= 10000000.0; // remove 10,000,000 meter offset used
16960    // for southern hemisphere
16961  }
16962
16963  // There are 60 zones with zone 1 being at West -180 to -174
16964  LongOrigin = (zoneNumber - 1) * 6 - 180 + 3; // +3 puts origin
16965  // in middle of
16966  // zone
16967
16968  eccPrimeSquared = (eccSquared) / (1 - eccSquared);
16969
16970  M = y / k0;
16971  mu = M / (a * (1 - eccSquared / 4 - 3 * eccSquared * eccSquared / 64 - 5 * eccSquared * eccSquared * eccSquared / 256));
16972
16973  phi1Rad = mu + (3 * e1 / 2 - 27 * e1 * e1 * e1 / 32) * Math.sin(2 * mu) + (21 * e1 * e1 / 16 - 55 * e1 * e1 * e1 * e1 / 32) * Math.sin(4 * mu) + (151 * e1 * e1 * e1 / 96) * Math.sin(6 * mu);
16974  // double phi1 = ProjMath.radToDeg(phi1Rad);
16975
16976  N1 = a / Math.sqrt(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad));
16977  T1 = Math.tan(phi1Rad) * Math.tan(phi1Rad);
16978  C1 = eccPrimeSquared * Math.cos(phi1Rad) * Math.cos(phi1Rad);
16979  R1 = a * (1 - eccSquared) / Math.pow(1 - eccSquared * Math.sin(phi1Rad) * Math.sin(phi1Rad), 1.5);
16980  D = x / (N1 * k0);
16981
16982  var lat = phi1Rad - (N1 * Math.tan(phi1Rad) / R1) * (D * D / 2 - (5 + 3 * T1 + 10 * C1 - 4 * C1 * C1 - 9 * eccPrimeSquared) * D * D * D * D / 24 + (61 + 90 * T1 + 298 * C1 + 45 * T1 * T1 - 252 * eccPrimeSquared - 3 * C1 * C1) * D * D * D * D * D * D / 720);
16983  lat = radToDeg(lat);
16984
16985  var lon = (D - (1 + 2 * T1 + C1) * D * D * D / 6 + (5 - 2 * C1 + 28 * T1 - 3 * C1 * C1 + 8 * eccPrimeSquared + 24 * T1 * T1) * D * D * D * D * D / 120) / Math.cos(phi1Rad);
16986  lon = LongOrigin + radToDeg(lon);
16987
16988  var result;
16989  if (utm.accuracy) {
16990    var topRight = UTMtoLL({
16991      northing: utm.northing + utm.accuracy,
16992      easting: utm.easting + utm.accuracy,
16993      zoneLetter: utm.zoneLetter,
16994      zoneNumber: utm.zoneNumber
16995    });
16996    result = {
16997      top: topRight.lat,
16998      right: topRight.lon,
16999      bottom: lat,
17000      left: lon
17001    };
17002  }
17003  else {
17004    result = {
17005      lat: lat,
17006      lon: lon
17007    };
17008  }
17009  return result;
17010}
17011
17012/**
17013 * Calculates the MGRS letter designator for the given latitude.
17014 *
17015 * @private
17016 * @param {number} lat The latitude in WGS84 to get the letter designator
17017 *     for.
17018 * @return {char} The letter designator.
17019 */
17020function getLetterDesignator(lat) {
17021  //This is here as an error flag to show that the Latitude is
17022  //outside MGRS limits
17023  var LetterDesignator = 'Z';
17024
17025  if ((84 >= lat) && (lat >= 72)) {
17026    LetterDesignator = 'X';
17027  }
17028  else if ((72 > lat) && (lat >= 64)) {
17029    LetterDesignator = 'W';
17030  }
17031  else if ((64 > lat) && (lat >= 56)) {
17032    LetterDesignator = 'V';
17033  }
17034  else if ((56 > lat) && (lat >= 48)) {
17035    LetterDesignator = 'U';
17036  }
17037  else if ((48 > lat) && (lat >= 40)) {
17038    LetterDesignator = 'T';
17039  }
17040  else if ((40 > lat) && (lat >= 32)) {
17041    LetterDesignator = 'S';
17042  }
17043  else if ((32 > lat) && (lat >= 24)) {
17044    LetterDesignator = 'R';
17045  }
17046  else if ((24 > lat) && (lat >= 16)) {
17047    LetterDesignator = 'Q';
17048  }
17049  else if ((16 > lat) && (lat >= 8)) {
17050    LetterDesignator = 'P';
17051  }
17052  else if ((8 > lat) && (lat >= 0)) {
17053    LetterDesignator = 'N';
17054  }
17055  else if ((0 > lat) && (lat >= -8)) {
17056    LetterDesignator = 'M';
17057  }
17058  else if ((-8 > lat) && (lat >= -16)) {
17059    LetterDesignator = 'L';
17060  }
17061  else if ((-16 > lat) && (lat >= -24)) {
17062    LetterDesignator = 'K';
17063  }
17064  else if ((-24 > lat) && (lat >= -32)) {
17065    LetterDesignator = 'J';
17066  }
17067  else if ((-32 > lat) && (lat >= -40)) {
17068    LetterDesignator = 'H';
17069  }
17070  else if ((-40 > lat) && (lat >= -48)) {
17071    LetterDesignator = 'G';
17072  }
17073  else if ((-48 > lat) && (lat >= -56)) {
17074    LetterDesignator = 'F';
17075  }
17076  else if ((-56 > lat) && (lat >= -64)) {
17077    LetterDesignator = 'E';
17078  }
17079  else if ((-64 > lat) && (lat >= -72)) {
17080    LetterDesignator = 'D';
17081  }
17082  else if ((-72 > lat) && (lat >= -80)) {
17083    LetterDesignator = 'C';
17084  }
17085  return LetterDesignator;
17086}
17087
17088/**
17089 * Encodes a UTM location as MGRS string.
17090 *
17091 * @private
17092 * @param {object} utm An object literal with easting, northing,
17093 *     zoneLetter, zoneNumber
17094 * @param {number} accuracy Accuracy in digits (1-5).
17095 * @return {string} MGRS string for the given UTM location.
17096 */
17097function encode(utm, accuracy) {
17098  // prepend with leading zeroes
17099  var seasting = "00000" + utm.easting,
17100    snorthing = "00000" + utm.northing;
17101
17102  return utm.zoneNumber + utm.zoneLetter + get100kID(utm.easting, utm.northing, utm.zoneNumber) + seasting.substr(seasting.length - 5, accuracy) + snorthing.substr(snorthing.length - 5, accuracy);
17103}
17104
17105/**
17106 * Get the two letter 100k designator for a given UTM easting,
17107 * northing and zone number value.
17108 *
17109 * @private
17110 * @param {number} easting
17111 * @param {number} northing
17112 * @param {number} zoneNumber
17113 * @return the two letter 100k designator for the given UTM location.
17114 */
17115function get100kID(easting, northing, zoneNumber) {
17116  var setParm = get100kSetForZone(zoneNumber);
17117  var setColumn = Math.floor(easting / 100000);
17118  var setRow = Math.floor(northing / 100000) % 20;
17119  return getLetter100kID(setColumn, setRow, setParm);
17120}
17121
17122/**
17123 * Given a UTM zone number, figure out the MGRS 100K set it is in.
17124 *
17125 * @private
17126 * @param {number} i An UTM zone number.
17127 * @return {number} the 100k set the UTM zone is in.
17128 */
17129function get100kSetForZone(i) {
17130  var setParm = i % NUM_100K_SETS;
17131  if (setParm === 0) {
17132    setParm = NUM_100K_SETS;
17133  }
17134
17135  return setParm;
17136}
17137
17138/**
17139 * Get the two-letter MGRS 100k designator given information
17140 * translated from the UTM northing, easting and zone number.
17141 *
17142 * @private
17143 * @param {number} column the column index as it relates to the MGRS
17144 *        100k set spreadsheet, created from the UTM easting.
17145 *        Values are 1-8.
17146 * @param {number} row the row index as it relates to the MGRS 100k set
17147 *        spreadsheet, created from the UTM northing value. Values
17148 *        are from 0-19.
17149 * @param {number} parm the set block, as it relates to the MGRS 100k set
17150 *        spreadsheet, created from the UTM zone. Values are from
17151 *        1-60.
17152 * @return two letter MGRS 100k code.
17153 */
17154function getLetter100kID(column, row, parm) {
17155  // colOrigin and rowOrigin are the letters at the origin of the set
17156  var index = parm - 1;
17157  var colOrigin = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(index);
17158  var rowOrigin = SET_ORIGIN_ROW_LETTERS.charCodeAt(index);
17159
17160  // colInt and rowInt are the letters to build to return
17161  var colInt = colOrigin + column - 1;
17162  var rowInt = rowOrigin + row;
17163  var rollover = false;
17164
17165  if (colInt > Z) {
17166    colInt = colInt - Z + A - 1;
17167    rollover = true;
17168  }
17169
17170  if (colInt === I || (colOrigin < I && colInt > I) || ((colInt > I || colOrigin < I) && rollover)) {
17171    colInt++;
17172  }
17173
17174  if (colInt === O || (colOrigin < O && colInt > O) || ((colInt > O || colOrigin < O) && rollover)) {
17175    colInt++;
17176
17177    if (colInt === I) {
17178      colInt++;
17179    }
17180  }
17181
17182  if (colInt > Z) {
17183    colInt = colInt - Z + A - 1;
17184  }
17185
17186  if (rowInt > V) {
17187    rowInt = rowInt - V + A - 1;
17188    rollover = true;
17189  }
17190  else {
17191    rollover = false;
17192  }
17193
17194  if (((rowInt === I) || ((rowOrigin < I) && (rowInt > I))) || (((rowInt > I) || (rowOrigin < I)) && rollover)) {
17195    rowInt++;
17196  }
17197
17198  if (((rowInt === O) || ((rowOrigin < O) && (rowInt > O))) || (((rowInt > O) || (rowOrigin < O)) && rollover)) {
17199    rowInt++;
17200
17201    if (rowInt === I) {
17202      rowInt++;
17203    }
17204  }
17205
17206  if (rowInt > V) {
17207    rowInt = rowInt - V + A - 1;
17208  }
17209
17210  var twoLetter = String.fromCharCode(colInt) + String.fromCharCode(rowInt);
17211  return twoLetter;
17212}
17213
17214/**
17215 * Decode the UTM parameters from a MGRS string.
17216 *
17217 * @private
17218 * @param {string} mgrsString an UPPERCASE coordinate string is expected.
17219 * @return {object} An object literal with easting, northing, zoneLetter,
17220 *     zoneNumber and accuracy (in meters) properties.
17221 */
17222function decode(mgrsString) {
17223
17224  if (mgrsString && mgrsString.length === 0) {
17225    throw ("MGRSPoint coverting from nothing");
17226  }
17227
17228  var length = mgrsString.length;
17229
17230  var hunK = null;
17231  var sb = "";
17232  var testChar;
17233  var i = 0;
17234
17235  // get Zone number
17236  while (!(/[A-Z]/).test(testChar = mgrsString.charAt(i))) {
17237    if (i >= 2) {
17238      throw ("MGRSPoint bad conversion from: " + mgrsString);
17239    }
17240    sb += testChar;
17241    i++;
17242  }
17243
17244  var zoneNumber = parseInt(sb, 10);
17245
17246  if (i === 0 || i + 3 > length) {
17247    // A good MGRS string has to be 4-5 digits long,
17248    // ##AAA/#AAA at least.
17249    throw ("MGRSPoint bad conversion from: " + mgrsString);
17250  }
17251
17252  var zoneLetter = mgrsString.charAt(i++);
17253
17254  // Should we check the zone letter here? Why not.
17255  if (zoneLetter <= 'A' || zoneLetter === 'B' || zoneLetter === 'Y' || zoneLetter >= 'Z' || zoneLetter === 'I' || zoneLetter === 'O') {
17256    throw ("MGRSPoint zone letter " + zoneLetter + " not handled: " + mgrsString);
17257  }
17258
17259  hunK = mgrsString.substring(i, i += 2);
17260
17261  var set = get100kSetForZone(zoneNumber);
17262
17263  var east100k = getEastingFromChar(hunK.charAt(0), set);
17264  var north100k = getNorthingFromChar(hunK.charAt(1), set);
17265
17266  // We have a bug where the northing may be 2000000 too low.
17267  // How
vendor: 1,787 bytes, lines 17268-17321
17268  // do we know when to roll over?
17269
17270  while (north100k < getMinNorthing(zoneLetter)) {
17271    north100k += 2000000;
17272  }
17273
17274  // calculate the char index for easting/northing separator
17275  var remainder = length - i;
17276
17277  if (remainder % 2 !== 0) {
17278    throw ("MGRSPoint has to have an even number \nof digits after the zone letter and two 100km letters - front \nhalf for easting meters, second half for \nnorthing meters" + mgrsString);
17279  }
17280
17281  var sep = remainder / 2;
17282
17283  var sepEasting = 0.0;
17284  var sepNorthing = 0.0;
17285  var accuracyBonus, sepEastingString, sepNorthingString, easting, northing;
17286  if (sep > 0) {
17287    accuracyBonus = 100000.0 / Math.pow(10, sep);
17288    sepEastingString = mgrsString.substring(i, i + sep);
17289    sepEasting = parseFloat(sepEastingString) * accuracyBonus;
17290    sepNorthingString = mgrsString.substring(i + sep);
17291    sepNorthing = parseFloat(sepNorthingString) * accuracyBonus;
17292  }
17293
17294  easting = sepEasting + east100k;
17295  northing = sepNorthing + north100k;
17296
17297  return {
17298    easting: easting,
17299    northing: northing,
17300    zoneLetter: zoneLetter,
17301    zoneNumber: zoneNumber,
17302    accuracy: accuracyBonus
17303  };
17304}
17305
17306/**
17307 * Given the first letter from a two-letter MGRS 100k zone, and given the
17308 * MGRS table set for the zone number, figure out the easting value that
17309 * should be added to the other, secondary easting value.
17310 *
17311 * @private
17312 * @param {char} e The first letter from a two-letter MGRS 100´k zone.
17313 * @param {number} set The MGRS table set for the zone number.
17314 * @return {number} The easting value for the given letter and set.
17315 */
17316function getEastingFromChar(e, set) {
17317  // colOrigin is the letter at the origin of the set for the
17318  // column
17319  var curCol = SET_ORIGIN_COLUMN_LETTERS.charCodeAt(set - 1);
17320  var eastingValue = 100000.0;
17321  var rewindMarker = false;
vendor: 3,322 bytes, lines 17322-17469
17322
17323  while (curCol !== e.charCodeAt(0)) {
17324    curCol++;
17325    if (curCol === I) {
17326      curCol++;
17327    }
17328    if (curCol === O) {
17329      curCol++;
17330    }
17331    if (curCol > Z) {
17332      if (rewindMarker) {
17333        throw ("Bad character: " + e);
17334      }
17335      curCol = A;
17336      rewindMarker = true;
17337    }
17338    eastingValue += 100000.0;
17339  }
17340
17341  return eastingValue;
17342}
17343
17344/**
17345 * Given the second letter from a two-letter MGRS 100k zone, and given the
17346 * MGRS table set for the zone number, figure out the northing value that
17347 * should be added to the other, secondary northing value. You have to
17348 * remember that Northings are determined from the equator, and the vertical
17349 * cycle of letters mean a 2000000 additional northing meters. This happens
17350 * approx. every 18 degrees of latitude. This method does *NOT* count any
17351 * additional northings. You have to figure out how many 2000000 meters need
17352 * to be added for the zone letter of the MGRS coordinate.
17353 *
17354 * @private
17355 * @param {char} n Second letter of the MGRS 100k zone
17356 * @param {number} set The MGRS table set number, which is dependent on the
17357 *     UTM zone number.
17358 * @return {number} The northing value for the given letter and set.
17359 */
17360function getNorthingFromChar(n, set) {
17361
17362  if (n > 'V') {
17363    throw ("MGRSPoint given invalid Northing " + n);
17364  }
17365
17366  // rowOrigin is the letter at the origin of the set for the
17367  // column
17368  var curRow = SET_ORIGIN_ROW_LETTERS.charCodeAt(set - 1);
17369  var northingValue = 0.0;
17370  var rewindMarker = false;
17371
17372  while (curRow !== n.charCodeAt(0)) {
17373    curRow++;
17374    if (curRow === I) {
17375      curRow++;
17376    }
17377    if (curRow === O) {
17378      curRow++;
17379    }
17380    // fixing a bug making whole application hang in this loop
17381    // when 'n' is a wrong character
17382    if (curRow > V) {
17383      if (rewindMarker) { // making sure that this loop ends
17384        throw ("Bad character: " + n);
17385      }
17386      curRow = A;
17387      rewindMarker = true;
17388    }
17389    northingValue += 100000.0;
17390  }
17391
17392  return northingValue;
17393}
17394
17395/**
17396 * The function getMinNorthing returns the minimum northing value of a MGRS
17397 * zone.
17398 *
17399 * Ported from Geotrans' c Lattitude_Band_Value structure table.
17400 *
17401 * @private
17402 * @param {char} zoneLetter The MGRS zone to get the min northing for.
17403 * @return {number}
17404 */
17405function getMinNorthing(zoneLetter) {
17406  var northing;
17407  switch (zoneLetter) {
17408  case 'C':
17409    northing = 1100000.0;
17410    break;
17411  case 'D':
17412    northing = 2000000.0;
17413    break;
17414  case 'E':
17415    northing = 2800000.0;
17416    break;
17417  case 'F':
17418    northing = 3700000.0;
17419    break;
17420  case 'G':
17421    northing = 4600000.0;
17422    break;
17423  case 'H':
17424    northing = 5500000.0;
17425    break;
17426  case 'J':
17427    northing = 6400000.0;
17428    break;
17429  case 'K':
17430    northing = 7300000.0;
17431    break;
17432  case 'L':
17433    northing = 8200000.0;
17434    break;
17435  case 'M':
17436    northing = 9100000.0;
17437    break;
17438  case 'N':
17439    northing = 0.0;
17440    break;
17441  case 'P':
17442    northing = 800000.0;
17443    break;
17444  case 'Q':
17445    northing = 1700000.0;
17446    break;
17447  case 'R':
17448    northing = 2600000.0;
17449    break;
17450  case 'S':
17451    northing = 3500000.0;
17452    break;
17453  case 'T':
17454    northing = 4400000.0;
17455    break;
17456  case 'U':
17457    northing = 5300000.0;
17458    break;
17459  case 'V':
17460    northing = 6200000.0;
17461    break;
17462  case 'W':
17463    northing = 7000000.0;
17464    break;
17465  case 'X':
17466    northing = 7900000.0;
17467    break;
17468  default:
17469    northing = -1
17469.0;
17470  }
17471  if (northing >= 0.0) {
17472    return northing;
17473  }
17474  else {
17475    throw ("Invalid zone letter: " + zoneLetter);
17476  }
17477
17478}
17479
17480},{}],132:[function(require,module,exports){
17481module.exports={
17482  "name": "proj4",
17483  "version": "2.3.7",
17484  "description": "Proj4js is a JavaScript library to transform point coordinates from one coordinate system to another, including datum transformations.",
17485  "main": "lib/index.js",
17486  "directories": {
17487    "test": "test",
17488    "doc": "docs"
17489  },
17490  "scripts": {
17491    "test": "./node_modules/istanbul/lib/cli.js test ./node_modules/mocha/bin/_mocha test/test.js"
17492  },
17493  "repository": {
17494    "type": "git",
17495    "url": "git://github.com/proj4js/proj4js.git"
17496  },
17497  "author": "",
17498  "license": "MIT",
17499  "jam": {
17500    "main": "dist/proj4.js",
17501    "include": [
17502      "dist/proj4.js",
17503      "README.md",
17504      "AUTHORS",
17505      "LICENSE.md"
17506    ]
17507  },
17508  "devDependencies": {
17509    "grunt-cli": "~0.1.13",
17510    "grunt": "~0.4.2",
17511    "grunt-contrib-connect": "~0.6.0",
17512    "grunt-contrib-jshint": "~0.8.0",
17513    "chai": "~1.8.1",
17514    "mocha": "~1.17.1",
17515    "grunt-mocha-phantomjs": "~0.4.0",
17516    "browserify": "~3.24.5",
17517    "grunt-browserify": "~1.3.0",
17518    "grunt-contrib-uglify": "~0.3.2",
17519    "curl": "git://github.com/cujojs/curl.git",
17520    "istanbul": "~0.2.4",
17521    "tin": "~0.4.0"
17522  },
17523  "dependencies": {
17524    "mgrs": "~0.0.2"
17525  },
17526  "contributors": [
17527    {
17528      "name": "Mike Adair",
17529      "email": "[email protected]"
17530    },
17531    {
17532      "name": "Richard Greenwood",
17533      "email": "[email protected]"
17534    },
17535    {
17536      "name": "Calvin Metcalf",
17537      "email": "[email protected]"
17538    },
17539    {
17540      "name": "Richard Marsden",
17541      "url": "http://www.winwaed.com"
17542    },
17543    {
17544      "name": "T. Mittan"
17545    },
17546    {
17547      "name": "D. Steinwand"
17548    },
17549    {
17550      "name": "S. Nelson"
17551    }
17552  ],
17553  "gitHead": "52b3a4f6bf8b609251d06f1f7ddd29d7074f3ce4",
17554  "bugs": {
17555    "url": "https://github.com/proj4js/proj4js/issues"
17556  },
17557  "homepage": "https://github.com/proj4js/proj4js#readme",
17558  "_id": "[email protected]",
17559  "_shasum": "248a30b2dc346dd1896dc5526c1a5e6b546f334a",
17560  "_from": "proj4@>=2.1.0 <3.0.0",
17561  "_npmVersion": "2.11.2",
17562  "_nodeVersion": "0.12.5",
17563  "_npmUser": {
17564    "name": "ahocevar",
17565    "email": "[email protected]"
17566  },
17567  "maintainers": [
17568    {
17569      "name": "cwmma",
17570      "email": "[email protected]"
17571    },
17572    {
17573      "name": "ahocevar",
17574      "email": "[email protected]"
17575    }
17576  ],
17577  "dist": {
17578    "shasum": "248a30b2dc346dd1896dc5526c1a5e6b546f334a",
17579    "tarball": "http://registry.npmjs.org/proj4/-/proj4-2.3.7.tgz"
17580  },
17581  "_resolved": "https://registry.npmjs.org/proj4/-/proj4-2.3.7.tgz"
17582}
17583
17584},{}],133:[function(require,module,exports){
17585(function (Buffer){
17586'use strict';
17587var proj4 = require('proj4');
17588var unzip = require('./unzip');
17589var binaryAjax = require('./binaryajax');
17590var parseShp = require('./parseShp');
17591var toArrayBuffer = require('./toArrayBuffer');
17592var parseDbf = require('parsedbf');
17593var Promise = require('lie');
17594var Cache = require('lru-cache');
17595var cache = new Cache({
17596	max: 20
17597});
17598function shp(base, whiteList) {
17599	if (typeof base === 'string' && cache.has(base)) {
17600		return Promise.resolve(cache.get(base));
17601	}
17602	return shp.getShapefile(base, whiteList).then(function (resp) {
17603		if (typeof base === 'string') {
17604			cache.set(base, resp);
17605		}
17606		return resp;
17607	});
17608}
17609shp.combine = function(arr) {
17610	var out = {};
17611	out.type = 'FeatureCollection';
17612	out.features = [];
17613	var i = 0;
17614	var len = arr[0].length;
17615	while (i < len) {
17616		out.features.push({
17617			'type': 'Feature',
17618			'geometry': arr[0][i],
17619			'properties': arr[1][i]
17620		});
17621		i++;
17622	}
17623	return out;
17624};
17625shp.parseZip = function(buffer, whiteList) {
17626	var key;
17627	var zip = unzip(buffer);
17628	var names = [];
17629	whiteList = whiteList || [];
17630	for (key in zip) {
17631		if (key.indexOf('__MACOSX') !== -1) {
17632			continue;
17633		}
17634		if (key.slice(-3).toLowerCase() === 'shp') {
17635			names.push(key.slice(0, - 4));
17636		}
17637		else if (key.slice(-3).toLowerCase() === 'dbf') {
17638			zip[key.slice(0, -3) + key.slice(-3).toLowerCase()] = parseDbf(zip[key]);
17639		}
17640		else if (key.slice(-3).toLowerCase() === 'prj') {
17641			zip[key.slice(0, -3) + key.slice(-3).toLowerCase()] = proj4(zip[key]);
17642		}
17643		else if (key.slice(-4).toLowerCase() === 'json' || whiteList.indexOf(key.split('.').pop()) > -1) {
17644			names.push(key.slice(0, -3) + key.slice(-3).toLowerCase());
17645		}
17646	}
17647	if (!names.length) {
17648		throw new Error('no layers founds');
17649	}
17650	var geojson = names.map(function(name) {
17651		var parsed;
17652		if (name.slice(-4).toLowerCase() === 'json') {
17653			parsed = JSON.parse(zip[name]);
17654			parsed.fileName = name.slice(0, name.lastIndexOf('.'));
17655		}
17656		else if (whiteList.indexOf(name.slice(name.lastIndexOf('.') + 1)) > -1) {
17657			parsed = zip[name];
17658			parsed.fileName = name;
17659		}
17660		else {
17661			parsed = shp.combine([parseShp(zip[name + '.shp'], zip[name + '.prj']), zip[name + '.dbf']]);
17662			parsed.fileName = name;
17663		}
17664		return parsed;
17665	});
17666	if (geojson.length === 1) {
17667		return geojson[0];
17668	}
17669	else {
17670		return geojson;
17671	}
17672};
17673
17674function getZip(base, whiteList) {
17675	return binaryAjax(base).then(function(a) {
17676		return shp.parseZip(a, whiteList);
17677	});
17678}
17679shp.getShapefile = function(base, whiteList) {
17680	if (typeof base === 'string') {
17681		if (base.slice(-4) === '.zip') {
17682			return getZip(base, whiteList);
17683		}
17684		else {
17685			return Promise.all([
17686				Promise.all([
17687					binaryAjax(base + '.shp'),
17688					binaryAjax(base + '.prj')
17689				]).then(function(args) {
17690					return parseShp(args[0], args[1] ? proj4(args[1]) : false);
17691				}),
17692				binaryAjax(base + '.dbf').then(parseDbf)
17693			]).then(shp.combine);
17694		}
17695	}
17696	else {
17697		return new Promise(function(resolve) {
17698			resolve(shp.parseZip(base));
17699		});
17700	}
17701};
17702shp.parseShp = function (shp, prj) {
17703	if (Buffer.isBuffer(shp)) {
17704		shp = toArrayBuffer(shp);
17705	}
17706	if (Buffer.isBuffer(prj)) {
17707		prj = prj.toString();
17708	}
17709	if (typeof prj === 'string') {
17710		prj = proj4(prj);
17711		return parseShp(shp, prj);
17712	} else {
17713		return parseShp(shp);
17714	}
17715};
17716shp.parseDbf = function (dbf) {
17717	if (Buffer.isBuffer(dbf)) {
17718		dbf = toArrayBuffer(dbf);
17719	}
17720	return parseDbf(dbf);
17721};
17722module.exports = shp;
17723
17724}).call(this,require("buffer").Buffer)
17725},{"./binaryajax":1,"./parseShp":2,"./toArrayBuffer":3,"./unzip":4,"buffer":5,"lie":51,"lru-cache":62,"parsedbf":63,"proj4":100}]},{},[133])(133)
17726});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.