{"version":3,"file":"nmr-parser.js","sources":["../src/constantTables.js","../src/formatDependentVariable.js","../src/formatLinearDimension.js","../node_modules/iobuffer/lib-esm/text-encoding-polyfill.js","../node_modules/iobuffer/lib-esm/utf8.browser.js","../node_modules/iobuffer/lib-esm/IOBuffer.js","../node_modules/jeolconverter/src/conversionTables.js","../node_modules/jeolconverter/src/utils.js","../node_modules/jeolconverter/src/parseJEOL.js","../src/utils/toKeyValue.js","../src/fromJEOL.js","../node_modules/jcampconverter/src/complexChromatogram.js","../node_modules/jcampconverter/src/convertToFloatArray.js","../node_modules/jcampconverter/src/parse/fastParseXYData.js","../node_modules/jcampconverter/src/parse/parsePeakTable.js","../node_modules/jcampconverter/src/parse/parseXYA.js","../node_modules/is-any-array/src/index.js","../node_modules/median-quickselect/lib/median-quickselect.min.js","../node_modules/ml-array-median/lib-es6/index.js","../node_modules/jcampconverter/src/2d/convertTo3DZ.js","../node_modules/jcampconverter/src/2d/generateContourLines.js","../node_modules/jcampconverter/src/2d/add2D.js","../node_modules/jcampconverter/src/profiling.js","../node_modules/jcampconverter/src/simpleChromatogram.js","../node_modules/jcampconverter/src/postProcessing.js","../node_modules/jcampconverter/src/prepareSpectrum.js","../node_modules/jcampconverter/src/convert.js","../node_modules/jszip/dist/jszip.js","../node_modules/brukerconverter/src/generateContourLines.js","../node_modules/brukerconverter/src/convertTo3DZ.js","../node_modules/brukerconverter/src/index.js","../src/utils/getDigitalFilterParameters.js","../src/utils/getNucleusFrom2DExperiment.js","../src/utils/getSpectrumType.js","../src/utils/getInfoFromBruker.js","../src/fromBruker.js","../src/utils/getInfoFromJCAMP.js","../src/fromJCAMP.js"],"sourcesContent":["/**\n * a number that correspond to a type of numeric\n * @typedef {number} numericType\n * @const\n */\nexport const numericTypeTable = {\n 0: 'uint8',\n 1: 'uint16',\n 2: 'uint32',\n 3: 'uint64',\n 4: 'int8',\n 5: 'int16',\n 6: 'int32',\n 7: 'int64',\n 8: 'float32',\n 9: 'float64',\n 10: 'complex64',\n 11: 'complex128',\n};\n\n/**\n * a number that corresponds to a type of quantity\n * @typedef {number} quantityType\n * @const\n */\nexport const quantityTypeTable = {\n 0: 'scalar',\n 1: 'vector',\n 2: 'matrix',\n 3: 'symetricMatrix',\n 4: 'pixel',\n};\n","import { numericTypeTable, quantityTypeTable } from './constantTables';\n/**\n * a class for dependent variable\n * @param {object || array} data - the dependent variable\n * @param {numericType} numericType - a number that correspond to a type of numeric used to store the components\n * @param {object} [options] - an object with options (name, unit, quantityName, componentLabels, sparseSampling, application, description)\n * @param {string} [options.name] - a name of the dependent variable\n * @param {string} [options.unit] - the unit of the dependent variable\n * @param {string} [options.quantityName] - a name of the quantity\n * @param {array} [options.componentLabels] - an array of labels for each component of the dependent variable\n * @return {object} - an dependent variable\n */\nexport function formatDependentVariable(data, numericType, options = {}) {\n let {\n quantityType = 0,\n encoding = 'none',\n name = '',\n unit = '',\n quantityName = '',\n componentLabels = [],\n sparseSampling = {},\n from = 0,\n to = -1,\n } = options;\n\n let components;\n if (Array.isArray(data)) {\n throw new Error('not yet implemented');\n } else if (Object.keys(data).length === 2) {\n components = fromReIm(data, from, to);\n }\n\n if (componentLabels.length === 0) {\n componentLabels = components.componentLabels;\n }\n\n return {\n type: 'internal',\n quantityType: quantityTypeTable[quantityType],\n numericType: numericTypeTable[numericType],\n encoding,\n name,\n unit,\n quantityName,\n componentLabels,\n sparseSampling,\n description: options.description || '',\n application: options.application || '',\n components: components.components,\n dataLength: components.dataLength,\n };\n}\n\n/**\n * import object {re:[], im:[]} to component\n * @param {object} reIm - a reIm object to import\n * @param {number} from - lower limit\n * @param {number} to - upper limit\n * @return {array} - components\n */\nfunction fromReIm(reIm, from, to) {\n let dataLength = [];\n let componentLabels = [];\n let components = [];\n if (Array.isArray(reIm.re) & Array.isArray(reIm.im)) {\n if (typeof reIm.re[0] === 'number') {\n // if 1D\n dataLength[0] = setLengthComplex(from[0], to[0], reIm.re.length);\n let component = new Float64Array(dataLength[0]);\n for (let i = 0; i < dataLength[0]; i += 2) {\n let idx = i + from[0] * 2;\n component[i] = reIm.re[idx / 2];\n component[i + 1] = reIm.im[idx / 2];\n }\n components.push(component);\n componentLabels.push('complex');\n } else if (Array.isArray(reIm.re[0])) {\n // if 2D\n dataLength[0] = setLength(from[1], to[1], reIm.re.length);\n dataLength[1] = setLengthComplex(from[0], to[0], reIm.re[0].length);\n\n for (let j = 0; j < dataLength[0]; j++) {\n let component = new Float64Array(dataLength[1]);\n for (let i = 0; i < dataLength[1]; i += 2) {\n let idx = i + from[0] * 2;\n component[i] = reIm.re[j][idx / 2];\n component[i + 1] = reIm.im[j][idx / 2];\n }\n components.push(component);\n }\n } else {\n throw new Error('check your object');\n }\n } else if (Array.isArray(reIm.re.re)) {\n dataLength[0] = reIm.re.re.length * 2;\n let re = fromReIm(reIm.re, from, to).components;\n let im = fromReIm(reIm.im, from, to).components;\n for (let j = 0; j < dataLength[0] / 2; j++) {\n components.push(re[j]);\n components.push(im[j]);\n }\n } else {\n throw new Error('check the dimension or the type of data in your array');\n }\n\n return {\n dataLength,\n componentLabels,\n components,\n };\n}\n\nfunction setLength(from, to, length) {\n if (to - from + 1 < length) {\n return to - from + 1;\n } else {\n return length;\n }\n}\n\nfunction setLengthComplex(from, to, length) {\n if (to - from + 1 < length) {\n return (to - from + 1) * 2;\n } else {\n return length * 2;\n }\n}\n\n// /**\n// * add component to components from 1D array.\n// * @param {array} array - a 1D or 2D array to import\n// * @return {Float64Array} - component\n// */\n// function add1DArray(array) {\n// let component;\n// component = new Float64Array(array.length);\n// for (let i = 0; i < array.length; i++) {\n// component[i] = array[i];\n// }\n// return component;\n// }\n\n// /**\n// * import component to InternalDEPENDENTVAR class object from 1D or 2D array.\n// * @param {array} array - a 1D or 2D array to import\n// */\n// function fromArray(array) {\n// this.dataLength[0] = array.length;\n// if (typeof array[0] === 'number') {\n// this.components = [this.add1DArray(array)];\n// } else if (Array.isArray(array[0])) {\n// this.dataLength[1] = array[0].length;\n// for (let j = 0; j < this.dataLength[1]; j++) {\n// this.components.push(this.add1DArray(array[j]));\n// }\n// } else {\n// throw new Error('check the dimension or the type of data in your array');\n// }\n// return this;\n// }\n","/**\n *\n * @param {*} label\n * @param {*} count\n * @param {*} increment\n * @param {*} options\n */\nexport function formatLinearDimension(label, count, increment, options = {}) {\n return {\n label: String(label),\n count: Number(count),\n increment: increment,\n type: 'linear',\n description: String(options.description) || '',\n application: options.application || {},\n coordinatesOffset: options.coordinatesOffset || 0,\n originOffset: options.originOffset || 0,\n quantityName: String(options.quantityName) || '',\n reciprocal: options.reciprocal || {},\n period: options.period || 0,\n complexFFT: options.complexFFT || false,\n };\n}\n","\"use strict\";\r\n/*\r\n * Copyright 2017 Sam Thorogood. All rights reserved.\r\n *\r\n * Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\r\n * use this file except in compliance with the License. You may obtain a copy of\r\n * the License at\r\n *\r\n * http://www.apache.org/licenses/LICENSE-2.0\r\n *\r\n * Unless required by applicable law or agreed to in writing, software\r\n * distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\r\n * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\r\n * License for the specific language governing permissions and limitations under\r\n * the License.\r\n */\r\n(function (scope) {\r\n 'use strict';\r\n // fail early\r\n if (scope['TextEncoder'] && scope['TextDecoder']) {\r\n return false;\r\n }\r\n /**\r\n * @constructor\r\n * @param {string=} utfLabel\r\n */\r\n function FastTextEncoder(utfLabel = 'utf-8') {\r\n if (utfLabel !== 'utf-8') {\r\n throw new RangeError(`Failed to construct 'TextEncoder': The encoding label provided ('${utfLabel}') is invalid.`);\r\n }\r\n }\r\n Object.defineProperty(FastTextEncoder.prototype, 'encoding', {\r\n value: 'utf-8',\r\n });\r\n /**\r\n * @param {string} string\r\n * @param {{stream: boolean}=} options\r\n * @return {!Uint8Array}\r\n */\r\n FastTextEncoder.prototype.encode = function (string, options = { stream: false }) {\r\n if (options.stream) {\r\n throw new Error(`Failed to encode: the 'stream' option is unsupported.`);\r\n }\r\n let pos = 0;\r\n const len = string.length;\r\n const out = [];\r\n let at = 0; // output position\r\n let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size\r\n let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset\r\n while (pos < len) {\r\n let value = string.charCodeAt(pos++);\r\n if (value >= 0xd800 && value <= 0xdbff) {\r\n // high surrogate\r\n if (pos < len) {\r\n const extra = string.charCodeAt(pos);\r\n if ((extra & 0xfc00) === 0xdc00) {\r\n ++pos;\r\n value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000;\r\n }\r\n }\r\n if (value >= 0xd800 && value <= 0xdbff) {\r\n continue; // drop lone surrogate\r\n }\r\n }\r\n // expand the buffer if we couldn't write 4 bytes\r\n if (at + 4 > target.length) {\r\n tlen += 8; // minimum extra\r\n tlen *= 1.0 + (pos / string.length) * 2; // take 2x the remaining\r\n tlen = (tlen >> 3) << 3; // 8 byte offset\r\n const update = new Uint8Array(tlen);\r\n update.set(target);\r\n target = update;\r\n }\r\n if ((value & 0xffffff80) === 0) {\r\n // 1-byte\r\n target[at++] = value; // ASCII\r\n continue;\r\n }\r\n else if ((value & 0xfffff800) === 0) {\r\n // 2-byte\r\n target[at++] = ((value >> 6) & 0x1f) | 0xc0;\r\n }\r\n else if ((value & 0xffff0000) === 0) {\r\n // 3-byte\r\n target[at++] = ((value >> 12) & 0x0f) | 0xe0;\r\n target[at++] = ((value >> 6) & 0x3f) | 0x80;\r\n }\r\n else if ((value & 0xffe00000) === 0) {\r\n // 4-byte\r\n target[at++] = ((value >> 18) & 0x07) | 0xf0;\r\n target[at++] = ((value >> 12) & 0x3f) | 0x80;\r\n target[at++] = ((value >> 6) & 0x3f) | 0x80;\r\n }\r\n else {\r\n // FIXME: do we care\r\n continue;\r\n }\r\n target[at++] = (value & 0x3f) | 0x80;\r\n }\r\n return target.slice(0, at);\r\n };\r\n /**\r\n * @constructor\r\n * @param {string=} utfLabel\r\n * @param {{fatal: boolean}=} options\r\n */\r\n function FastTextDecoder(utfLabel = 'utf-8', options = { fatal: false }) {\r\n if (utfLabel !== 'utf-8') {\r\n throw new RangeError(`Failed to construct 'TextDecoder': The encoding label provided ('${utfLabel}') is invalid.`);\r\n }\r\n if (options.fatal) {\r\n throw new Error(`Failed to construct 'TextDecoder': the 'fatal' option is unsupported.`);\r\n }\r\n }\r\n Object.defineProperty(FastTextDecoder.prototype, 'encoding', {\r\n value: 'utf-8',\r\n });\r\n Object.defineProperty(FastTextDecoder.prototype, 'fatal', { value: false });\r\n Object.defineProperty(FastTextDecoder.prototype, 'ignoreBOM', {\r\n value: false,\r\n });\r\n /**\r\n * @param {(!ArrayBuffer|!ArrayBufferView)} buffer\r\n * @param {{stream: boolean}=} options\r\n */\r\n FastTextDecoder.prototype.decode = function (buffer, options = { stream: false }) {\r\n if (options['stream']) {\r\n throw new Error(`Failed to decode: the 'stream' option is unsupported.`);\r\n }\r\n const bytes = new Uint8Array(buffer);\r\n let pos = 0;\r\n const len = bytes.length;\r\n const out = [];\r\n while (pos < len) {\r\n const byte1 = bytes[pos++];\r\n if (byte1 === 0) {\r\n break; // NULL\r\n }\r\n if ((byte1 & 0x80) === 0) {\r\n // 1-byte\r\n out.push(byte1);\r\n }\r\n else if ((byte1 & 0xe0) === 0xc0) {\r\n // 2-byte\r\n const byte2 = bytes[pos++] & 0x3f;\r\n out.push(((byte1 & 0x1f) << 6) | byte2);\r\n }\r\n else if ((byte1 & 0xf0) === 0xe0) {\r\n const byte2 = bytes[pos++] & 0x3f;\r\n const byte3 = bytes[pos++] & 0x3f;\r\n out.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3);\r\n }\r\n else if ((byte1 & 0xf8) === 0xf0) {\r\n const byte2 = bytes[pos++] & 0x3f;\r\n const byte3 = bytes[pos++] & 0x3f;\r\n const byte4 = bytes[pos++] & 0x3f;\r\n // this can be > 0xffff, so possibly generate surrogates\r\n let codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4;\r\n if (codepoint > 0xffff) {\r\n // codepoint &= ~0x10000;\r\n codepoint -= 0x10000;\r\n out.push(((codepoint >>> 10) & 0x3ff) | 0xd800);\r\n codepoint = 0xdc00 | (codepoint & 0x3ff);\r\n }\r\n out.push(codepoint);\r\n }\r\n else {\r\n // FIXME: we're ignoring this\r\n }\r\n }\r\n return String.fromCharCode.apply(null, out);\r\n };\r\n scope['TextEncoder'] = FastTextEncoder;\r\n scope['TextDecoder'] = FastTextDecoder;\r\n})(typeof window !== 'undefined'\r\n ? window\r\n : typeof self !== 'undefined'\r\n ? self\r\n : this);\r\n//# sourceMappingURL=text-encoding-polyfill.js.map","import './text-encoding-polyfill';\r\nconst decoder = new TextDecoder('utf-8');\r\nexport function decode(bytes) {\r\n return decoder.decode(bytes);\r\n}\r\nconst encoder = new TextEncoder();\r\nexport function encode(str) {\r\n return encoder.encode(str);\r\n}\r\n//# sourceMappingURL=utf8.browser.js.map","import { decode, encode } from './utf8';\r\nconst defaultByteLength = 1024 * 8;\r\nexport class IOBuffer {\r\n /**\r\n * @param data - The data to construct the IOBuffer with.\r\n * If data is a number, it will be the new buffer's length
\r\n * If data is `undefined`, the buffer will be initialized with a default length of 8Kb
\r\n * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,\r\n * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.\r\n * @param options\r\n */\r\n constructor(data = defaultByteLength, options = {}) {\r\n let dataIsGiven = false;\r\n if (typeof data === 'number') {\r\n data = new ArrayBuffer(data);\r\n }\r\n else {\r\n dataIsGiven = true;\r\n this.lastWrittenByte = data.byteLength;\r\n }\r\n const offset = options.offset ? options.offset >>> 0 : 0;\r\n const byteLength = data.byteLength - offset;\r\n let dvOffset = offset;\r\n if (ArrayBuffer.isView(data) || data instanceof IOBuffer) {\r\n if (data.byteLength !== data.buffer.byteLength) {\r\n dvOffset = data.byteOffset + offset;\r\n }\r\n data = data.buffer;\r\n }\r\n if (dataIsGiven) {\r\n this.lastWrittenByte = byteLength;\r\n }\r\n else {\r\n this.lastWrittenByte = 0;\r\n }\r\n this.buffer = data;\r\n this.length = byteLength;\r\n this.byteLength = byteLength;\r\n this.byteOffset = dvOffset;\r\n this.offset = 0;\r\n this.littleEndian = true;\r\n this._data = new DataView(this.buffer, dvOffset, byteLength);\r\n this._mark = 0;\r\n this._marks = [];\r\n }\r\n /**\r\n * Checks if the memory allocated to the buffer is sufficient to store more\r\n * bytes after the offset.\r\n * @param byteLength - The needed memory in bytes.\r\n * @returns `true` if there is sufficient space and `false` otherwise.\r\n */\r\n available(byteLength = 1) {\r\n return this.offset + byteLength <= this.length;\r\n }\r\n /**\r\n * Check if little-endian mode is used for reading and writing multi-byte\r\n * values.\r\n * @returns `true` if little-endian mode is used, `false` otherwise.\r\n */\r\n isLittleEndian() {\r\n return this.littleEndian;\r\n }\r\n /**\r\n * Set little-endian mode for reading and writing multi-byte values.\r\n */\r\n setLittleEndian() {\r\n this.littleEndian = true;\r\n return this;\r\n }\r\n /**\r\n * Check if big-endian mode is used for reading and writing multi-byte values.\r\n * @returns `true` if big-endian mode is used, `false` otherwise.\r\n */\r\n isBigEndian() {\r\n return !this.littleEndian;\r\n }\r\n /**\r\n * Switches to big-endian mode for reading and writing multi-byte values.\r\n */\r\n setBigEndian() {\r\n this.littleEndian = false;\r\n return this;\r\n }\r\n /**\r\n * Move the pointer n bytes forward.\r\n * @param n - Number of bytes to skip.\r\n */\r\n skip(n = 1) {\r\n this.offset += n;\r\n return this;\r\n }\r\n /**\r\n * Move the pointer to the given offset.\r\n * @param offset\r\n */\r\n seek(offset) {\r\n this.offset = offset;\r\n return this;\r\n }\r\n /**\r\n * Store the current pointer offset.\r\n * @see {@link IOBuffer#reset}\r\n */\r\n mark() {\r\n this._mark = this.offset;\r\n return this;\r\n }\r\n /**\r\n * Move the pointer back to the last pointer offset set by mark.\r\n * @see {@link IOBuffer#mark}\r\n */\r\n reset() {\r\n this.offset = this._mark;\r\n return this;\r\n }\r\n /**\r\n * Push the current pointer offset to the mark stack.\r\n * @see {@link IOBuffer#popMark}\r\n */\r\n pushMark() {\r\n this._marks.push(this.offset);\r\n return this;\r\n }\r\n /**\r\n * Pop the last pointer offset from the mark stack, and set the current\r\n * pointer offset to the popped value.\r\n * @see {@link IOBuffer#pushMark}\r\n */\r\n popMark() {\r\n const offset = this._marks.pop();\r\n if (offset === undefined) {\r\n throw new Error('Mark stack empty');\r\n }\r\n this.seek(offset);\r\n return this;\r\n }\r\n /**\r\n * Move the pointer offset back to 0.\r\n */\r\n rewind() {\r\n this.offset = 0;\r\n return this;\r\n }\r\n /**\r\n * Make sure the buffer has sufficient memory to write a given byteLength at\r\n * the current pointer offset.\r\n * If the buffer's memory is insufficient, this method will create a new\r\n * buffer (a copy) with a length that is twice (byteLength + current offset).\r\n * @param byteLength\r\n */\r\n ensureAvailable(byteLength = 1) {\r\n if (!this.available(byteLength)) {\r\n const lengthNeeded = this.offset + byteLength;\r\n const newLength = lengthNeeded * 2;\r\n const newArray = new Uint8Array(newLength);\r\n newArray.set(new Uint8Array(this.buffer));\r\n this.buffer = newArray.buffer;\r\n this.length = this.byteLength = newLength;\r\n this._data = new DataView(this.buffer);\r\n }\r\n return this;\r\n }\r\n /**\r\n * Read a byte and return false if the byte's value is 0, or true otherwise.\r\n * Moves pointer forward by one byte.\r\n */\r\n readBoolean() {\r\n return this.readUint8() !== 0;\r\n }\r\n /**\r\n * Read a signed 8-bit integer and move pointer forward by 1 byte.\r\n */\r\n readInt8() {\r\n return this._data.getInt8(this.offset++);\r\n }\r\n /**\r\n * Read an unsigned 8-bit integer and move pointer forward by 1 byte.\r\n */\r\n readUint8() {\r\n return this._data.getUint8(this.offset++);\r\n }\r\n /**\r\n * Alias for {@link IOBuffer#readUint8}.\r\n */\r\n readByte() {\r\n return this.readUint8();\r\n }\r\n /**\r\n * Read `n` bytes and move pointer forward by `n` bytes.\r\n */\r\n readBytes(n = 1) {\r\n const bytes = new Uint8Array(n);\r\n for (let i = 0; i < n; i++) {\r\n bytes[i] = this.readByte();\r\n }\r\n return bytes;\r\n }\r\n /**\r\n * Read a 16-bit signed integer and move pointer forward by 2 bytes.\r\n */\r\n readInt16() {\r\n const value = this._data.getInt16(this.offset, this.littleEndian);\r\n this.offset += 2;\r\n return value;\r\n }\r\n /**\r\n * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.\r\n */\r\n readUint16() {\r\n const value = this._data.getUint16(this.offset, this.littleEndian);\r\n this.offset += 2;\r\n return value;\r\n }\r\n /**\r\n * Read a 32-bit signed integer and move pointer forward by 4 bytes.\r\n */\r\n readInt32() {\r\n const value = this._data.getInt32(this.offset, this.littleEndian);\r\n this.offset += 4;\r\n return value;\r\n }\r\n /**\r\n * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.\r\n */\r\n readUint32() {\r\n const value = this._data.getUint32(this.offset, this.littleEndian);\r\n this.offset += 4;\r\n return value;\r\n }\r\n /**\r\n * Read a 32-bit floating number and move pointer forward by 4 bytes.\r\n */\r\n readFloat32() {\r\n const value = this._data.getFloat32(this.offset, this.littleEndian);\r\n this.offset += 4;\r\n return value;\r\n }\r\n /**\r\n * Read a 64-bit floating number and move pointer forward by 8 bytes.\r\n */\r\n readFloat64() {\r\n const value = this._data.getFloat64(this.offset, this.littleEndian);\r\n this.offset += 8;\r\n return value;\r\n }\r\n /**\r\n * Read a 1-byte ASCII character and move pointer forward by 1 byte.\r\n */\r\n readChar() {\r\n return String.fromCharCode(this.readInt8());\r\n }\r\n /**\r\n * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.\r\n */\r\n readChars(n = 1) {\r\n let result = '';\r\n for (let i = 0; i < n; i++) {\r\n result += this.readChar();\r\n }\r\n return result;\r\n }\r\n /**\r\n * Read the next `n` bytes, return a UTF-8 decoded string and move pointer\r\n * forward by `n` bytes.\r\n */\r\n readUtf8(n = 1) {\r\n return decode(this.readBytes(n));\r\n }\r\n /**\r\n * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer\r\n * forward by 1 byte.\r\n */\r\n writeBoolean(value) {\r\n this.writeUint8(value ? 0xff : 0x00);\r\n return this;\r\n }\r\n /**\r\n * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.\r\n */\r\n writeInt8(value) {\r\n this.ensureAvailable(1);\r\n this._data.setInt8(this.offset++, value);\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * Write `value` as an 8-bit unsigned integer and move pointer forward by 1\r\n * byte.\r\n */\r\n writeUint8(value) {\r\n this.ensureAvailable(1);\r\n this._data.setUint8(this.offset++, value);\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * An alias for {@link IOBuffer#writeUint8}.\r\n */\r\n writeByte(value) {\r\n return this.writeUint8(value);\r\n }\r\n /**\r\n * Write all elements of `bytes` as uint8 values and move pointer forward by\r\n * `bytes.length` bytes.\r\n */\r\n writeBytes(bytes) {\r\n this.ensureAvailable(bytes.length);\r\n for (let i = 0; i < bytes.length; i++) {\r\n this._data.setUint8(this.offset++, bytes[i]);\r\n }\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * Write `value` as a 16-bit signed integer and move pointer forward by 2\r\n * bytes.\r\n */\r\n writeInt16(value) {\r\n this.ensureAvailable(2);\r\n this._data.setInt16(this.offset, value, this.littleEndian);\r\n this.offset += 2;\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * Write `value` as a 16-bit unsigned integer and move pointer forward by 2\r\n * bytes.\r\n */\r\n writeUint16(value) {\r\n this.ensureAvailable(2);\r\n this._data.setUint16(this.offset, value, this.littleEndian);\r\n this.offset += 2;\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * Write `value` as a 32-bit signed integer and move pointer forward by 4\r\n * bytes.\r\n */\r\n writeInt32(value) {\r\n this.ensureAvailable(4);\r\n this._data.setInt32(this.offset, value, this.littleEndian);\r\n this.offset += 4;\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * Write `value` as a 32-bit unsigned integer and move pointer forward by 4\r\n * bytes.\r\n */\r\n writeUint32(value) {\r\n this.ensureAvailable(4);\r\n this._data.setUint32(this.offset, value, this.littleEndian);\r\n this.offset += 4;\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * Write `value` as a 32-bit floating number and move pointer forward by 4\r\n * bytes.\r\n */\r\n writeFloat32(value) {\r\n this.ensureAvailable(4);\r\n this._data.setFloat32(this.offset, value, this.littleEndian);\r\n this.offset += 4;\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * Write `value` as a 64-bit floating number and move pointer forward by 8\r\n * bytes.\r\n */\r\n writeFloat64(value) {\r\n this.ensureAvailable(8);\r\n this._data.setFloat64(this.offset, value, this.littleEndian);\r\n this.offset += 8;\r\n this._updateLastWrittenByte();\r\n return this;\r\n }\r\n /**\r\n * Write the charCode of `str`'s first character as an 8-bit unsigned integer\r\n * and move pointer forward by 1 byte.\r\n */\r\n writeChar(str) {\r\n return this.writeUint8(str.charCodeAt(0));\r\n }\r\n /**\r\n * Write the charCodes of all `str`'s characters as 8-bit unsigned integers\r\n * and move pointer forward by `str.length` bytes.\r\n */\r\n writeChars(str) {\r\n for (let i = 0; i < str.length; i++) {\r\n this.writeUint8(str.charCodeAt(i));\r\n }\r\n return this;\r\n }\r\n /**\r\n * UTF-8 encode and write `str` to the current pointer offset and move pointer\r\n * forward according to the encoded length.\r\n */\r\n writeUtf8(str) {\r\n return this.writeBytes(encode(str));\r\n }\r\n /**\r\n * Export a Uint8Array view of the internal buffer.\r\n * The view starts at the byte offset and its length\r\n * is calculated to stop at the last written byte or the original length.\r\n */\r\n toArray() {\r\n return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);\r\n }\r\n /**\r\n * Update the last written byte offset\r\n * @private\r\n */\r\n _updateLastWrittenByte() {\r\n if (this.offset > this.lastWrittenByte) {\r\n this.lastWrittenByte = this.offset;\r\n }\r\n }\r\n}\r\n//# sourceMappingURL=IOBuffer.js.map","export const endianness = {\n 0: 'bigEndian',\n 1: 'littleEndian',\n};\n\nexport const instrumentTable = {\n 0: 'NONE',\n 1: 'GSX',\n 2: 'ALPHA',\n 3: 'ECLIPSE',\n 4: 'MASS_SPEC',\n 5: 'COMPILER',\n 6: 'OTHER_NMR',\n 7: 'UNKNOWN',\n 8: 'GEMINI',\n 9: 'UNITY',\n 10: 'ASPECT',\n 11: 'UX',\n 12: 'FELIX',\n 13: 'LAMBDA',\n 14: 'GE_1280',\n 15: 'GE_OMEGA',\n 16: 'CHEMAGNETICS',\n 17: 'CDFF',\n 18: 'GALACTIC',\n 19: 'TRIAD',\n 20: 'GENERIC_NMR',\n 21: 'GAMMA',\n 22: 'JCAMP_DX',\n 23: 'AMX',\n 24: 'DMX',\n 25: 'ECA',\n 26: 'ALICE',\n 27: 'NMR_PIPE',\n 28: 'SIMPSON',\n};\n\nexport const dataTypeTable = {\n 0: '64Bit Float',\n 1: '32Bit Float',\n 2: 'Reserved',\n 3: 'Reserved',\n};\n\nexport const dataFormatTable = {\n 1: 'One_D',\n 2: 'Two_D',\n 3: 'Three_D',\n 4: 'Four_D',\n 5: 'Five_D',\n 6: 'Six_D',\n 7: 'Seven_D',\n 8: 'Eight_D',\n 9: 'not for NMR data formats',\n 10: 'not for NMR data formats',\n 11: 'not for NMR data formats',\n 12: 'Small_Two_D',\n 13: 'Small_Three_D',\n 14: 'Small_Four_D',\n};\n\nexport const dataAxisTypeTable = {\n 0: 'None', //Axis is not used.\n 1: 'Real', //Axis has real data only, no imaginary.\n 2: 'TPPI',\n 3: 'Complex',\n 4: 'Real_Complex',\n /* Axis should be accessed as complex when it is the major axis,\n accessed as real otherwise. This is only valid when all axes in\n use have this setting.*/\n 5: 'Envelope',\n /* Behaves the same way as a Real_Complex dimension but the data\n has different meaning. Instead of being treated as real and\n imaginary parts of a complex number, the data should be treated as minimum and maximum parts of a projection. This is used\n for the data that results from an envelope projection.*/\n};\n\nexport const prefixTable = {\n '-8': 'Yotta',\n '-6': 'Exa',\n '-7': 'Zetta',\n '-5': 'Pecta',\n '-4': 'Tera',\n '-3': 'Giga',\n '-2': 'Mega',\n '-1': 'Kilo',\n '0': 'None',\n '1': 'Milli',\n '2': 'Micro',\n '3': 'Nano',\n '4': 'Pico',\n '5': 'Femto',\n '6': 'Atto',\n '7': 'Zepto',\n};\n\nexport const unitPrefixTable = {\n Yotta: 24,\n Exa: 21,\n Zetta: 18,\n Pecta: 15,\n Tera: 12,\n Giga: 9,\n Mega: 6,\n Kilo: 3,\n None: 0,\n Milli: -3,\n Micro: -6,\n Nano: -9,\n Pico: -12,\n Femto: -15,\n Atto: -18,\n Zepto: -21,\n};\n\nexport const baseTable = {\n 0: 'None',\n 1: 'Abundance',\n 2: 'Ampere',\n 3: 'Candela',\n 4: 'Celsius',\n 5: 'Coulomb',\n 6: 'Degree',\n 7: 'Electronvolt',\n 8: 'Farad',\n 9: 'Sievert',\n 10: 'Gram',\n 11: 'Gray',\n 12: 'Henry',\n 13: 'Hertz',\n 14: 'Kelvin',\n 15: 'Joule',\n 16: 'Liter',\n 17: 'Lumen',\n 18: 'Lux',\n 19: 'Meter',\n 20: 'Mole',\n 21: 'Newton',\n 22: 'Ohm',\n 23: 'Pascal',\n 24: 'Percent',\n 25: 'Point',\n 26: 'Ppm',\n 27: 'Radian',\n 28: 'Second',\n 29: 'Siemens',\n 30: 'Steradian',\n 31: 'Tesla',\n 32: 'Volt',\n 33: 'Watt',\n 34: 'Weber',\n 35: 'Decibel',\n 36: 'Dalton',\n 37: 'Thompson',\n 38: 'Ugeneric', // Treated as None, but never displayed',\n 39: 'LPercent ', // Treated as percent for display, but different for comparison',\n 40: 'PPT', // Parts per trillion (Private, do not use)',\n 41: 'PPB ', // Parts per billion (Private, do not use)',\n 42: 'Index',\n};\n\nexport const dataAxisRangedTable = {\n 0: 'Ranged',\n /* The ruler for the axis ranges from Data_Axis_Start[n] to\n Data_Axis_Stop[n] with a step function of\n (Data_Axis_Stop[n] - Data_Axis_Start[n]) /\n (Data_Offset_Stop[n] - Data_Offset_Start[n]) */\n 1: 'Listed', // (deprecated)\n /* The ruler for the axis is a list of doubles stored in the\n List Section. Values in the ruler may be anything.*/\n 2: 'Sparse',\n /*The ruler for the axis is a list of doubles stored in the\n List Section. Values in the rulers must be strictly monotonically\n increasing or decreasing.*/\n 3: 'Listed',\n /* The ruler for the axis is a list of doubles stored in the\n List Section. Values in the rulers do not fit definition of Sparse.*/\n};\n\nexport const valueTypeTable = {\n 0: 'String',\n 1: 'Integer',\n 2: 'Float',\n 3: 'Complex',\n 4: 'Infinity',\n};\n","import * as table from './conversionTables';\n\nexport function getPar(param, searchStr) {\n return param.paramArray.find((o) => o.name === searchStr) || '';\n}\n\nexport function getMagnitude(param, searchStr) {\n let par = getPar(param, searchStr) || 'NA';\n if (par === 'NA') {\n return { magnitude: 'NA', unit: 'NA' };\n }\n let unit = par.unit[0].base;\n let unitMult = table.unitPrefixTable[par.unit[0].prefix];\n let magnitude = par.value * 10 ** unitMult;\n return { magnitude, unit };\n}\n\nexport function getUnit(buffer, size) {\n let unit = [];\n for (let i = 0; i < size; i++) {\n let byte = buffer.readByte();\n let prefix = table.prefixTable[byte >> 4];\n let power = byte & 0b00001111;\n let base = table.baseTable[buffer.readInt8()];\n unit.push({ prefix, power, base });\n }\n return unit;\n}\n\nexport function getString(buffer, size) {\n let string = [];\n for (let i = 0; i < size; i++) {\n let char = buffer.readChar();\n if (char !== '\\u0000') {\n string.push(char);\n }\n }\n return string.join('');\n}\n\nexport function getParamName(buffer, size) {\n let string = [];\n for (let i = 0; i < size; i++) {\n let char = buffer.readChar();\n if (char !== ' ') {\n string.push(char);\n }\n }\n return string.join('');\n}\n\nexport function getArray(buffer, size, format) {\n let double = [];\n for (let i = 0; i < size; i++) {\n switch (format) {\n case 'readUint32':\n double.push(buffer.readUint32());\n break;\n case 'readFloat64':\n double.push(buffer.readFloat64());\n break;\n case 'readFloat32':\n double.push(buffer.readFloat32());\n break;\n case 'readUint8':\n double.push(buffer.readUint8());\n break;\n case 'readBoolean':\n double.push(buffer.readBoolean());\n break;\n default:\n break;\n }\n }\n return double;\n}\n","import { IOBuffer } from 'iobuffer';\n\nimport * as table from './conversionTables';\nimport {\n getPar,\n getMagnitude,\n getParamName,\n getArray,\n getUnit,\n getString,\n} from './utils';\n\n/**\n * A parser for 1D and 2D JDL NMR Files\n * @param {ArrayBuffer} buffer - a buffer object containing the JDL file\n * @return {Object} - an Object with converted data\n */\nexport function parseJEOL(buffer) {\n let ioBuffer = new IOBuffer(buffer);\n ioBuffer.setBigEndian();\n\n // read header section\n let byte;\n let header = {};\n let byteArray = [];\n\n header.fileIdentifier = ioBuffer.readChars(8);\n header.endian = table.endianness[ioBuffer.readInt8()];\n header.majorVersion = ioBuffer.readUint8();\n header.minorVersion = ioBuffer.readUint16();\n header.dataDimensionNumber = ioBuffer.readUint8();\n\n header.dataDimensionExist = ioBuffer\n .readByte()\n .toString(2)\n .split('')\n .map((x) => Boolean(Number(x)));\n\n byte = ioBuffer.readByte();\n header.dataType = table.dataTypeTable[byte >> 6];\n header.dataFormat = table.dataFormatTable[byte & 0b00111111];\n header.dataInstrument = table.instrumentTable[ioBuffer.readInt8()];\n header.translate = getArray(ioBuffer, 8, 'readUint8');\n header.dataAxisType = getArray(ioBuffer, 8, 'readUint8').map(\n (x) => table.dataAxisTypeTable[x],\n );\n\n header.dataUnits = getUnit(ioBuffer, 8);\n header.title = getString(ioBuffer, 124);\n\n for (byte in getArray(ioBuffer, 4, 'readUint8')) {\n byteArray.push(table.dataAxisRangedTable[byte >> 4]);\n byteArray.push(table.dataAxisRangedTable[byte & 0b00001111]);\n }\n\n header.dataAxisRanged = byteArray;\n header.dataPoints = getArray(ioBuffer, 8, 'readUint32');\n header.dataOffsetStart = getArray(ioBuffer, 8, 'readUint32');\n header.dataOffsetStop = getArray(ioBuffer, 8, 'readUint32');\n header.dataAxisStart = getArray(ioBuffer, 8, 'readFloat64');\n header.dataAxisStop = getArray(ioBuffer, 8, 'readFloat64');\n\n byteArray = new Uint8Array(4);\n for (let i = 0; i < 4; i++) {\n byteArray[i] = ioBuffer.readByte();\n }\n let year = 1990 + (byteArray[0] >> 1);\n let month = ((byteArray[0] << 3) & 0b00001000) + (byteArray[1] >> 5);\n let day = byteArray[2] & 0b00011111;\n header.creationTime = { year, month, day };\n\n for (let i = 0; i < 4; i++) {\n byteArray[i] = ioBuffer.readByte();\n }\n year = 1990 + (byteArray[0] >> 1);\n month = ((byteArray[0] << 3) & 0b00001000) + (byteArray[1] >> 5);\n day = byteArray[2] & 0b00011111;\n header.revisionTime = { year, month, day };\n\n header.nodeName = getString(ioBuffer, 16);\n header.site = getString(ioBuffer, 128);\n header.author = getString(ioBuffer, 128);\n header.comment = getString(ioBuffer, 128);\n\n let dataAxisTitles = [];\n for (let i = 0; i < 8; i++) {\n dataAxisTitles.push(getString(ioBuffer, 32));\n }\n header.dataAxisTitles = dataAxisTitles;\n\n header.baseFreq = getArray(ioBuffer, 8, 'readFloat64');\n header.zeroPoint = getArray(ioBuffer, 8, 'readFloat64');\n header.reversed = getArray(ioBuffer, 8, 'readBoolean');\n ioBuffer.skip(3);\n header.annotationOK = Boolean(ioBuffer.readByte() >> 7);\n header.historyUsed = ioBuffer.readUint32();\n header.historyLength = ioBuffer.readUint32();\n header.paramStart = ioBuffer.readUint32();\n header.paramLength = ioBuffer.readUint32();\n header.ListStart = getArray(ioBuffer, 8, 'readUint32');\n header.ListLength = getArray(ioBuffer, 8, 'readUint32');\n header.dataStart = ioBuffer.readUint32();\n header.dataLength = (ioBuffer.readUint32() << 32) | ioBuffer.readUint32();\n header.contextStart = (ioBuffer.readUint32() << 32) | ioBuffer.readUint32();\n header.contextLength = ioBuffer.readUint32();\n header.annoteStart = (ioBuffer.readUint32() << 32) | ioBuffer.readUint32();\n header.annoteLength = ioBuffer.readUint32();\n header.totalSize = (ioBuffer.readUint32() << 32) | ioBuffer.readUint32();\n header.unitLocation = getArray(ioBuffer, 8, 'readUint8');\n\n let compoundUnit = [];\n for (let i = 0; i < 2; i++) {\n let unit = [];\n let scaler = ioBuffer.readInt16();\n for (let j = 0; j < 5; j++) {\n byte = ioBuffer.readInt16();\n unit.push(byte);\n }\n compoundUnit.push({ scaler, unit });\n }\n header.compoundUnit = compoundUnit;\n\n // section parameters (param header and array)\n if (header.endian === 'littleEndian') {\n ioBuffer.setLittleEndian();\n }\n ioBuffer.seek(header.paramStart);\n\n let parameters = {\n parameterSize: ioBuffer.readUint32(),\n lowIndex: ioBuffer.readUint32(),\n highIndex: ioBuffer.readUint32(),\n totalSize: ioBuffer.readUint32(),\n };\n let paramArray = [];\n for (let p = 0; p < parameters.highIndex + 1; p++) {\n ioBuffer.skip(4);\n let scaler = ioBuffer.readInt16();\n let unit = getUnit(ioBuffer, 5);\n ioBuffer.skip(16);\n let valueType = table.valueTypeTable[ioBuffer.readInt32()];\n ioBuffer.seek(ioBuffer.offset - 20);\n let value;\n switch (valueType) {\n case 'String':\n value = getParamName(ioBuffer, 16);\n break;\n case 'Integer':\n value = ioBuffer.readInt32();\n ioBuffer.skip(12);\n break;\n case 'Float':\n value = ioBuffer.readFloat64();\n ioBuffer.skip(8);\n break;\n case 'Complex':\n value.Real = ioBuffer.readFloat64();\n value.Imag = ioBuffer.readFloat64();\n break;\n case 'Infinity':\n value = ioBuffer.readInt32();\n ioBuffer.skip(12);\n break;\n default:\n ioBuffer.skip(16);\n break;\n }\n ioBuffer.skip(4);\n let name = getParamName(ioBuffer, 28);\n paramArray.push({ name, scaler, unit, value, valueType });\n }\n parameters.paramArray = paramArray;\n\n // data section\n ioBuffer.seek(header.dataStart);\n if (header.endian === 'littleEndian') {\n ioBuffer.setLittleEndian();\n }\n\n let data = {};\n let dataSectionCount = 1;\n let realComplex = 0;\n for (let type of header.dataAxisType) {\n if (type === 'Real_Complex' && realComplex === 0) {\n dataSectionCount += 1;\n realComplex += 1;\n }\n if (type === 'Complex') {\n dataSectionCount *= 2;\n }\n }\n\n if (header.dataFormat !== 'One_D' && header.dataFormat !== 'Two_D') {\n throw new Error('Only One_D and two_D data formats are implemented yet');\n }\n\n if (header.dataFormat === 'One_D') {\n for (let s = 0; s < dataSectionCount; s++) {\n let section;\n if (header.dataType === '32Bit Float') {\n section = getArray(ioBuffer, header.dataPoints[0], 'readFloat32');\n } else if (header.dataType === '64Bit Float') {\n section = getArray(ioBuffer, header.dataPoints[0], 'readFloat64');\n }\n if (s === 0) data.re = section;\n if (s === 1) data.im = section;\n }\n }\n\n if (header.dataFormat === 'Two_D') {\n let me = 32;\n let dim1 = header.dataPoints[0];\n let dim2 = header.dataPoints[1];\n // console.log(\n // `dim1: ${dim1},\n // dim2: ${dim2},\n // total: ${dim1 * dim2},\n // total(byte): ${dim1 * dim2 * 8},\n // total(length): ${dim1 * dim2 * 8 * dataSectionCount}\n // m size: ${dim1 / me} / ${dim2 / me}`,\n // );\n let I = dim2 / me;\n let J = dim1 / me;\n\n for (let s = 0; s < dataSectionCount; s++) {\n let section;\n for (let i = 0; i < I; i++) {\n let row = [];\n for (let j = 0; j < J; j++) {\n for (let k = 0; k < me; k++) {\n if (j === 0) {\n if (header.dataType === '32Bit Float') {\n row[k] = getArray(ioBuffer, me, 'readFloat32');\n } else if (header.dataType === '64Bit Float') {\n row[k] = getArray(ioBuffer, me, 'readFloat64');\n }\n } else {\n if (header.dataType === '32Bit Float') {\n row[k] = row[k].concat(getArray(ioBuffer, me, 'readFloat32'));\n } else if (header.dataType === '64Bit Float') {\n row[k] = row[k].concat(getArray(ioBuffer, me, 'readFloat64'));\n }\n }\n }\n }\n if (i === 0) {\n section = row;\n } else {\n section = section.concat(row);\n }\n }\n if (dataSectionCount === 2) {\n if (s === 0) data.re = section;\n if (s === 1) data.im = section;\n }\n if (dataSectionCount === 4) {\n if (s === 0) {\n data.re = {};\n data.re.re = section;\n }\n if (s === 1) data.re.im = section;\n if (s === 2) {\n data.im = {};\n data.im.re = section;\n }\n if (s === 3) data.im.im = section;\n }\n }\n }\n\n // format output\n let nucleus = [];\n let acquisitionTime = [];\n let spectralWidth = [];\n let spectralWidthClipped = [];\n let resolution = [];\n let originFrequency = [];\n let frequencyOffset = [];\n let dataUnits = [];\n if (header.dataFormat === 'One_D' || header.dataFormat === 'Two_D') {\n nucleus.push(getPar(parameters, 'X_DOMAIN').value);\n acquisitionTime.push(getMagnitude(parameters, 'x_acq_time'));\n spectralWidth.push(getMagnitude(parameters, 'X_SWEEP'));\n spectralWidthClipped.push(getMagnitude(parameters, 'X_SWEEP_CLIPPED'));\n resolution.push(getMagnitude(parameters, 'X_RESOLUTION'));\n originFrequency.push(getMagnitude(parameters, 'X_FREQ'));\n frequencyOffset.push(getMagnitude(parameters, 'X_OFFSET'));\n dataUnits.push(header.dataUnits[0].base);\n }\n if (header.dataFormat === 'Two_D') {\n nucleus.push(getPar(parameters, 'Y_DOMAIN').value);\n acquisitionTime.push(getMagnitude(parameters, 'y_acq_time'));\n spectralWidth.push(getMagnitude(parameters, 'Y_SWEEP'));\n resolution.push(getMagnitude(parameters, 'Y_RESOLUTION'));\n originFrequency.push(getMagnitude(parameters, 'Y_FREQ'));\n frequencyOffset.push(getMagnitude(parameters, 'Y_OFFSET'));\n dataUnits.push(header.dataUnits[1].base);\n }\n\n let digest = {\n info: {\n sampleName: getPar(parameters, 'sample_id').value,\n creationTime: header.creationTime,\n revisionTime: header.revisionTime,\n author: header.author,\n comment: header.comment,\n solvent: getPar(parameters, 'solvent').value,\n temperature: getMagnitude(parameters, 'temp_get'),\n probeName: getPar(parameters, 'probe_id').value,\n fieldStrength: getMagnitude(parameters, 'field_strength'),\n experiment: getPar(parameters, 'experiment').value,\n dimension: header.dataDimensionNumber,\n nucleus: nucleus,\n pulseStrength90: getMagnitude(parameters, 'X90'),\n numberOfScans: getPar(parameters, 'SCANS').value,\n relaxationTime: getMagnitude(parameters, 'relaxation_delay'),\n dataPoints: header.dataPoints.slice(0, header.dataDimensionNumber),\n dataOffsetStart: header.dataOffsetStart,\n dataOffsetStop: header.dataOffsetStop,\n dataUnits: dataUnits,\n dataSections: Object.keys(data),\n originFrequency,\n frequencyOffset,\n acquisitionTime,\n spectralWidth,\n spectralWidthClipped,\n dataAxisStart: header.dataAxisStart,\n dataAxisStop: header.dataAxisStop,\n resolution: resolution,\n digitalFilter: getPar(parameters, 'FILTER_FACTOR').value,\n decimationRate: getPar(parameters, 'decimation_rate').value,\n paramList: JSON.stringify(parameters.paramArray.map((par) => par.name)),\n },\n\n headers: header,\n parameters: parameters,\n data: data,\n };\n return digest;\n}\n","export function toKeyValue(object) {\n let newObject = {};\n for (let key in object) {\n if (typeof object[key] !== 'string') {\n newObject[key] = JSON.stringify(object[key]);\n } else {\n newObject[key] = object[key];\n }\n }\n return newObject;\n}\n","import { parseJEOL } from 'jeolconverter';\n\nimport { version, dependencies, devDependencies } from '../package.json';\n\nimport { formatDependentVariable } from './formatDependentVariable';\nimport { formatLinearDimension } from './formatLinearDimension';\nimport { toKeyValue } from './utils/toKeyValue';\n\nexport function fromJEOL(buffer) {\n let parsedData = parseJEOL(buffer);\n let info = parsedData.info;\n let headers = parsedData.headers;\n let parameters = parsedData.parameters;\n let paramArray = Object.assign({}, parameters.paramArray);\n delete parameters.paramArray;\n let data = parsedData.data;\n\n // curation of parameters\n let newInfo = {};\n newInfo.title = `title: ${headers.title} / comment: ${headers.comment} / author:${headers.author} / site: ${headers.site}`;\n newInfo.nucleus = info.nucleus.map((x) => {\n if (x === 'Proton') {\n x = '1H';\n }\n if (x === 'Carbon13') {\n x = '13C';\n }\n if (x === 'Nitrogen15') {\n x = '15N';\n }\n return x;\n });\n newInfo.sampleName = info.sampleName;\n newInfo.date = JSON.stringify(info.creationTime);\n newInfo.author = info.author;\n //newInfo.comment = info.comment;\n newInfo.solvent = info.solvent;\n newInfo.temperature = info.temperature.magnitude;\n newInfo.probeName = info.probeId;\n newInfo.fieldStrength = info.fieldStrength.magnitude;\n newInfo.baseFrequency = info.fieldStrength.magnitude * 42.577478518;\n newInfo.pulseSequence = info.experiment;\n newInfo.temperature = info.temperature.magnitude;\n newInfo.digitalFilter = 19;\n newInfo.pulseStrength90 = 1 / (4 * info.pulseStrength90.magnitude);\n newInfo.numberOfScans = info.numberOfScans;\n newInfo.relaxationTime = info.relaxationTime;\n\n newInfo.isComplex = info.dataSections.includes('im');\n newInfo.isFid = info.dataUnits[0] === 'Second';\n newInfo.isFt = info.dataUnits[0] === 'Ppm';\n\n newInfo.dimension = info.dimension;\n newInfo.originFrequency = info.originFrequency\n .map((d) => d.magnitude / 1e6)\n .slice(0, 1);\n newInfo.numberOfPoints = info.dataPoints.slice(0, 1);\n newInfo.frequencyOffset = info.frequencyOffset\n .map((f) => f.magnitude * newInfo.baseFrequency)\n .slice(0, 1);\n newInfo.acquisitionTime = info.acquisitionTime\n .map((a) => a.magnitude)\n .slice(0, 1);\n newInfo.spectralWidth =\n (info.spectralWidth[0].magnitude / info.originFrequency[0].magnitude) * 1e6;\n\n // set options for dimensions\n let dimensions = [];\n let options = {};\n let increment;\n for (let d = 0; d < info.dimension; d++) {\n increment = {\n magnitude: info.acquisitionTime[d].magnitude / (info.dataPoints[d] - 1),\n unit: 's',\n };\n if (info.dataUnits[d] === 'Second') {\n options.quantityName = 'time';\n options.originOffset = { magnitude: 0, unit: 's' };\n if (d === 0) {\n options.coordinatesOffset = {\n magnitude: info.digitalFilter * increment,\n unit: 's',\n };\n } else {\n options.coordinatesOffset = { magnitude: 0, unit: 's' };\n }\n options.reciprocal = {\n originOffset: {\n magnitude: info.originFrequency[d].magnitude,\n unit: 'Hz',\n },\n quantityName: 'frequency',\n coordinatesOffset: {\n magnitude:\n (info.frequencyOffset[d].magnitude *\n info.originFrequency[d].magnitude) /\n 1000000,\n unit: 'Hz',\n },\n };\n } else if (info.dataUnits[d] === 'Ppm') {\n options.quantityName = 'frequency';\n\n let origin = info.originFrequency[d].magnitude;\n options.originOffset = { magnitude: origin, unit: 'Hz' };\n\n let firstPoint = info.dataOffsetStart[0];\n let lastPoint = info.dataOffsetStop[0];\n let dataLength = lastPoint - firstPoint + 1;\n\n let spectralWidth = info.spectralWidth[d].magnitude;\n let incr = spectralWidth / info.dataPoints[d];\n increment = { magnitude: incr, unit: 'Hz' };\n\n let offset = (info.dataAxisStop[0] * origin) / 1000000;\n options.coordinatesOffset = {\n magnitude: offset,\n unit: 'Hz',\n };\n\n // after increment is computed with whole frequency\n // and original number of points, we recast the\n // number of point for export\n if (dataLength < info.dataPoints[d]) {\n info.dataPoints[d] = dataLength;\n }\n }\n\n if (d === 0) {\n options.description = 'direct dimension';\n } else {\n options.description = 'indirect dimension';\n }\n\n dimensions.push(\n formatLinearDimension(\n headers.dataAxisTitles[d],\n info.dataPoints[d],\n increment,\n options,\n ),\n );\n }\n\n // set options for dependentVariable\n options = {\n unit: 'none',\n quantityName: 'relative intensity',\n from: info.dataOffsetStart,\n to: info.dataOffsetStop,\n };\n\n let dependentVariables = [];\n dependentVariables.push(formatDependentVariable(data, 11, options));\n\n // let description = {};\n // for (let key in newInfo) {\n // description[key] = newInfo[key];\n // }\n\n let description = Object.assign({}, newInfo);\n\n delete description.paramList;\n description.metadata = Object.assign(\n {},\n toKeyValue(headers),\n toKeyValue(parameters),\n toKeyValue(paramArray),\n );\n\n let dataStructure = {\n timeStamp: new Date().valueOf(),\n version: [{ 'nmr-parser': version }, dependencies, devDependencies],\n description,\n tags: ['magnetic resonance'].concat(newInfo.nucleus),\n application: {\n spectralWidthClipped:\n info.spectralWidthClipped[0].magnitude / newInfo.baseFrequency[0],\n },\n dimensions: dimensions,\n dependentVariables: dependentVariables,\n };\n return dataStructure;\n}\n","const GC_MS_FIELDS = ['TIC', '.RIC', 'SCANNUMBER'];\n\nexport function complexChromatogram(result) {\n let spectra = result.spectra;\n let length = spectra.length;\n let chromatogram = {\n times: new Array(length),\n series: {\n ms: {\n dimension: 2,\n data: new Array(length),\n },\n },\n };\n\n let existingGCMSFields = [];\n for (let i = 0; i < GC_MS_FIELDS.length; i++) {\n let label = convertMSFieldToLabel(GC_MS_FIELDS[i]);\n if (spectra[0][label]) {\n existingGCMSFields.push(label);\n chromatogram.series[label] = {\n dimension: 1,\n data: new Array(length),\n };\n }\n }\n\n for (let i = 0; i < length; i++) {\n let spectrum = spectra[i];\n chromatogram.times[i] = spectrum.pageValue;\n for (let j = 0; j < existingGCMSFields.length; j++) {\n chromatogram.series[existingGCMSFields[j]].data[i] = parseFloat(\n spectrum[existingGCMSFields[j]],\n );\n }\n if (spectrum.data) {\n chromatogram.series.ms.data[i] = [spectrum.data.x, spectrum.data.y];\n }\n }\n result.chromatogram = chromatogram;\n}\n\nexport function isMSField(canonicDataLabel) {\n return GC_MS_FIELDS.indexOf(canonicDataLabel) !== -1;\n}\n\nexport function convertMSFieldToLabel(value) {\n return value.toLowerCase().replace(/[^a-z0-9]/g, '');\n}\n","export default function convertToFloatArray(stringArray) {\n let floatArray = [];\n for (let i = 0; i < stringArray.length; i++) {\n floatArray.push(parseFloat(stringArray[i]));\n }\n return floatArray;\n}\n","export default function fastParseXYData(spectrum, value) {\n // TODO need to deal with result\n // console.log(value);\n // we check if deltaX is defined otherwise we calculate it\n\n let yFactor = spectrum.yFactor;\n let deltaX = spectrum.deltaX;\n\n spectrum.isXYdata = true;\n // TODO to be improved using 2 array {x:[], y:[]}\n let currentData = [];\n spectrum.data = currentData;\n\n let currentX = spectrum.firstX;\n let currentY = spectrum.firstY;\n\n // we skip the first line\n //\n let endLine = false;\n let ascii;\n let i = 0;\n for (; i < value.length; i++) {\n ascii = value.charCodeAt(i);\n if (ascii === 13 || ascii === 10) {\n endLine = true;\n } else {\n if (endLine) break;\n }\n }\n\n // we proceed taking the i after the first line\n let newLine = true;\n let isDifference = false;\n let isLastDifference = false;\n let lastDifference = 0;\n let isDuplicate = false;\n let inComment = false;\n let currentValue = 0; // can be a difference or a duplicate\n let lastValue = 0; // must be the real last value\n let isNegative = false;\n let inValue = false;\n let skipFirstValue = false;\n let decimalPosition = 0;\n for (; i <= value.length; i++) {\n if (i === value.length) ascii = 13;\n else ascii = value.charCodeAt(i);\n if (inComment) {\n // we should ignore the text if we are after $$\n if (ascii === 13 || ascii === 10) {\n newLine = true;\n inComment = false;\n }\n } else {\n // when is it a new value ?\n // when it is not a digit, . or comma\n // it is a number that is either new or we continue\n if (ascii <= 57 && ascii >= 48) {\n // a number\n inValue = true;\n if (decimalPosition > 0) {\n currentValue += (ascii - 48) / Math.pow(10, decimalPosition++);\n } else {\n currentValue *= 10;\n currentValue += ascii - 48;\n }\n } else if (ascii === 44 || ascii === 46) {\n // a \",\" or \".\"\n inValue = true;\n decimalPosition++;\n } else {\n if (inValue) {\n // need to process the previous value\n if (newLine) {\n newLine = false; // we don't check the X value\n // console.log(\"NEW LINE\",isDifference, lastDifference);\n // if new line and lastDifference, the first value is just a check !\n // that we don't check ...\n if (isLastDifference) skipFirstValue = true;\n } else {\n // need to deal with duplicate and differences\n if (skipFirstValue) {\n skipFirstValue = false;\n } else {\n if (isDifference) {\n lastDifference = isNegative ? 0 - currentValue : currentValue;\n isLastDifference = true;\n isDifference = false;\n } else if (!isDuplicate) {\n lastValue = isNegative ? 0 - currentValue : currentValue;\n }\n let duplicate = isDuplicate ? currentValue - 1 : 1;\n for (let j = 0; j < duplicate; j++) {\n if (isLastDifference) {\n currentY += lastDifference;\n } else {\n currentY = lastValue;\n }\n currentData.push(currentX);\n currentData.push(currentY * yFactor);\n currentX += deltaX;\n }\n }\n }\n isNegative = false;\n currentValue = 0;\n decimalPosition = 0;\n inValue = false;\n isDuplicate = false;\n }\n\n // positive SQZ digits @ A B C D E F G H I (ascii 64-73)\n if (ascii < 74 && ascii > 63) {\n inValue = true;\n isLastDifference = false;\n currentValue = ascii - 64;\n } else if (ascii > 96 && ascii < 106) {\n // negative SQZ digits a b c d e f g h i (ascii 97-105)\n inValue = true;\n isLastDifference = false;\n currentValue = ascii - 96;\n isNegative = true;\n } else if (ascii === 115) {\n // DUP digits S T U V W X Y Z s (ascii 83-90, 115)\n inValue = true;\n isDuplicate = true;\n currentValue = 9;\n } else if (ascii > 82 && ascii < 91) {\n inValue = true;\n isDuplicate = true;\n currentValue = ascii - 82;\n } else if (ascii > 73 && ascii < 83) {\n // positive DIF digits % J K L M N O P Q R (ascii 37, 74-82)\n inValue = true;\n isDifference = true;\n currentValue = ascii - 73;\n } else if (ascii > 105 && ascii < 115) {\n // negative DIF digits j k l m n o p q r (ascii 106-114)\n inValue = true;\n isDifference = true;\n currentValue = ascii - 105;\n isNegative = true;\n } else if (ascii === 36 && value.charCodeAt(i + 1) === 36) {\n // $ sign, we need to check the next one\n inValue = true;\n inComment = true;\n } else if (ascii === 37) {\n // positive DIF digits % J K L M N O P Q R (ascii 37, 74-82)\n inValue = true;\n isDifference = true;\n currentValue = 0;\n isNegative = false;\n } else if (ascii === 45) {\n // a \"-\"\n // check if after there is a number, decimal or comma\n let ascii2 = value.charCodeAt(i + 1);\n if (\n (ascii2 >= 48 && ascii2 <= 57) ||\n ascii2 === 44 ||\n ascii2 === 46\n ) {\n inValue = true;\n if (!newLine) isLastDifference = false;\n isNegative = true;\n }\n } else if (ascii === 13 || ascii === 10) {\n newLine = true;\n inComment = false;\n }\n // and now analyse the details ... space or tabulation\n // if \"+\" we just don't care\n }\n }\n }\n}\n","export default function parsePeakTable(spectrum, value, result) {\n let removeCommentRegExp = /\\$\\$.*/;\n let peakTableSplitRegExp = /[,\\t ]+/;\n\n spectrum.isPeaktable = true;\n let values;\n let currentData = [];\n spectrum.data = currentData;\n\n // counts for around 20% of the time\n let lines = value.split(/,? *,?[;\\r\\n]+ */);\n\n for (let i = 1; i < lines.length; i++) {\n values = lines[i]\n .trim()\n .replace(removeCommentRegExp, '')\n .split(peakTableSplitRegExp);\n if (values.length % 2 === 0) {\n for (let j = 0; j < values.length; j = j + 2) {\n // takes around 40% of the time to add and parse the 2 values nearly exclusively because of parseFloat\n currentData.push(parseFloat(values[j]) * spectrum.xFactor);\n currentData.push(parseFloat(values[j + 1]) * spectrum.yFactor);\n }\n } else {\n result.logs.push(`Format error: ${values}`);\n }\n }\n}\n","export default function parseXYA(spectrum, value) {\n let removeSymbolRegExp = /(\\(+|\\)+|<+|>+|\\s+)/g;\n\n spectrum.isXYAdata = true;\n let values;\n let currentData = [];\n spectrum.data = currentData;\n\n let lines = value.split(/,? *,?[;\\r\\n]+ */);\n\n for (let i = 1; i < lines.length; i++) {\n values = lines[i].trim().replace(removeSymbolRegExp, '').split(',');\n currentData.push(parseFloat(values[0]));\n currentData.push(parseFloat(values[1]));\n }\n}\n","'use strict';\n\nconst toString = Object.prototype.toString;\n\nfunction isAnyArray(object) {\n return toString.call(object).endsWith('Array]');\n}\n\nmodule.exports = isAnyArray;\n","(function(){function a(d){for(var e=0,f=d.length-1,g=void 0,h=void 0,i=void 0,j=c(e,f);!0;){if(f<=e)return d[j];if(f==e+1)return d[e]>d[f]&&b(d,e,f),d[j];for(g=c(e,f),d[g]>d[f]&&b(d,g,f),d[e]>d[f]&&b(d,e,f),d[g]>d[e]&&b(d,g,e),b(d,g,e+1),h=e+1,i=f;!0;){do h++;while(d[e]>d[h]);do i--;while(d[i]>d[e]);if(i=j&&(f=i-1)}}var b=function b(d,e,f){var _ref;return _ref=[d[f],d[e]],d[e]=_ref[0],d[f]=_ref[1],_ref},c=function c(d,e){return~~((d+e)/2)};'undefined'!=typeof module&&module.exports?module.exports=a:window.median=a})();\n","import isArray from 'is-any-array';\nimport quickSelectMedian from 'median-quickselect';\n\n/**\n * Computes the median of the given values\n * @param {Array} input\n * @return {number}\n */\n\nfunction median(input) {\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n }\n\n if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n return quickSelectMedian(input.slice());\n}\n\nexport default median;\n","import getMedian from 'ml-array-median';\n\nexport default function convertTo3DZ(spectra) {\n let minZ = spectra[0].data[0];\n let maxZ = minZ;\n let ySize = spectra.length;\n let xSize = spectra[0].data.length / 2;\n let z = new Array(ySize);\n for (let i = 0; i < ySize; i++) {\n z[i] = new Array(xSize);\n let xVector = spectra[i].data;\n for (let j = 0; j < xSize; j++) {\n let value = xVector[j * 2 + 1];\n z[i][j] = value;\n if (value < minZ) minZ = value;\n if (value > maxZ) maxZ = value;\n }\n }\n\n const firstX = spectra[0].data[0];\n const lastX = spectra[0].data[spectra[0].data.length - 2]; // has to be -2 because it is a 1D array [x,y,x,y,...]\n const firstY = spectra[0].pageValue;\n const lastY = spectra[ySize - 1].pageValue;\n\n // Because the min / max value are the only information about the matrix if we invert\n // min and max we need to invert the array\n if (firstX > lastX) {\n for (let spectrum of z) {\n spectrum.reverse();\n }\n }\n if (firstY > lastY) {\n z.reverse();\n }\n\n return {\n z: z,\n minX: Math.min(firstX, lastX),\n maxX: Math.max(firstX, lastX),\n minY: Math.min(firstY, lastY),\n maxY: Math.max(firstY, lastY),\n minZ: minZ,\n maxZ: maxZ,\n noise: getMedian(z[0].map(Math.abs)),\n };\n}\n","export default function generateContourLines(zData, options) {\n let noise = zData.noise;\n let z = zData.z;\n let povarHeight0, povarHeight1, povarHeight2, povarHeight3;\n let isOver0, isOver1, isOver2, isOver3;\n let nbSubSpectra = z.length;\n let nbPovars = z[0].length;\n let pAx, pAy, pBx, pBy;\n\n let x0 = zData.minX;\n let xN = zData.maxX;\n let dx = (xN - x0) / (nbPovars - 1);\n let y0 = zData.minY;\n let yN = zData.maxY;\n let dy = (yN - y0) / (nbSubSpectra - 1);\n let minZ = zData.minZ;\n let maxZ = zData.maxZ;\n\n // System.out.prvarln('y0 '+y0+' yN '+yN);\n // -------------------------\n // Povars attribution\n //\n // 0----1\n // | / |\n // | / |\n // 2----3\n //\n // ---------------------d------\n\n let iter = options.nbContourLevels * 2;\n let contourLevels = new Array(iter);\n let lineZValue;\n for (let level = 0; level < iter; level++) {\n // multiply by 2 for positif and negatif\n let contourLevel = {};\n contourLevels[level] = contourLevel;\n let side = level % 2;\n let factor =\n (maxZ - options.noiseMultiplier * noise) *\n Math.exp((level >> 1) - options.nbContourLevels);\n if (side === 0) {\n lineZValue = factor + options.noiseMultiplier * noise;\n } else {\n lineZValue = 0 - factor - options.noiseMultiplier * noise;\n }\n let lines = [];\n contourLevel.zValue = lineZValue;\n contourLevel.lines = lines;\n\n if (lineZValue <= minZ || lineZValue >= maxZ) continue;\n\n for (let iSubSpectra = 0; iSubSpectra < nbSubSpectra - 1; iSubSpectra++) {\n let subSpectra = z[iSubSpectra];\n let subSpectraAfter = z[iSubSpectra + 1];\n for (let povar = 0; povar < nbPovars - 1; povar++) {\n povarHeight0 = subSpectra[povar];\n povarHeight1 = subSpectra[povar + 1];\n povarHeight2 = subSpectraAfter[povar];\n povarHeight3 = subSpectraAfter[povar + 1];\n\n isOver0 = povarHeight0 > lineZValue;\n isOver1 = povarHeight1 > lineZValue;\n isOver2 = povarHeight2 > lineZValue;\n isOver3 = povarHeight3 > lineZValue;\n\n // Example povar0 is over the plane and povar1 and\n // povar2 are below, we find the varersections and add\n // the segment\n if (isOver0 !== isOver1 && isOver0 !== isOver2) {\n pAx =\n povar + (lineZValue - povarHeight0) / (povarHeight1 - povarHeight0);\n pAy = iSubSpectra;\n pBx = povar;\n pBy =\n iSubSpectra +\n (lineZValue - povarHeight0) / (povarHeight2 - povarHeight0);\n lines.push(pAx * dx + x0);\n lines.push(pAy * dy + y0);\n lines.push(pBx * dx + x0);\n lines.push(pBy * dy + y0);\n }\n // remove push does not help !!!!\n if (isOver3 !== isOver1 && isOver3 !== isOver2) {\n pAx = povar + 1;\n pAy =\n iSubSpectra +\n 1 -\n (lineZValue - povarHeight3) / (povarHeight1 - povarHeight3);\n pBx =\n povar +\n 1 -\n (lineZValue - povarHeight3) / (povarHeight2 - povarHeight3);\n pBy = iSubSpectra + 1;\n lines.push(pAx * dx + x0);\n lines.push(pAy * dy + y0);\n lines.push(pBx * dx + x0);\n lines.push(pBy * dy + y0);\n }\n // test around the diagonal\n if (isOver1 !== isOver2) {\n pAx =\n (povar +\n 1 -\n (lineZValue - povarHeight1) / (povarHeight2 - povarHeight1)) *\n dx +\n x0;\n pAy =\n (iSubSpectra +\n (lineZValue - povarHeight1) / (povarHeight2 - povarHeight1)) *\n dy +\n y0;\n if (isOver1 !== isOver0) {\n pBx =\n povar +\n 1 -\n (lineZValue - povarHeight1) / (povarHeight0 - povarHeight1);\n pBy = iSubSpectra;\n lines.push(pAx);\n lines.push(pAy);\n lines.push(pBx * dx + x0);\n lines.push(pBy * dy + y0);\n }\n if (isOver2 !== isOver0) {\n pBx = povar;\n pBy =\n iSubSpectra +\n 1 -\n (lineZValue - povarHeight2) / (povarHeight0 - povarHeight2);\n lines.push(pAx);\n lines.push(pAy);\n lines.push(pBx * dx + x0);\n lines.push(pBy * dy + y0);\n }\n if (isOver1 !== isOver3) {\n pBx = povar + 1;\n pBy =\n iSubSpectra +\n (lineZValue - povarHeight1) / (povarHeight3 - povarHeight1);\n lines.push(pAx);\n lines.push(pAy);\n lines.push(pBx * dx + x0);\n lines.push(pBy * dy + y0);\n }\n if (isOver2 !== isOver3) {\n pBx =\n povar +\n (lineZValue - povarHeight2) / (povarHeight3 - povarHeight2);\n pBy = iSubSpectra + 1;\n lines.push(pAx);\n lines.push(pAy);\n lines.push(pBx * dx + x0);\n lines.push(pBy * dy + y0);\n }\n }\n }\n }\n }\n\n return {\n minX: zData.minX,\n maxX: zData.maxX,\n minY: zData.minY,\n maxY: zData.maxY,\n segments: contourLevels,\n };\n}\n","import convertTo3DZ from './convertTo3DZ';\nimport generateContourLines from './generateContourLines';\n\nexport default function add2D(result, options) {\n let zData = convertTo3DZ(result.spectra);\n if (!options.noContour) {\n result.contourLines = generateContourLines(zData, options);\n delete zData.z;\n }\n result.minMax = zData;\n}\n","export default function profiling(result, action, options) {\n if (result.profiling) {\n result.profiling.push({\n action,\n time: Date.now() - options.start,\n });\n }\n}\n","export default function simpleChromatogram(result) {\n let data = result.spectra[0].data;\n result.chromatogram = {\n times: data.x.slice(),\n series: {\n intensity: {\n dimension: 1,\n data: data.y.slice(),\n },\n },\n };\n}\n","import add2D from './2d/add2D';\nimport { complexChromatogram } from './complexChromatogram';\nimport profiling from './profiling';\nimport simpleChromatogram from './simpleChromatogram';\n\nexport default function postProcessing(entriesFlat, result, options) {\n for (let entry of entriesFlat) {\n if (Object.keys(entry.ntuples).length > 0) {\n let newNtuples = [];\n let keys = Object.keys(entry.ntuples);\n for (let i = 0; i < keys.length; i++) {\n let key = keys[i];\n let values = entry.ntuples[key];\n for (let j = 0; j < values.length; j++) {\n if (!newNtuples[j]) newNtuples[j] = {};\n newNtuples[j][key] = values[j];\n }\n }\n entry.ntuples = newNtuples;\n }\n\n if (entry.twoD && options.wantXY) {\n add2D(entry, options);\n\n profiling(result, 'Finished countour plot calculation', options);\n\n if (!options.keepSpectra) {\n delete entry.spectra;\n }\n }\n\n if (options.chromatogram) {\n options.xy = true;\n }\n\n if (options.xy && options.wantXY) {\n // the spectraData should not be a oneD array but an object with x and y\n if (entry.spectra && entry.spectra.length > 0) {\n for (let spectrum of entry.spectra) {\n if (spectrum.data) {\n let data = spectrum.data;\n let newData = {\n x: new Array(data.length / 2),\n y: new Array(data.length / 2),\n };\n for (let k = 0; k < data.length; k = k + 2) {\n newData.x[k / 2] = data[k];\n newData.y[k / 2] = data[k + 1];\n }\n spectrum.data = newData;\n }\n }\n }\n }\n\n // maybe it is a GC (HPLC) / MS. In this case we add a new format\n if (options.chromatogram) {\n if (entry.spectra.length > 1) {\n complexChromatogram(entry);\n } else {\n simpleChromatogram(entry);\n }\n profiling(result, 'Finished chromatogram calculation', options);\n }\n }\n}\n","export default function prepareSpectrum(spectrum) {\n if (!spectrum.xFactor) spectrum.xFactor = 1;\n if (!spectrum.yFactor) spectrum.yFactor = 1;\n if (spectrum.observeFrequency) {\n if (spectrum.xUnit && spectrum.xUnit.toUpperCase() === 'HZ') {\n spectrum.xUnit = 'PPM';\n spectrum.xFactor = spectrum.xFactor / spectrum.observeFrequency;\n spectrum.firstX = spectrum.firstX / spectrum.observeFrequency;\n spectrum.lastX = spectrum.lastX / spectrum.observeFrequency;\n spectrum.deltaX = spectrum.deltaX / spectrum.observeFrequency;\n }\n }\n if (spectrum.shiftOffsetVal) {\n let shift = spectrum.firstX - spectrum.shiftOffsetVal;\n spectrum.firstX = spectrum.firstX - shift;\n spectrum.lastX = spectrum.lastX - shift;\n }\n}\n","import { isMSField, convertMSFieldToLabel } from './complexChromatogram';\nimport convertToFloatArray from './convertToFloatArray';\nimport fastParseXYData from './parse/fastParseXYData';\nimport parsePeakTable from './parse/parsePeakTable';\nimport parseXYA from './parse/parseXYA';\nimport postProcessing from './postProcessing';\nimport prepareSpectrum from './prepareSpectrum';\nimport profiling from './profiling';\n\n// the following RegExp can only be used for XYdata, some peakTables have values with a \"E-5\" ...\nconst ntuplesSeparator = /[, \\t]+/;\n\nclass Spectrum {}\n\nconst defaultOptions = {\n keepRecordsRegExp: /^$/,\n canonicDataLabels: true,\n dynamicTyping: false,\n xy: true,\n withoutXY: false,\n chromatogram: false,\n keepSpectra: false,\n noContour: false,\n nbContourLevels: 7,\n noiseMultiplier: 5,\n profiling: false,\n};\n\nexport default function convert(jcamp, options) {\n options = Object.assign({}, defaultOptions, options);\n options.wantXY = !options.withoutXY;\n options.start = Date.now();\n\n let entriesFlat = [];\n\n let result = {\n profiling: options.profiling ? [] : false,\n logs: [],\n entries: [],\n };\n\n let tmpResult = { children: [] };\n let currentEntry = tmpResult;\n let parentsStack = [];\n\n let spectrum = new Spectrum();\n\n if (typeof jcamp !== 'string') {\n throw new TypeError('the JCAMP should be a string');\n }\n\n profiling(result, 'Before split to LDRS', options);\n\n let ldrs = jcamp.replace(/[\\r\\n]+##/g, '\\n##').split('\\n##');\n\n profiling(result, 'Split to LDRS', options);\n\n if (ldrs[0]) ldrs[0] = ldrs[0].replace(/^[\\r\\n ]*##/, '');\n\n for (let ldr of ldrs) {\n // This is a new LDR\n let position = ldr.indexOf('=');\n let dataLabel = position > 0 ? ldr.substring(0, position) : ldr;\n let dataValue = position > 0 ? ldr.substring(position + 1).trim() : '';\n\n let canonicDataLabel = dataLabel.replace(/[_ -]/g, '').toUpperCase();\n\n if (canonicDataLabel === 'DATATABLE') {\n let endLine = dataValue.indexOf('\\n');\n if (endLine === -1) endLine = dataValue.indexOf('\\r');\n if (endLine > 0) {\n let xIndex = -1;\n let yIndex = -1;\n // ##DATA TABLE= (X++(I..I)), XYDATA\n // We need to find the variables\n\n let infos = dataValue.substring(0, endLine).split(/[ ,;\\t]+/);\n if (infos[0].indexOf('++') > 0) {\n let firstVariable = infos[0].replace(\n /.*\\(([a-zA-Z0-9]+)\\+\\+.*/,\n '$1',\n );\n let secondVariable = infos[0].replace(/.*\\.\\.([a-zA-Z0-9]+).*/, '$1');\n xIndex = currentEntry.ntuples.symbol.indexOf(firstVariable);\n yIndex = currentEntry.ntuples.symbol.indexOf(secondVariable);\n }\n\n if (xIndex === -1) xIndex = 0;\n if (yIndex === -1) yIndex = 0;\n\n if (currentEntry.ntuples.first) {\n if (currentEntry.ntuples.first.length > xIndex) {\n spectrum.firstX = currentEntry.ntuples.first[xIndex];\n }\n if (currentEntry.ntuples.first.length > yIndex) {\n spectrum.firstY = currentEntry.ntuples.first[yIndex];\n }\n }\n if (currentEntry.ntuples.last) {\n if (currentEntry.ntuples.last.length > xIndex) {\n spectrum.lastX = currentEntry.ntuples.last[xIndex];\n }\n if (currentEntry.ntuples.last.length > yIndex) {\n spectrum.lastY = currentEntry.ntuples.last[yIndex];\n }\n }\n if (\n currentEntry.ntuples.vardim &&\n currentEntry.ntuples.vardim.length > xIndex\n ) {\n spectrum.nbPoints = currentEntry.ntuples.vardim[xIndex];\n }\n if (currentEntry.ntuples.factor) {\n if (currentEntry.ntuples.factor.length > xIndex) {\n spectrum.xFactor = currentEntry.ntuples.factor[xIndex];\n }\n if (currentEntry.ntuples.factor.length > yIndex) {\n spectrum.yFactor = currentEntry.ntuples.factor[yIndex];\n }\n }\n if (currentEntry.ntuples.units) {\n if (currentEntry.ntuples.units.length > xIndex) {\n spectrum.xUnit = currentEntry.ntuples.units[xIndex];\n }\n if (currentEntry.ntuples.units.length > yIndex) {\n spectrum.yUnit = currentEntry.ntuples.units[yIndex];\n }\n }\n spectrum.datatable = infos[0];\n if (infos[1] && infos[1].indexOf('PEAKS') > -1) {\n canonicDataLabel = 'PEAKTABLE';\n } else if (\n infos[1] &&\n (infos[1].indexOf('XYDATA') || infos[0].indexOf('++') > 0)\n ) {\n canonicDataLabel = 'XYDATA';\n spectrum.deltaX =\n (spectrum.lastX - spectrum.firstX) / (spectrum.nbPoints - 1);\n }\n }\n }\n\n if (canonicDataLabel === 'XYDATA') {\n if (options.wantXY) {\n prepareSpectrum(spectrum);\n // well apparently we should still consider it is a PEAK TABLE if there are no '++' after\n if (dataValue.match(/.*\\+\\+.*/)) {\n // ex: (X++(Y..Y))\n if (!spectrum.deltaX) {\n spectrum.deltaX =\n (spectrum.lastX - spectrum.firstX) / (spectrum.nbPoints - 1);\n }\n fastParseXYData(spectrum, dataValue, result);\n } else {\n parsePeakTable(spectrum, dataValue, result);\n }\n currentEntry.spectra.push(spectrum);\n spectrum = new Spectrum();\n }\n continue;\n } else if (canonicDataLabel === 'PEAKTABLE') {\n if (options.wantXY) {\n prepareSpectrum(spectrum);\n parsePeakTable(spectrum, dataValue, result);\n currentEntry.spectra.push(spectrum);\n spectrum = new Spectrum();\n }\n continue;\n }\n if (canonicDataLabel === 'PEAKASSIGNMENTS') {\n if (options.wantXY) {\n if (dataValue.match(/.*(XYA).*/)) {\n // ex: (XYA)\n parseXYA(spectrum, dataValue);\n }\n currentEntry.spectra.push(spectrum);\n spectrum = new Spectrum();\n }\n continue;\n }\n\n if (canonicDataLabel === 'TITLE') {\n let parentEntry = currentEntry;\n if (!parentEntry.children) {\n parentEntry.children = [];\n }\n currentEntry = {\n spectra: [],\n ntuples: {},\n info: {},\n };\n parentEntry.children.push(currentEntry);\n parentsStack.push(parentEntry);\n entriesFlat.push(currentEntry);\n currentEntry.title = dataValue;\n } else if (canonicDataLabel === 'DATATYPE') {\n currentEntry.dataType = dataValue;\n if (dataValue.indexOf('nD') > -1) {\n currentEntry.twoD = true;\n }\n } else if (canonicDataLabel === 'NTUPLES') {\n if (dataValue.indexOf('nD') > -1) {\n currentEntry.twoD = true;\n }\n } else if (canonicDataLabel === 'DATACLASS') {\n currentEntry.dataClass = dataValue;\n } else if (canonicDataLabel === 'XUNITS') {\n spectrum.xUnit = dataValue;\n } else if (canonicDataLabel === 'YUNITS') {\n spectrum.yUnit = dataValue;\n } else if (canonicDataLabel === 'FIRSTX') {\n spectrum.firstX = parseFloat(dataValue);\n } else if (canonicDataLabel === 'LASTX') {\n spectrum.lastX = parseFloat(dataValue);\n } else if (canonicDataLabel === 'FIRSTY') {\n spectrum.firstY = parseFloat(dataValue);\n } else if (canonicDataLabel === 'LASTY') {\n spectrum.lastY = parseFloat(dataValue);\n } else if (canonicDataLabel === 'NPOINTS') {\n spectrum.nbPoints = parseFloat(dataValue);\n } else if (canonicDataLabel === 'XFACTOR') {\n spectrum.xFactor = parseFloat(dataValue);\n } else if (canonicDataLabel === 'YFACTOR') {\n spectrum.yFactor = parseFloat(dataValue);\n } else if (canonicDataLabel === 'MAXX') {\n spectrum.maxX = parseFloat(dataValue);\n } else if (canonicDataLabel === 'MINX') {\n spectrum.minX = parseFloat(dataValue);\n } else if (canonicDataLabel === 'MAXY') {\n spectrum.maxY = parseFloat(dataValue);\n } else if (canonicDataLabel === 'MINY') {\n spectrum.minY = parseFloat(dataValue);\n } else if (canonicDataLabel === 'DELTAX') {\n spectrum.deltaX = parseFloat(dataValue);\n } else if (\n canonicDataLabel === '.OBSERVEFREQUENCY' ||\n canonicDataLabel === '$SFO1'\n ) {\n if (!spectrum.observeFrequency) {\n spectrum.observeFrequency = parseFloat(dataValue);\n }\n } else if (canonicDataLabel === '.OBSERVENUCLEUS') {\n if (!spectrum.xType) {\n currentEntry.xType = dataValue.replace(/[^a-zA-Z0-9]/g, '');\n }\n } else if (canonicDataLabel === '$SFO2') {\n if (!currentEntry.indirectFrequency) {\n currentEntry.indirectFrequency = parseFloat(dataValue);\n }\n } else if (canonicDataLabel === '$OFFSET') {\n // OFFSET for Bruker spectra\n currentEntry.shiftOffsetNum = 0;\n if (!spectrum.shiftOffsetVal) {\n spectrum.shiftOffsetVal = parseFloat(dataValue);\n }\n } else if (canonicDataLabel === '$REFERENCEPOINT') {\n // OFFSET for Varian spectra\n // if we activate this part it does not work for ACD specmanager\n // } else if (canonicDataLabel=='.SHIFTREFERENCE') { // OFFSET FOR Bruker Spectra\n // var parts = dataValue.split(/ *, */);\n // currentEntry.shiftOffsetNum = parseInt(parts[2].trim());\n // spectrum.shiftOffsetVal = parseFloat(parts[3].trim());\n } else if (canonicDataLabel === 'VARNAME') {\n currentEntry.ntuples.varname = dataValue.split(ntuplesSeparator);\n } else if (canonicDataLabel === 'SYMBOL') {\n currentEntry.ntuples.symbol = dataValue.split(ntuplesSeparator);\n } else if (canonicDataLabel === 'VARTYPE') {\n currentEntry.ntuples.vartype = dataValue.split(ntuplesSeparator);\n } else if (canonicDataLabel === 'VARFORM') {\n currentEntry.ntuples.varform = dataValue.split(ntuplesSeparator);\n } else if (canonicDataLabel === 'VARDIM') {\n currentEntry.ntuples.vardim = convertToFloatArray(\n dataValue.split(ntuplesSeparator),\n );\n } else if (canonicDataLabel === 'UNITS') {\n currentEntry.ntuples.units = dataValue.split(ntuplesSeparator);\n } else if (canonicDataLabel === 'FACTOR') {\n currentEntry.ntuples.factor = convertToFloatArray(\n dataValue.split(ntuplesSeparator),\n );\n } else if (canonicDataLabel === 'FIRST') {\n currentEntry.ntuples.first = convertToFloatArray(\n dataValue.split(ntuplesSeparator),\n );\n } else if (canonicDataLabel === 'LAST') {\n currentEntry.ntuples.last = convertToFloatArray(\n dataValue.split(ntuplesSeparator),\n );\n } else if (canonicDataLabel === 'MIN') {\n currentEntry.ntuples.min = convertToFloatArray(\n dataValue.split(ntuplesSeparator),\n );\n } else if (canonicDataLabel === 'MAX') {\n currentEntry.ntuples.max = convertToFloatArray(\n dataValue.split(ntuplesSeparator),\n );\n } else if (canonicDataLabel === '.NUCLEUS') {\n if (currentEntry.twoD) {\n currentEntry.yType = dataValue.split(ntuplesSeparator)[0];\n }\n } else if (canonicDataLabel === 'PAGE') {\n spectrum.page = dataValue.trim();\n spectrum.pageValue = parseFloat(dataValue.replace(/^.*=/, ''));\n spectrum.pageSymbol = spectrum.page.replace(/[=].*/, '');\n let pageSymbolIndex = currentEntry.ntuples.symbol.indexOf(\n spectrum.pageSymbol,\n );\n let unit = '';\n if (\n currentEntry.ntuples.units &&\n currentEntry.ntuples.units[pageSymbolIndex]\n ) {\n unit = currentEntry.ntuples.units[pageSymbolIndex];\n }\n if (currentEntry.indirectFrequency && unit !== 'PPM') {\n spectrum.pageValue /= currentEntry.indirectFrequency;\n }\n } else if (canonicDataLabel === 'RETENTIONTIME') {\n spectrum.pageValue = parseFloat(dataValue);\n } else if (isMSField(canonicDataLabel)) {\n spectrum[convertMSFieldToLabel(canonicDataLabel)] = dataValue;\n } else if (canonicDataLabel === 'SAMPLEDESCRIPTION') {\n spectrum.sampleDescription = dataValue;\n } else if (canonicDataLabel === 'END') {\n currentEntry = parentsStack.pop();\n }\n\n if (\n currentEntry &&\n currentEntry.info &&\n canonicDataLabel.match(options.keepRecordsRegExp)\n ) {\n let label = options.canonicDataLabels ? canonicDataLabel : dataLabel;\n let value = dataValue.trim();\n if (options.dynamicTyping && !isNaN(value)) {\n value = Number(value);\n }\n if (currentEntry.info[label]) {\n if (!Array.isArray(currentEntry.info[label])) {\n currentEntry.info[label] = [currentEntry.info[label]];\n }\n currentEntry.info[label].push(value);\n } else {\n currentEntry.info[label] = value;\n }\n }\n }\n\n profiling(result, 'Finished parsing', options);\n\n postProcessing(entriesFlat, result, options);\n\n profiling(result, 'Total time', options);\n\n /*\n if (result.children && result.children.length>0) {\n result = { ...result, ...result.children[0] };\n }\n */\n result.entries = tmpResult.children;\n result.flatten = entriesFlat;\n\n return result;\n}\n","/*!\n\nJSZip v3.5.0 - A JavaScript class for generating and reading zip files\n\n\n(c) 2009-2016 Stuart Knightley \nDual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.\n\nJSZip uses the library pako released under the MIT license :\nhttps://github.com/nodeca/pako/blob/master/LICENSE\n*/\n\n(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.JSZip = 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> 2;\n enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);\n enc3 = remainingBytes > 1 ? (((chr2 & 15) << 2) | (chr3 >> 6)) : 64;\n enc4 = remainingBytes > 2 ? (chr3 & 63) : 64;\n\n output.push(_keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4));\n\n }\n\n return output.join(\"\");\n};\n\n// public method for decoding\nexports.decode = function(input) {\n var chr1, chr2, chr3;\n var enc1, enc2, enc3, enc4;\n var i = 0, resultIndex = 0;\n\n var dataUrlPrefix = \"data:\";\n\n if (input.substr(0, dataUrlPrefix.length) === dataUrlPrefix) {\n // This is a common error: people give a data url\n // (data:image/png;base64,iVBOR...) with a {base64: true} and\n // wonders why things don't work.\n // We can detect that the string input looks like a data url but we\n // *can't* be sure it is one: removing everything up to the comma would\n // be too dangerous.\n throw new Error(\"Invalid base64 input, it looks like a data url.\");\n }\n\n input = input.replace(/[^A-Za-z0-9\\+\\/\\=]/g, \"\");\n\n var totalLength = input.length * 3 / 4;\n if(input.charAt(input.length - 1) === _keyStr.charAt(64)) {\n totalLength--;\n }\n if(input.charAt(input.length - 2) === _keyStr.charAt(64)) {\n totalLength--;\n }\n if (totalLength % 1 !== 0) {\n // totalLength is not an integer, the length does not match a valid\n // base64 content. That can happen if:\n // - the input is not a base64 content\n // - the input is *almost* a base64 content, with a extra chars at the\n // beginning or at the end\n // - the input uses a base64 variant (base64url for example)\n throw new Error(\"Invalid base64 input, bad content length.\");\n }\n var output;\n if (support.uint8array) {\n output = new Uint8Array(totalLength|0);\n } else {\n output = new Array(totalLength|0);\n }\n\n while (i < input.length) {\n\n enc1 = _keyStr.indexOf(input.charAt(i++));\n enc2 = _keyStr.indexOf(input.charAt(i++));\n enc3 = _keyStr.indexOf(input.charAt(i++));\n enc4 = _keyStr.indexOf(input.charAt(i++));\n\n chr1 = (enc1 << 2) | (enc2 >> 4);\n chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);\n chr3 = ((enc3 & 3) << 6) | enc4;\n\n output[resultIndex++] = chr1;\n\n if (enc3 !== 64) {\n output[resultIndex++] = chr2;\n }\n if (enc4 !== 64) {\n output[resultIndex++] = chr3;\n }\n\n }\n\n return output;\n};\n\n},{\"./support\":30,\"./utils\":32}],2:[function(require,module,exports){\n'use strict';\n\nvar external = require(\"./external\");\nvar DataWorker = require('./stream/DataWorker');\nvar DataLengthProbe = require('./stream/DataLengthProbe');\nvar Crc32Probe = require('./stream/Crc32Probe');\nvar DataLengthProbe = require('./stream/DataLengthProbe');\n\n/**\n * Represent a compressed object, with everything needed to decompress it.\n * @constructor\n * @param {number} compressedSize the size of the data compressed.\n * @param {number} uncompressedSize the size of the data after decompression.\n * @param {number} crc32 the crc32 of the decompressed file.\n * @param {object} compression the type of compression, see lib/compressions.js.\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the compressed data.\n */\nfunction CompressedObject(compressedSize, uncompressedSize, crc32, compression, data) {\n this.compressedSize = compressedSize;\n this.uncompressedSize = uncompressedSize;\n this.crc32 = crc32;\n this.compression = compression;\n this.compressedContent = data;\n}\n\nCompressedObject.prototype = {\n /**\n * Create a worker to get the uncompressed content.\n * @return {GenericWorker} the worker.\n */\n getContentWorker : function () {\n var worker = new DataWorker(external.Promise.resolve(this.compressedContent))\n .pipe(this.compression.uncompressWorker())\n .pipe(new DataLengthProbe(\"data_length\"));\n\n var that = this;\n worker.on(\"end\", function () {\n if(this.streamInfo['data_length'] !== that.uncompressedSize) {\n throw new Error(\"Bug : uncompressed data size mismatch\");\n }\n });\n return worker;\n },\n /**\n * Create a worker to get the compressed content.\n * @return {GenericWorker} the worker.\n */\n getCompressedWorker : function () {\n return new DataWorker(external.Promise.resolve(this.compressedContent))\n .withStreamInfo(\"compressedSize\", this.compressedSize)\n .withStreamInfo(\"uncompressedSize\", this.uncompressedSize)\n .withStreamInfo(\"crc32\", this.crc32)\n .withStreamInfo(\"compression\", this.compression)\n ;\n }\n};\n\n/**\n * Chain the given worker with other workers to compress the content with the\n * given compression.\n * @param {GenericWorker} uncompressedWorker the worker to pipe.\n * @param {Object} compression the compression object.\n * @param {Object} compressionOptions the options to use when compressing.\n * @return {GenericWorker} the new worker compressing the content.\n */\nCompressedObject.createWorkerFrom = function (uncompressedWorker, compression, compressionOptions) {\n return uncompressedWorker\n .pipe(new Crc32Probe())\n .pipe(new DataLengthProbe(\"uncompressedSize\"))\n .pipe(compression.compressWorker(compressionOptions))\n .pipe(new DataLengthProbe(\"compressedSize\"))\n .withStreamInfo(\"compression\", compression);\n};\n\nmodule.exports = CompressedObject;\n\n},{\"./external\":6,\"./stream/Crc32Probe\":25,\"./stream/DataLengthProbe\":26,\"./stream/DataWorker\":27}],3:[function(require,module,exports){\n'use strict';\n\nvar GenericWorker = require(\"./stream/GenericWorker\");\n\nexports.STORE = {\n magic: \"\\x00\\x00\",\n compressWorker : function (compressionOptions) {\n return new GenericWorker(\"STORE compression\");\n },\n uncompressWorker : function () {\n return new GenericWorker(\"STORE decompression\");\n }\n};\nexports.DEFLATE = require('./flate');\n\n},{\"./flate\":7,\"./stream/GenericWorker\":28}],4:[function(require,module,exports){\n'use strict';\n\nvar utils = require('./utils');\n\n/**\n * The following functions come from pako, from pako/lib/zlib/crc32.js\n * released under the MIT license, see pako https://github.com/nodeca/pako/\n */\n\n// Use ordinary array, since untyped makes no boost here\nfunction makeTable() {\n var c, table = [];\n\n for(var n =0; n < 256; n++){\n c = n;\n for(var k =0; k < 8; k++){\n c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));\n }\n table[n] = c;\n }\n\n return table;\n}\n\n// Create table on load. Just 255 signed longs. Not a problem.\nvar crcTable = makeTable();\n\n\nfunction crc32(crc, buf, len, pos) {\n var t = crcTable, end = pos + len;\n\n crc = crc ^ (-1);\n\n for (var i = pos; i < end; i++ ) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\n// That's all for the pako functions.\n\n/**\n * Compute the crc32 of a string.\n * This is almost the same as the function crc32, but for strings. Using the\n * same function for the two use cases leads to horrible performances.\n * @param {Number} crc the starting value of the crc.\n * @param {String} str the string to use.\n * @param {Number} len the length of the string.\n * @param {Number} pos the starting position for the crc32 computation.\n * @return {Number} the computed crc32.\n */\nfunction crc32str(crc, str, len, pos) {\n var t = crcTable, end = pos + len;\n\n crc = crc ^ (-1);\n\n for (var i = pos; i < end; i++ ) {\n crc = (crc >>> 8) ^ t[(crc ^ str.charCodeAt(i)) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n}\n\nmodule.exports = function crc32wrapper(input, crc) {\n if (typeof input === \"undefined\" || !input.length) {\n return 0;\n }\n\n var isArray = utils.getTypeOf(input) !== \"string\";\n\n if(isArray) {\n return crc32(crc|0, input, input.length, 0);\n } else {\n return crc32str(crc|0, input, input.length, 0);\n }\n};\n\n},{\"./utils\":32}],5:[function(require,module,exports){\n'use strict';\nexports.base64 = false;\nexports.binary = false;\nexports.dir = false;\nexports.createFolders = true;\nexports.date = null;\nexports.compression = null;\nexports.compressionOptions = null;\nexports.comment = null;\nexports.unixPermissions = null;\nexports.dosPermissions = null;\n\n},{}],6:[function(require,module,exports){\n/* global Promise */\n'use strict';\n\n// load the global object first:\n// - it should be better integrated in the system (unhandledRejection in node)\n// - the environment may have a custom Promise implementation (see zone.js)\nvar ES6Promise = null;\nif (typeof Promise !== \"undefined\") {\n ES6Promise = Promise;\n} else {\n ES6Promise = require(\"lie\");\n}\n\n/**\n * Let the user use/change some implementations.\n */\nmodule.exports = {\n Promise: ES6Promise\n};\n\n},{\"lie\":37}],7:[function(require,module,exports){\n'use strict';\nvar USE_TYPEDARRAY = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Uint32Array !== 'undefined');\n\nvar pako = require(\"pako\");\nvar utils = require(\"./utils\");\nvar GenericWorker = require(\"./stream/GenericWorker\");\n\nvar ARRAY_TYPE = USE_TYPEDARRAY ? \"uint8array\" : \"array\";\n\nexports.magic = \"\\x08\\x00\";\n\n/**\n * Create a worker that uses pako to inflate/deflate.\n * @constructor\n * @param {String} action the name of the pako function to call : either \"Deflate\" or \"Inflate\".\n * @param {Object} options the options to use when (de)compressing.\n */\nfunction FlateWorker(action, options) {\n GenericWorker.call(this, \"FlateWorker/\" + action);\n\n this._pako = null;\n this._pakoAction = action;\n this._pakoOptions = options;\n // the `meta` object from the last chunk received\n // this allow this worker to pass around metadata\n this.meta = {};\n}\n\nutils.inherits(FlateWorker, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nFlateWorker.prototype.processChunk = function (chunk) {\n this.meta = chunk.meta;\n if (this._pako === null) {\n this._createPako();\n }\n this._pako.push(utils.transformTo(ARRAY_TYPE, chunk.data), false);\n};\n\n/**\n * @see GenericWorker.flush\n */\nFlateWorker.prototype.flush = function () {\n GenericWorker.prototype.flush.call(this);\n if (this._pako === null) {\n this._createPako();\n }\n this._pako.push([], true);\n};\n/**\n * @see GenericWorker.cleanUp\n */\nFlateWorker.prototype.cleanUp = function () {\n GenericWorker.prototype.cleanUp.call(this);\n this._pako = null;\n};\n\n/**\n * Create the _pako object.\n * TODO: lazy-loading this object isn't the best solution but it's the\n * quickest. The best solution is to lazy-load the worker list. See also the\n * issue #446.\n */\nFlateWorker.prototype._createPako = function () {\n this._pako = new pako[this._pakoAction]({\n raw: true,\n level: this._pakoOptions.level || -1 // default compression\n });\n var self = this;\n this._pako.onData = function(data) {\n self.push({\n data : data,\n meta : self.meta\n });\n };\n};\n\nexports.compressWorker = function (compressionOptions) {\n return new FlateWorker(\"Deflate\", compressionOptions);\n};\nexports.uncompressWorker = function () {\n return new FlateWorker(\"Inflate\", {});\n};\n\n},{\"./stream/GenericWorker\":28,\"./utils\":32,\"pako\":38}],8:[function(require,module,exports){\n'use strict';\n\nvar utils = require('../utils');\nvar GenericWorker = require('../stream/GenericWorker');\nvar utf8 = require('../utf8');\nvar crc32 = require('../crc32');\nvar signature = require('../signature');\n\n/**\n * Transform an integer into a string in hexadecimal.\n * @private\n * @param {number} dec the number to convert.\n * @param {number} bytes the number of bytes to generate.\n * @returns {string} the result.\n */\nvar decToHex = function(dec, bytes) {\n var hex = \"\", i;\n for (i = 0; i < bytes; i++) {\n hex += String.fromCharCode(dec & 0xff);\n dec = dec >>> 8;\n }\n return hex;\n};\n\n/**\n * Generate the UNIX part of the external file attributes.\n * @param {Object} unixPermissions the unix permissions or null.\n * @param {Boolean} isDir true if the entry is a directory, false otherwise.\n * @return {Number} a 32 bit integer.\n *\n * adapted from http://unix.stackexchange.com/questions/14705/the-zip-formats-external-file-attribute :\n *\n * TTTTsstrwxrwxrwx0000000000ADVSHR\n * ^^^^____________________________ file type, see zipinfo.c (UNX_*)\n * ^^^_________________________ setuid, setgid, sticky\n * ^^^^^^^^^________________ permissions\n * ^^^^^^^^^^______ not used ?\n * ^^^^^^ DOS attribute bits : Archive, Directory, Volume label, System file, Hidden, Read only\n */\nvar generateUnixExternalFileAttr = function (unixPermissions, isDir) {\n\n var result = unixPermissions;\n if (!unixPermissions) {\n // I can't use octal values in strict mode, hence the hexa.\n // 040775 => 0x41fd\n // 0100664 => 0x81b4\n result = isDir ? 0x41fd : 0x81b4;\n }\n return (result & 0xFFFF) << 16;\n};\n\n/**\n * Generate the DOS part of the external file attributes.\n * @param {Object} dosPermissions the dos permissions or null.\n * @param {Boolean} isDir true if the entry is a directory, false otherwise.\n * @return {Number} a 32 bit integer.\n *\n * Bit 0 Read-Only\n * Bit 1 Hidden\n * Bit 2 System\n * Bit 3 Volume Label\n * Bit 4 Directory\n * Bit 5 Archive\n */\nvar generateDosExternalFileAttr = function (dosPermissions, isDir) {\n\n // the dir flag is already set for compatibility\n return (dosPermissions || 0) & 0x3F;\n};\n\n/**\n * Generate the various parts used in the construction of the final zip file.\n * @param {Object} streamInfo the hash with information about the compressed file.\n * @param {Boolean} streamedContent is the content streamed ?\n * @param {Boolean} streamingEnded is the stream finished ?\n * @param {number} offset the current offset from the start of the zip file.\n * @param {String} platform let's pretend we are this platform (change platform dependents fields)\n * @param {Function} encodeFileName the function to encode the file name / comment.\n * @return {Object} the zip parts.\n */\nvar generateZipParts = function(streamInfo, streamedContent, streamingEnded, offset, platform, encodeFileName) {\n var file = streamInfo['file'],\n compression = streamInfo['compression'],\n useCustomEncoding = encodeFileName !== utf8.utf8encode,\n encodedFileName = utils.transformTo(\"string\", encodeFileName(file.name)),\n utfEncodedFileName = utils.transformTo(\"string\", utf8.utf8encode(file.name)),\n comment = file.comment,\n encodedComment = utils.transformTo(\"string\", encodeFileName(comment)),\n utfEncodedComment = utils.transformTo(\"string\", utf8.utf8encode(comment)),\n useUTF8ForFileName = utfEncodedFileName.length !== file.name.length,\n useUTF8ForComment = utfEncodedComment.length !== comment.length,\n dosTime,\n dosDate,\n extraFields = \"\",\n unicodePathExtraField = \"\",\n unicodeCommentExtraField = \"\",\n dir = file.dir,\n date = file.date;\n\n\n var dataInfo = {\n crc32 : 0,\n compressedSize : 0,\n uncompressedSize : 0\n };\n\n // if the content is streamed, the sizes/crc32 are only available AFTER\n // the end of the stream.\n if (!streamedContent || streamingEnded) {\n dataInfo.crc32 = streamInfo['crc32'];\n dataInfo.compressedSize = streamInfo['compressedSize'];\n dataInfo.uncompressedSize = streamInfo['uncompressedSize'];\n }\n\n var bitflag = 0;\n if (streamedContent) {\n // Bit 3: the sizes/crc32 are set to zero in the local header.\n // The correct values are put in the data descriptor immediately\n // following the compressed data.\n bitflag |= 0x0008;\n }\n if (!useCustomEncoding && (useUTF8ForFileName || useUTF8ForComment)) {\n // Bit 11: Language encoding flag (EFS).\n bitflag |= 0x0800;\n }\n\n\n var extFileAttr = 0;\n var versionMadeBy = 0;\n if (dir) {\n // dos or unix, we set the dos dir flag\n extFileAttr |= 0x00010;\n }\n if(platform === \"UNIX\") {\n versionMadeBy = 0x031E; // UNIX, version 3.0\n extFileAttr |= generateUnixExternalFileAttr(file.unixPermissions, dir);\n } else { // DOS or other, fallback to DOS\n versionMadeBy = 0x0014; // DOS, version 2.0\n extFileAttr |= generateDosExternalFileAttr(file.dosPermissions, dir);\n }\n\n // date\n // @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html\n // @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html\n // @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html\n\n dosTime = date.getUTCHours();\n dosTime = dosTime << 6;\n dosTime = dosTime | date.getUTCMinutes();\n dosTime = dosTime << 5;\n dosTime = dosTime | date.getUTCSeconds() / 2;\n\n dosDate = date.getUTCFullYear() - 1980;\n dosDate = dosDate << 4;\n dosDate = dosDate | (date.getUTCMonth() + 1);\n dosDate = dosDate << 5;\n dosDate = dosDate | date.getUTCDate();\n\n if (useUTF8ForFileName) {\n // set the unicode path extra field. unzip needs at least one extra\n // field to correctly handle unicode path, so using the path is as good\n // as any other information. This could improve the situation with\n // other archive managers too.\n // This field is usually used without the utf8 flag, with a non\n // unicode path in the header (winrar, winzip). This helps (a bit)\n // with the messy Windows' default compressed folders feature but\n // breaks on p7zip which doesn't seek the unicode path extra field.\n // So for now, UTF-8 everywhere !\n unicodePathExtraField =\n // Version\n decToHex(1, 1) +\n // NameCRC32\n decToHex(crc32(encodedFileName), 4) +\n // UnicodeName\n utfEncodedFileName;\n\n extraFields +=\n // Info-ZIP Unicode Path Extra Field\n \"\\x75\\x70\" +\n // size\n decToHex(unicodePathExtraField.length, 2) +\n // content\n unicodePathExtraField;\n }\n\n if(useUTF8ForComment) {\n\n unicodeCommentExtraField =\n // Version\n decToHex(1, 1) +\n // CommentCRC32\n decToHex(crc32(encodedComment), 4) +\n // UnicodeName\n utfEncodedComment;\n\n extraFields +=\n // Info-ZIP Unicode Path Extra Field\n \"\\x75\\x63\" +\n // size\n decToHex(unicodeCommentExtraField.length, 2) +\n // content\n unicodeCommentExtraField;\n }\n\n var header = \"\";\n\n // version needed to extract\n header += \"\\x0A\\x00\";\n // general purpose bit flag\n header += decToHex(bitflag, 2);\n // compression method\n header += compression.magic;\n // last mod file time\n header += decToHex(dosTime, 2);\n // last mod file date\n header += decToHex(dosDate, 2);\n // crc-32\n header += decToHex(dataInfo.crc32, 4);\n // compressed size\n header += decToHex(dataInfo.compressedSize, 4);\n // uncompressed size\n header += decToHex(dataInfo.uncompressedSize, 4);\n // file name length\n header += decToHex(encodedFileName.length, 2);\n // extra field length\n header += decToHex(extraFields.length, 2);\n\n\n var fileRecord = signature.LOCAL_FILE_HEADER + header + encodedFileName + extraFields;\n\n var dirRecord = signature.CENTRAL_FILE_HEADER +\n // version made by (00: DOS)\n decToHex(versionMadeBy, 2) +\n // file header (common to file and central directory)\n header +\n // file comment length\n decToHex(encodedComment.length, 2) +\n // disk number start\n \"\\x00\\x00\" +\n // internal file attributes TODO\n \"\\x00\\x00\" +\n // external file attributes\n decToHex(extFileAttr, 4) +\n // relative offset of local header\n decToHex(offset, 4) +\n // file name\n encodedFileName +\n // extra field\n extraFields +\n // file comment\n encodedComment;\n\n return {\n fileRecord: fileRecord,\n dirRecord: dirRecord\n };\n};\n\n/**\n * Generate the EOCD record.\n * @param {Number} entriesCount the number of entries in the zip file.\n * @param {Number} centralDirLength the length (in bytes) of the central dir.\n * @param {Number} localDirLength the length (in bytes) of the local dir.\n * @param {String} comment the zip file comment as a binary string.\n * @param {Function} encodeFileName the function to encode the comment.\n * @return {String} the EOCD record.\n */\nvar generateCentralDirectoryEnd = function (entriesCount, centralDirLength, localDirLength, comment, encodeFileName) {\n var dirEnd = \"\";\n var encodedComment = utils.transformTo(\"string\", encodeFileName(comment));\n\n // end of central dir signature\n dirEnd = signature.CENTRAL_DIRECTORY_END +\n // number of this disk\n \"\\x00\\x00\" +\n // number of the disk with the start of the central directory\n \"\\x00\\x00\" +\n // total number of entries in the central directory on this disk\n decToHex(entriesCount, 2) +\n // total number of entries in the central directory\n decToHex(entriesCount, 2) +\n // size of the central directory 4 bytes\n decToHex(centralDirLength, 4) +\n // offset of start of central directory with respect to the starting disk number\n decToHex(localDirLength, 4) +\n // .ZIP file comment length\n decToHex(encodedComment.length, 2) +\n // .ZIP file comment\n encodedComment;\n\n return dirEnd;\n};\n\n/**\n * Generate data descriptors for a file entry.\n * @param {Object} streamInfo the hash generated by a worker, containing information\n * on the file entry.\n * @return {String} the data descriptors.\n */\nvar generateDataDescriptors = function (streamInfo) {\n var descriptor = \"\";\n descriptor = signature.DATA_DESCRIPTOR +\n // crc-32 4 bytes\n decToHex(streamInfo['crc32'], 4) +\n // compressed size 4 bytes\n decToHex(streamInfo['compressedSize'], 4) +\n // uncompressed size 4 bytes\n decToHex(streamInfo['uncompressedSize'], 4);\n\n return descriptor;\n};\n\n\n/**\n * A worker to concatenate other workers to create a zip file.\n * @param {Boolean} streamFiles `true` to stream the content of the files,\n * `false` to accumulate it.\n * @param {String} comment the comment to use.\n * @param {String} platform the platform to use, \"UNIX\" or \"DOS\".\n * @param {Function} encodeFileName the function to encode file names and comments.\n */\nfunction ZipFileWorker(streamFiles, comment, platform, encodeFileName) {\n GenericWorker.call(this, \"ZipFileWorker\");\n // The number of bytes written so far. This doesn't count accumulated chunks.\n this.bytesWritten = 0;\n // The comment of the zip file\n this.zipComment = comment;\n // The platform \"generating\" the zip file.\n this.zipPlatform = platform;\n // the function to encode file names and comments.\n this.encodeFileName = encodeFileName;\n // Should we stream the content of the files ?\n this.streamFiles = streamFiles;\n // If `streamFiles` is false, we will need to accumulate the content of the\n // files to calculate sizes / crc32 (and write them *before* the content).\n // This boolean indicates if we are accumulating chunks (it will change a lot\n // during the lifetime of this worker).\n this.accumulate = false;\n // The buffer receiving chunks when accumulating content.\n this.contentBuffer = [];\n // The list of generated directory records.\n this.dirRecords = [];\n // The offset (in bytes) from the beginning of the zip file for the current source.\n this.currentSourceOffset = 0;\n // The total number of entries in this zip file.\n this.entriesCount = 0;\n // the name of the file currently being added, null when handling the end of the zip file.\n // Used for the emitted metadata.\n this.currentFile = null;\n\n\n\n this._sources = [];\n}\nutils.inherits(ZipFileWorker, GenericWorker);\n\n/**\n * @see GenericWorker.push\n */\nZipFileWorker.prototype.push = function (chunk) {\n\n var currentFilePercent = chunk.meta.percent || 0;\n var entriesCount = this.entriesCount;\n var remainingFiles = this._sources.length;\n\n if(this.accumulate) {\n this.contentBuffer.push(chunk);\n } else {\n this.bytesWritten += chunk.data.length;\n\n GenericWorker.prototype.push.call(this, {\n data : chunk.data,\n meta : {\n currentFile : this.currentFile,\n percent : entriesCount ? (currentFilePercent + 100 * (entriesCount - remainingFiles - 1)) / entriesCount : 100\n }\n });\n }\n};\n\n/**\n * The worker started a new source (an other worker).\n * @param {Object} streamInfo the streamInfo object from the new source.\n */\nZipFileWorker.prototype.openedSource = function (streamInfo) {\n this.currentSourceOffset = this.bytesWritten;\n this.currentFile = streamInfo['file'].name;\n\n var streamedContent = this.streamFiles && !streamInfo['file'].dir;\n\n // don't stream folders (because they don't have any content)\n if(streamedContent) {\n var record = generateZipParts(streamInfo, streamedContent, false, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);\n this.push({\n data : record.fileRecord,\n meta : {percent:0}\n });\n } else {\n // we need to wait for the whole file before pushing anything\n this.accumulate = true;\n }\n};\n\n/**\n * The worker finished a source (an other worker).\n * @param {Object} streamInfo the streamInfo object from the finished source.\n */\nZipFileWorker.prototype.closedSource = function (streamInfo) {\n this.accumulate = false;\n var streamedContent = this.streamFiles && !streamInfo['file'].dir;\n var record = generateZipParts(streamInfo, streamedContent, true, this.currentSourceOffset, this.zipPlatform, this.encodeFileName);\n\n this.dirRecords.push(record.dirRecord);\n if(streamedContent) {\n // after the streamed file, we put data descriptors\n this.push({\n data : generateDataDescriptors(streamInfo),\n meta : {percent:100}\n });\n } else {\n // the content wasn't streamed, we need to push everything now\n // first the file record, then the content\n this.push({\n data : record.fileRecord,\n meta : {percent:0}\n });\n while(this.contentBuffer.length) {\n this.push(this.contentBuffer.shift());\n }\n }\n this.currentFile = null;\n};\n\n/**\n * @see GenericWorker.flush\n */\nZipFileWorker.prototype.flush = function () {\n\n var localDirLength = this.bytesWritten;\n for(var i = 0; i < this.dirRecords.length; i++) {\n this.push({\n data : this.dirRecords[i],\n meta : {percent:100}\n });\n }\n var centralDirLength = this.bytesWritten - localDirLength;\n\n var dirEnd = generateCentralDirectoryEnd(this.dirRecords.length, centralDirLength, localDirLength, this.zipComment, this.encodeFileName);\n\n this.push({\n data : dirEnd,\n meta : {percent:100}\n });\n};\n\n/**\n * Prepare the next source to be read.\n */\nZipFileWorker.prototype.prepareNextSource = function () {\n this.previous = this._sources.shift();\n this.openedSource(this.previous.streamInfo);\n if (this.isPaused) {\n this.previous.pause();\n } else {\n this.previous.resume();\n }\n};\n\n/**\n * @see GenericWorker.registerPrevious\n */\nZipFileWorker.prototype.registerPrevious = function (previous) {\n this._sources.push(previous);\n var self = this;\n\n previous.on('data', function (chunk) {\n self.processChunk(chunk);\n });\n previous.on('end', function () {\n self.closedSource(self.previous.streamInfo);\n if(self._sources.length) {\n self.prepareNextSource();\n } else {\n self.end();\n }\n });\n previous.on('error', function (e) {\n self.error(e);\n });\n return this;\n};\n\n/**\n * @see GenericWorker.resume\n */\nZipFileWorker.prototype.resume = function () {\n if(!GenericWorker.prototype.resume.call(this)) {\n return false;\n }\n\n if (!this.previous && this._sources.length) {\n this.prepareNextSource();\n return true;\n }\n if (!this.previous && !this._sources.length && !this.generatedError) {\n this.end();\n return true;\n }\n};\n\n/**\n * @see GenericWorker.error\n */\nZipFileWorker.prototype.error = function (e) {\n var sources = this._sources;\n if(!GenericWorker.prototype.error.call(this, e)) {\n return false;\n }\n for(var i = 0; i < sources.length; i++) {\n try {\n sources[i].error(e);\n } catch(e) {\n // the `error` exploded, nothing to do\n }\n }\n return true;\n};\n\n/**\n * @see GenericWorker.lock\n */\nZipFileWorker.prototype.lock = function () {\n GenericWorker.prototype.lock.call(this);\n var sources = this._sources;\n for(var i = 0; i < sources.length; i++) {\n sources[i].lock();\n }\n};\n\nmodule.exports = ZipFileWorker;\n\n},{\"../crc32\":4,\"../signature\":23,\"../stream/GenericWorker\":28,\"../utf8\":31,\"../utils\":32}],9:[function(require,module,exports){\n'use strict';\n\nvar compressions = require('../compressions');\nvar ZipFileWorker = require('./ZipFileWorker');\n\n/**\n * Find the compression to use.\n * @param {String} fileCompression the compression defined at the file level, if any.\n * @param {String} zipCompression the compression defined at the load() level.\n * @return {Object} the compression object to use.\n */\nvar getCompression = function (fileCompression, zipCompression) {\n\n var compressionName = fileCompression || zipCompression;\n var compression = compressions[compressionName];\n if (!compression) {\n throw new Error(compressionName + \" is not a valid compression method !\");\n }\n return compression;\n};\n\n/**\n * Create a worker to generate a zip file.\n * @param {JSZip} zip the JSZip instance at the right root level.\n * @param {Object} options to generate the zip file.\n * @param {String} comment the comment to use.\n */\nexports.generateWorker = function (zip, options, comment) {\n\n var zipFileWorker = new ZipFileWorker(options.streamFiles, comment, options.platform, options.encodeFileName);\n var entriesCount = 0;\n try {\n\n zip.forEach(function (relativePath, file) {\n entriesCount++;\n var compression = getCompression(file.options.compression, options.compression);\n var compressionOptions = file.options.compressionOptions || options.compressionOptions || {};\n var dir = file.dir, date = file.date;\n\n file._compressWorker(compression, compressionOptions)\n .withStreamInfo(\"file\", {\n name : relativePath,\n dir : dir,\n date : date,\n comment : file.comment || \"\",\n unixPermissions : file.unixPermissions,\n dosPermissions : file.dosPermissions\n })\n .pipe(zipFileWorker);\n });\n zipFileWorker.entriesCount = entriesCount;\n } catch (e) {\n zipFileWorker.error(e);\n }\n\n return zipFileWorker;\n};\n\n},{\"../compressions\":3,\"./ZipFileWorker\":8}],10:[function(require,module,exports){\n'use strict';\n\n/**\n * Representation a of zip file in js\n * @constructor\n */\nfunction JSZip() {\n // if this constructor is used without `new`, it adds `new` before itself:\n if(!(this instanceof JSZip)) {\n return new JSZip();\n }\n\n if(arguments.length) {\n throw new Error(\"The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.\");\n }\n\n // object containing the files :\n // {\n // \"folder/\" : {...},\n // \"folder/data.txt\" : {...}\n // }\n this.files = {};\n\n this.comment = null;\n\n // Where we are in the hierarchy\n this.root = \"\";\n this.clone = function() {\n var newObj = new JSZip();\n for (var i in this) {\n if (typeof this[i] !== \"function\") {\n newObj[i] = this[i];\n }\n }\n return newObj;\n };\n}\nJSZip.prototype = require('./object');\nJSZip.prototype.loadAsync = require('./load');\nJSZip.support = require('./support');\nJSZip.defaults = require('./defaults');\n\n// TODO find a better way to handle this version,\n// a require('package.json').version doesn't work with webpack, see #327\nJSZip.version = \"3.5.0\";\n\nJSZip.loadAsync = function (content, options) {\n return new JSZip().loadAsync(content, options);\n};\n\nJSZip.external = require(\"./external\");\nmodule.exports = JSZip;\n\n},{\"./defaults\":5,\"./external\":6,\"./load\":11,\"./object\":15,\"./support\":30}],11:[function(require,module,exports){\n'use strict';\nvar utils = require('./utils');\nvar external = require(\"./external\");\nvar utf8 = require('./utf8');\nvar utils = require('./utils');\nvar ZipEntries = require('./zipEntries');\nvar Crc32Probe = require('./stream/Crc32Probe');\nvar nodejsUtils = require(\"./nodejsUtils\");\n\n/**\n * Check the CRC32 of an entry.\n * @param {ZipEntry} zipEntry the zip entry to check.\n * @return {Promise} the result.\n */\nfunction checkEntryCRC32(zipEntry) {\n return new external.Promise(function (resolve, reject) {\n var worker = zipEntry.decompressed.getContentWorker().pipe(new Crc32Probe());\n worker.on(\"error\", function (e) {\n reject(e);\n })\n .on(\"end\", function () {\n if (worker.streamInfo.crc32 !== zipEntry.decompressed.crc32) {\n reject(new Error(\"Corrupted zip : CRC32 mismatch\"));\n } else {\n resolve();\n }\n })\n .resume();\n });\n}\n\nmodule.exports = function(data, options) {\n var zip = this;\n options = utils.extend(options || {}, {\n base64: false,\n checkCRC32: false,\n optimizedBinaryString: false,\n createFolders: false,\n decodeFileName: utf8.utf8decode\n });\n\n if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {\n return external.Promise.reject(new Error(\"JSZip can't accept a stream when loading a zip file.\"));\n }\n\n return utils.prepareContent(\"the loaded zip file\", data, true, options.optimizedBinaryString, options.base64)\n .then(function(data) {\n var zipEntries = new ZipEntries(options);\n zipEntries.load(data);\n return zipEntries;\n }).then(function checkCRC32(zipEntries) {\n var promises = [external.Promise.resolve(zipEntries)];\n var files = zipEntries.files;\n if (options.checkCRC32) {\n for (var i = 0; i < files.length; i++) {\n promises.push(checkEntryCRC32(files[i]));\n }\n }\n return external.Promise.all(promises);\n }).then(function addFiles(results) {\n var zipEntries = results.shift();\n var files = zipEntries.files;\n for (var i = 0; i < files.length; i++) {\n var input = files[i];\n zip.file(input.fileNameStr, input.decompressed, {\n binary: true,\n optimizedBinaryString: true,\n date: input.date,\n dir: input.dir,\n comment : input.fileCommentStr.length ? input.fileCommentStr : null,\n unixPermissions : input.unixPermissions,\n dosPermissions : input.dosPermissions,\n createFolders: options.createFolders\n });\n }\n if (zipEntries.zipComment.length) {\n zip.comment = zipEntries.zipComment;\n }\n\n return zip;\n });\n};\n\n},{\"./external\":6,\"./nodejsUtils\":14,\"./stream/Crc32Probe\":25,\"./utf8\":31,\"./utils\":32,\"./zipEntries\":33}],12:[function(require,module,exports){\n\"use strict\";\n\nvar utils = require('../utils');\nvar GenericWorker = require('../stream/GenericWorker');\n\n/**\n * A worker that use a nodejs stream as source.\n * @constructor\n * @param {String} filename the name of the file entry for this stream.\n * @param {Readable} stream the nodejs stream.\n */\nfunction NodejsStreamInputAdapter(filename, stream) {\n GenericWorker.call(this, \"Nodejs stream input adapter for \" + filename);\n this._upstreamEnded = false;\n this._bindStream(stream);\n}\n\nutils.inherits(NodejsStreamInputAdapter, GenericWorker);\n\n/**\n * Prepare the stream and bind the callbacks on it.\n * Do this ASAP on node 0.10 ! A lazy binding doesn't always work.\n * @param {Stream} stream the nodejs stream to use.\n */\nNodejsStreamInputAdapter.prototype._bindStream = function (stream) {\n var self = this;\n this._stream = stream;\n stream.pause();\n stream\n .on(\"data\", function (chunk) {\n self.push({\n data: chunk,\n meta : {\n percent : 0\n }\n });\n })\n .on(\"error\", function (e) {\n if(self.isPaused) {\n this.generatedError = e;\n } else {\n self.error(e);\n }\n })\n .on(\"end\", function () {\n if(self.isPaused) {\n self._upstreamEnded = true;\n } else {\n self.end();\n }\n });\n};\nNodejsStreamInputAdapter.prototype.pause = function () {\n if(!GenericWorker.prototype.pause.call(this)) {\n return false;\n }\n this._stream.pause();\n return true;\n};\nNodejsStreamInputAdapter.prototype.resume = function () {\n if(!GenericWorker.prototype.resume.call(this)) {\n return false;\n }\n\n if(this._upstreamEnded) {\n this.end();\n } else {\n this._stream.resume();\n }\n\n return true;\n};\n\nmodule.exports = NodejsStreamInputAdapter;\n\n},{\"../stream/GenericWorker\":28,\"../utils\":32}],13:[function(require,module,exports){\n'use strict';\n\nvar Readable = require('readable-stream').Readable;\n\nvar utils = require('../utils');\nutils.inherits(NodejsStreamOutputAdapter, Readable);\n\n/**\n* A nodejs stream using a worker as source.\n* @see the SourceWrapper in http://nodejs.org/api/stream.html\n* @constructor\n* @param {StreamHelper} helper the helper wrapping the worker\n* @param {Object} options the nodejs stream options\n* @param {Function} updateCb the update callback.\n*/\nfunction NodejsStreamOutputAdapter(helper, options, updateCb) {\n Readable.call(this, options);\n this._helper = helper;\n\n var self = this;\n helper.on(\"data\", function (data, meta) {\n if (!self.push(data)) {\n self._helper.pause();\n }\n if(updateCb) {\n updateCb(meta);\n }\n })\n .on(\"error\", function(e) {\n self.emit('error', e);\n })\n .on(\"end\", function () {\n self.push(null);\n });\n}\n\n\nNodejsStreamOutputAdapter.prototype._read = function() {\n this._helper.resume();\n};\n\nmodule.exports = NodejsStreamOutputAdapter;\n\n},{\"../utils\":32,\"readable-stream\":16}],14:[function(require,module,exports){\n'use strict';\n\nmodule.exports = {\n /**\n * True if this is running in Nodejs, will be undefined in a browser.\n * In a browser, browserify won't include this file and the whole module\n * will be resolved an empty object.\n */\n isNode : typeof Buffer !== \"undefined\",\n /**\n * Create a new nodejs Buffer from an existing content.\n * @param {Object} data the data to pass to the constructor.\n * @param {String} encoding the encoding to use.\n * @return {Buffer} a new Buffer.\n */\n newBufferFrom: function(data, encoding) {\n if (Buffer.from && Buffer.from !== Uint8Array.from) {\n return Buffer.from(data, encoding);\n } else {\n if (typeof data === \"number\") {\n // Safeguard for old Node.js versions. On newer versions,\n // Buffer.from(number) / Buffer(number, encoding) already throw.\n throw new Error(\"The \\\"data\\\" argument must not be a number\");\n }\n return new Buffer(data, encoding);\n }\n },\n /**\n * Create a new nodejs Buffer with the specified size.\n * @param {Integer} size the size of the buffer.\n * @return {Buffer} a new Buffer.\n */\n allocBuffer: function (size) {\n if (Buffer.alloc) {\n return Buffer.alloc(size);\n } else {\n var buf = new Buffer(size);\n buf.fill(0);\n return buf;\n }\n },\n /**\n * Find out if an object is a Buffer.\n * @param {Object} b the object to test.\n * @return {Boolean} true if the object is a Buffer, false otherwise.\n */\n isBuffer : function(b){\n return Buffer.isBuffer(b);\n },\n\n isStream : function (obj) {\n return obj &&\n typeof obj.on === \"function\" &&\n typeof obj.pause === \"function\" &&\n typeof obj.resume === \"function\";\n }\n};\n\n},{}],15:[function(require,module,exports){\n'use strict';\nvar utf8 = require('./utf8');\nvar utils = require('./utils');\nvar GenericWorker = require('./stream/GenericWorker');\nvar StreamHelper = require('./stream/StreamHelper');\nvar defaults = require('./defaults');\nvar CompressedObject = require('./compressedObject');\nvar ZipObject = require('./zipObject');\nvar generate = require(\"./generate\");\nvar nodejsUtils = require(\"./nodejsUtils\");\nvar NodejsStreamInputAdapter = require(\"./nodejs/NodejsStreamInputAdapter\");\n\n\n/**\n * Add a file in the current folder.\n * @private\n * @param {string} name the name of the file\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data of the file\n * @param {Object} originalOptions the options of the file\n * @return {Object} the new file.\n */\nvar fileAdd = function(name, data, originalOptions) {\n // be sure sub folders exist\n var dataType = utils.getTypeOf(data),\n parent;\n\n\n /*\n * Correct options.\n */\n\n var o = utils.extend(originalOptions || {}, defaults);\n o.date = o.date || new Date();\n if (o.compression !== null) {\n o.compression = o.compression.toUpperCase();\n }\n\n if (typeof o.unixPermissions === \"string\") {\n o.unixPermissions = parseInt(o.unixPermissions, 8);\n }\n\n // UNX_IFDIR 0040000 see zipinfo.c\n if (o.unixPermissions && (o.unixPermissions & 0x4000)) {\n o.dir = true;\n }\n // Bit 4 Directory\n if (o.dosPermissions && (o.dosPermissions & 0x0010)) {\n o.dir = true;\n }\n\n if (o.dir) {\n name = forceTrailingSlash(name);\n }\n if (o.createFolders && (parent = parentFolder(name))) {\n folderAdd.call(this, parent, true);\n }\n\n var isUnicodeString = dataType === \"string\" && o.binary === false && o.base64 === false;\n if (!originalOptions || typeof originalOptions.binary === \"undefined\") {\n o.binary = !isUnicodeString;\n }\n\n\n var isCompressedEmpty = (data instanceof CompressedObject) && data.uncompressedSize === 0;\n\n if (isCompressedEmpty || o.dir || !data || data.length === 0) {\n o.base64 = false;\n o.binary = true;\n data = \"\";\n o.compression = \"STORE\";\n dataType = \"string\";\n }\n\n /*\n * Convert content to fit.\n */\n\n var zipObjectContent = null;\n if (data instanceof CompressedObject || data instanceof GenericWorker) {\n zipObjectContent = data;\n } else if (nodejsUtils.isNode && nodejsUtils.isStream(data)) {\n zipObjectContent = new NodejsStreamInputAdapter(name, data);\n } else {\n zipObjectContent = utils.prepareContent(name, data, o.binary, o.optimizedBinaryString, o.base64);\n }\n\n var object = new ZipObject(name, zipObjectContent, o);\n this.files[name] = object;\n /*\n TODO: we can't throw an exception because we have async promises\n (we can have a promise of a Date() for example) but returning a\n promise is useless because file(name, data) returns the JSZip\n object for chaining. Should we break that to allow the user\n to catch the error ?\n\n return external.Promise.resolve(zipObjectContent)\n .then(function () {\n return object;\n });\n */\n};\n\n/**\n * Find the parent folder of the path.\n * @private\n * @param {string} path the path to use\n * @return {string} the parent folder, or \"\"\n */\nvar parentFolder = function (path) {\n if (path.slice(-1) === '/') {\n path = path.substring(0, path.length - 1);\n }\n var lastSlash = path.lastIndexOf('/');\n return (lastSlash > 0) ? path.substring(0, lastSlash) : \"\";\n};\n\n/**\n * Returns the path with a slash at the end.\n * @private\n * @param {String} path the path to check.\n * @return {String} the path with a trailing slash.\n */\nvar forceTrailingSlash = function(path) {\n // Check the name ends with a /\n if (path.slice(-1) !== \"/\") {\n path += \"/\"; // IE doesn't like substr(-1)\n }\n return path;\n};\n\n/**\n * Add a (sub) folder in the current folder.\n * @private\n * @param {string} name the folder's name\n * @param {boolean=} [createFolders] If true, automatically create sub\n * folders. Defaults to false.\n * @return {Object} the new folder.\n */\nvar folderAdd = function(name, createFolders) {\n createFolders = (typeof createFolders !== 'undefined') ? createFolders : defaults.createFolders;\n\n name = forceTrailingSlash(name);\n\n // Does this folder already exist?\n if (!this.files[name]) {\n fileAdd.call(this, name, null, {\n dir: true,\n createFolders: createFolders\n });\n }\n return this.files[name];\n};\n\n/**\n* Cross-window, cross-Node-context regular expression detection\n* @param {Object} object Anything\n* @return {Boolean} true if the object is a regular expression,\n* false otherwise\n*/\nfunction isRegExp(object) {\n return Object.prototype.toString.call(object) === \"[object RegExp]\";\n}\n\n// return the actual prototype of JSZip\nvar out = {\n /**\n * @see loadAsync\n */\n load: function() {\n throw new Error(\"This method has been removed in JSZip 3.0, please check the upgrade guide.\");\n },\n\n\n /**\n * Call a callback function for each entry at this folder level.\n * @param {Function} cb the callback function:\n * function (relativePath, file) {...}\n * It takes 2 arguments : the relative path and the file.\n */\n forEach: function(cb) {\n var filename, relativePath, file;\n for (filename in this.files) {\n if (!this.files.hasOwnProperty(filename)) {\n continue;\n }\n file = this.files[filename];\n relativePath = filename.slice(this.root.length, filename.length);\n if (relativePath && filename.slice(0, this.root.length) === this.root) { // the file is in the current root\n cb(relativePath, file); // TODO reverse the parameters ? need to be clean AND consistent with the filter search fn...\n }\n }\n },\n\n /**\n * Filter nested files/folders with the specified function.\n * @param {Function} search the predicate to use :\n * function (relativePath, file) {...}\n * It takes 2 arguments : the relative path and the file.\n * @return {Array} An array of matching elements.\n */\n filter: function(search) {\n var result = [];\n this.forEach(function (relativePath, entry) {\n if (search(relativePath, entry)) { // the file matches the function\n result.push(entry);\n }\n\n });\n return result;\n },\n\n /**\n * Add a file to the zip file, or search a file.\n * @param {string|RegExp} name The name of the file to add (if data is defined),\n * the name of the file to find (if no data) or a regex to match files.\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data The file data, either raw or base64 encoded\n * @param {Object} o File options\n * @return {JSZip|Object|Array} this JSZip object (when adding a file),\n * a file (when searching by string) or an array of files (when searching by regex).\n */\n file: function(name, data, o) {\n if (arguments.length === 1) {\n if (isRegExp(name)) {\n var regexp = name;\n return this.filter(function(relativePath, file) {\n return !file.dir && regexp.test(relativePath);\n });\n }\n else { // text\n var obj = this.files[this.root + name];\n if (obj && !obj.dir) {\n return obj;\n } else {\n return null;\n }\n }\n }\n else { // more than one argument : we have data !\n name = this.root + name;\n fileAdd.call(this, name, data, o);\n }\n return this;\n },\n\n /**\n * Add a directory to the zip file, or search.\n * @param {String|RegExp} arg The name of the directory to add, or a regex to search folders.\n * @return {JSZip} an object with the new directory as the root, or an array containing matching folders.\n */\n folder: function(arg) {\n if (!arg) {\n return this;\n }\n\n if (isRegExp(arg)) {\n return this.filter(function(relativePath, file) {\n return file.dir && arg.test(relativePath);\n });\n }\n\n // else, name is a new folder\n var name = this.root + arg;\n var newFolder = folderAdd.call(this, name);\n\n // Allow chaining by returning a new object with this folder as the root\n var ret = this.clone();\n ret.root = newFolder.name;\n return ret;\n },\n\n /**\n * Delete a file, or a directory and all sub-files, from the zip\n * @param {string} name the name of the file to delete\n * @return {JSZip} this JSZip object\n */\n remove: function(name) {\n name = this.root + name;\n var file = this.files[name];\n if (!file) {\n // Look for any folders\n if (name.slice(-1) !== \"/\") {\n name += \"/\";\n }\n file = this.files[name];\n }\n\n if (file && !file.dir) {\n // file\n delete this.files[name];\n } else {\n // maybe a folder, delete recursively\n var kids = this.filter(function(relativePath, file) {\n return file.name.slice(0, name.length) === name;\n });\n for (var i = 0; i < kids.length; i++) {\n delete this.files[kids[i].name];\n }\n }\n\n return this;\n },\n\n /**\n * Generate the complete zip file\n * @param {Object} options the options to generate the zip file :\n * - compression, \"STORE\" by default.\n * - type, \"base64\" by default. Values are : string, base64, uint8array, arraybuffer, blob.\n * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the zip file\n */\n generate: function(options) {\n throw new Error(\"This method has been removed in JSZip 3.0, please check the upgrade guide.\");\n },\n\n /**\n * Generate the complete zip file as an internal stream.\n * @param {Object} options the options to generate the zip file :\n * - compression, \"STORE\" by default.\n * - type, \"base64\" by default. Values are : string, base64, uint8array, arraybuffer, blob.\n * @return {StreamHelper} the streamed zip file.\n */\n generateInternalStream: function(options) {\n var worker, opts = {};\n try {\n opts = utils.extend(options || {}, {\n streamFiles: false,\n compression: \"STORE\",\n compressionOptions : null,\n type: \"\",\n platform: \"DOS\",\n comment: null,\n mimeType: 'application/zip',\n encodeFileName: utf8.utf8encode\n });\n\n opts.type = opts.type.toLowerCase();\n opts.compression = opts.compression.toUpperCase();\n\n // \"binarystring\" is preferred but the internals use \"string\".\n if(opts.type === \"binarystring\") {\n opts.type = \"string\";\n }\n\n if (!opts.type) {\n throw new Error(\"No output type specified.\");\n }\n\n utils.checkSupport(opts.type);\n\n // accept nodejs `process.platform`\n if(\n opts.platform === 'darwin' ||\n opts.platform === 'freebsd' ||\n opts.platform === 'linux' ||\n opts.platform === 'sunos'\n ) {\n opts.platform = \"UNIX\";\n }\n if (opts.platform === 'win32') {\n opts.platform = \"DOS\";\n }\n\n var comment = opts.comment || this.comment || \"\";\n worker = generate.generateWorker(this, opts, comment);\n } catch (e) {\n worker = new GenericWorker(\"error\");\n worker.error(e);\n }\n return new StreamHelper(worker, opts.type || \"string\", opts.mimeType);\n },\n /**\n * Generate the complete zip file asynchronously.\n * @see generateInternalStream\n */\n generateAsync: function(options, onUpdate) {\n return this.generateInternalStream(options).accumulate(onUpdate);\n },\n /**\n * Generate the complete zip file asynchronously.\n * @see generateInternalStream\n */\n generateNodeStream: function(options, onUpdate) {\n options = options || {};\n if (!options.type) {\n options.type = \"nodebuffer\";\n }\n return this.generateInternalStream(options).toNodejsStream(onUpdate);\n }\n};\nmodule.exports = out;\n\n},{\"./compressedObject\":2,\"./defaults\":5,\"./generate\":9,\"./nodejs/NodejsStreamInputAdapter\":12,\"./nodejsUtils\":14,\"./stream/GenericWorker\":28,\"./stream/StreamHelper\":29,\"./utf8\":31,\"./utils\":32,\"./zipObject\":35}],16:[function(require,module,exports){\n/*\n * This file is used by module bundlers (browserify/webpack/etc) when\n * including a stream implementation. We use \"readable-stream\" to get a\n * consistent behavior between nodejs versions but bundlers often have a shim\n * for \"stream\". Using this shim greatly improve the compatibility and greatly\n * reduce the final size of the bundle (only one stream implementation, not\n * two).\n */\nmodule.exports = require(\"stream\");\n\n},{\"stream\":undefined}],17:[function(require,module,exports){\n'use strict';\nvar DataReader = require('./DataReader');\nvar utils = require('../utils');\n\nfunction ArrayReader(data) {\n DataReader.call(this, data);\n\tfor(var i = 0; i < this.data.length; i++) {\n\t\tdata[i] = data[i] & 0xFF;\n\t}\n}\nutils.inherits(ArrayReader, DataReader);\n/**\n * @see DataReader.byteAt\n */\nArrayReader.prototype.byteAt = function(i) {\n return this.data[this.zero + i];\n};\n/**\n * @see DataReader.lastIndexOfSignature\n */\nArrayReader.prototype.lastIndexOfSignature = function(sig) {\n var sig0 = sig.charCodeAt(0),\n sig1 = sig.charCodeAt(1),\n sig2 = sig.charCodeAt(2),\n sig3 = sig.charCodeAt(3);\n for (var i = this.length - 4; i >= 0; --i) {\n if (this.data[i] === sig0 && this.data[i + 1] === sig1 && this.data[i + 2] === sig2 && this.data[i + 3] === sig3) {\n return i - this.zero;\n }\n }\n\n return -1;\n};\n/**\n * @see DataReader.readAndCheckSignature\n */\nArrayReader.prototype.readAndCheckSignature = function (sig) {\n var sig0 = sig.charCodeAt(0),\n sig1 = sig.charCodeAt(1),\n sig2 = sig.charCodeAt(2),\n sig3 = sig.charCodeAt(3),\n data = this.readData(4);\n return sig0 === data[0] && sig1 === data[1] && sig2 === data[2] && sig3 === data[3];\n};\n/**\n * @see DataReader.readData\n */\nArrayReader.prototype.readData = function(size) {\n this.checkOffset(size);\n if(size === 0) {\n return [];\n }\n var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);\n this.index += size;\n return result;\n};\nmodule.exports = ArrayReader;\n\n},{\"../utils\":32,\"./DataReader\":18}],18:[function(require,module,exports){\n'use strict';\nvar utils = require('../utils');\n\nfunction DataReader(data) {\n this.data = data; // type : see implementation\n this.length = data.length;\n this.index = 0;\n this.zero = 0;\n}\nDataReader.prototype = {\n /**\n * Check that the offset will not go too far.\n * @param {string} offset the additional offset to check.\n * @throws {Error} an Error if the offset is out of bounds.\n */\n checkOffset: function(offset) {\n this.checkIndex(this.index + offset);\n },\n /**\n * Check that the specified index will not be too far.\n * @param {string} newIndex the index to check.\n * @throws {Error} an Error if the index is out of bounds.\n */\n checkIndex: function(newIndex) {\n if (this.length < this.zero + newIndex || newIndex < 0) {\n throw new Error(\"End of data reached (data length = \" + this.length + \", asked index = \" + (newIndex) + \"). Corrupted zip ?\");\n }\n },\n /**\n * Change the index.\n * @param {number} newIndex The new index.\n * @throws {Error} if the new index is out of the data.\n */\n setIndex: function(newIndex) {\n this.checkIndex(newIndex);\n this.index = newIndex;\n },\n /**\n * Skip the next n bytes.\n * @param {number} n the number of bytes to skip.\n * @throws {Error} if the new index is out of the data.\n */\n skip: function(n) {\n this.setIndex(this.index + n);\n },\n /**\n * Get the byte at the specified index.\n * @param {number} i the index to use.\n * @return {number} a byte.\n */\n byteAt: function(i) {\n // see implementations\n },\n /**\n * Get the next number with a given byte size.\n * @param {number} size the number of bytes to read.\n * @return {number} the corresponding number.\n */\n readInt: function(size) {\n var result = 0,\n i;\n this.checkOffset(size);\n for (i = this.index + size - 1; i >= this.index; i--) {\n result = (result << 8) + this.byteAt(i);\n }\n this.index += size;\n return result;\n },\n /**\n * Get the next string with a given byte size.\n * @param {number} size the number of bytes to read.\n * @return {string} the corresponding string.\n */\n readString: function(size) {\n return utils.transformTo(\"string\", this.readData(size));\n },\n /**\n * Get raw data without conversion, bytes.\n * @param {number} size the number of bytes to read.\n * @return {Object} the raw data, implementation specific.\n */\n readData: function(size) {\n // see implementations\n },\n /**\n * Find the last occurrence of a zip signature (4 bytes).\n * @param {string} sig the signature to find.\n * @return {number} the index of the last occurrence, -1 if not found.\n */\n lastIndexOfSignature: function(sig) {\n // see implementations\n },\n /**\n * Read the signature (4 bytes) at the current position and compare it with sig.\n * @param {string} sig the expected signature\n * @return {boolean} true if the signature matches, false otherwise.\n */\n readAndCheckSignature: function(sig) {\n // see implementations\n },\n /**\n * Get the next date.\n * @return {Date} the date.\n */\n readDate: function() {\n var dostime = this.readInt(4);\n return new Date(Date.UTC(\n ((dostime >> 25) & 0x7f) + 1980, // year\n ((dostime >> 21) & 0x0f) - 1, // month\n (dostime >> 16) & 0x1f, // day\n (dostime >> 11) & 0x1f, // hour\n (dostime >> 5) & 0x3f, // minute\n (dostime & 0x1f) << 1)); // second\n }\n};\nmodule.exports = DataReader;\n\n},{\"../utils\":32}],19:[function(require,module,exports){\n'use strict';\nvar Uint8ArrayReader = require('./Uint8ArrayReader');\nvar utils = require('../utils');\n\nfunction NodeBufferReader(data) {\n Uint8ArrayReader.call(this, data);\n}\nutils.inherits(NodeBufferReader, Uint8ArrayReader);\n\n/**\n * @see DataReader.readData\n */\nNodeBufferReader.prototype.readData = function(size) {\n this.checkOffset(size);\n var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);\n this.index += size;\n return result;\n};\nmodule.exports = NodeBufferReader;\n\n},{\"../utils\":32,\"./Uint8ArrayReader\":21}],20:[function(require,module,exports){\n'use strict';\nvar DataReader = require('./DataReader');\nvar utils = require('../utils');\n\nfunction StringReader(data) {\n DataReader.call(this, data);\n}\nutils.inherits(StringReader, DataReader);\n/**\n * @see DataReader.byteAt\n */\nStringReader.prototype.byteAt = function(i) {\n return this.data.charCodeAt(this.zero + i);\n};\n/**\n * @see DataReader.lastIndexOfSignature\n */\nStringReader.prototype.lastIndexOfSignature = function(sig) {\n return this.data.lastIndexOf(sig) - this.zero;\n};\n/**\n * @see DataReader.readAndCheckSignature\n */\nStringReader.prototype.readAndCheckSignature = function (sig) {\n var data = this.readData(4);\n return sig === data;\n};\n/**\n * @see DataReader.readData\n */\nStringReader.prototype.readData = function(size) {\n this.checkOffset(size);\n // this will work because the constructor applied the \"& 0xff\" mask.\n var result = this.data.slice(this.zero + this.index, this.zero + this.index + size);\n this.index += size;\n return result;\n};\nmodule.exports = StringReader;\n\n},{\"../utils\":32,\"./DataReader\":18}],21:[function(require,module,exports){\n'use strict';\nvar ArrayReader = require('./ArrayReader');\nvar utils = require('../utils');\n\nfunction Uint8ArrayReader(data) {\n ArrayReader.call(this, data);\n}\nutils.inherits(Uint8ArrayReader, ArrayReader);\n/**\n * @see DataReader.readData\n */\nUint8ArrayReader.prototype.readData = function(size) {\n this.checkOffset(size);\n if(size === 0) {\n // in IE10, when using subarray(idx, idx), we get the array [0x00] instead of [].\n return new Uint8Array(0);\n }\n var result = this.data.subarray(this.zero + this.index, this.zero + this.index + size);\n this.index += size;\n return result;\n};\nmodule.exports = Uint8ArrayReader;\n\n},{\"../utils\":32,\"./ArrayReader\":17}],22:[function(require,module,exports){\n'use strict';\n\nvar utils = require('../utils');\nvar support = require('../support');\nvar ArrayReader = require('./ArrayReader');\nvar StringReader = require('./StringReader');\nvar NodeBufferReader = require('./NodeBufferReader');\nvar Uint8ArrayReader = require('./Uint8ArrayReader');\n\n/**\n * Create a reader adapted to the data.\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data to read.\n * @return {DataReader} the data reader.\n */\nmodule.exports = function (data) {\n var type = utils.getTypeOf(data);\n utils.checkSupport(type);\n if (type === \"string\" && !support.uint8array) {\n return new StringReader(data);\n }\n if (type === \"nodebuffer\") {\n return new NodeBufferReader(data);\n }\n if (support.uint8array) {\n return new Uint8ArrayReader(utils.transformTo(\"uint8array\", data));\n }\n return new ArrayReader(utils.transformTo(\"array\", data));\n};\n\n},{\"../support\":30,\"../utils\":32,\"./ArrayReader\":17,\"./NodeBufferReader\":19,\"./StringReader\":20,\"./Uint8ArrayReader\":21}],23:[function(require,module,exports){\n'use strict';\nexports.LOCAL_FILE_HEADER = \"PK\\x03\\x04\";\nexports.CENTRAL_FILE_HEADER = \"PK\\x01\\x02\";\nexports.CENTRAL_DIRECTORY_END = \"PK\\x05\\x06\";\nexports.ZIP64_CENTRAL_DIRECTORY_LOCATOR = \"PK\\x06\\x07\";\nexports.ZIP64_CENTRAL_DIRECTORY_END = \"PK\\x06\\x06\";\nexports.DATA_DESCRIPTOR = \"PK\\x07\\x08\";\n\n},{}],24:[function(require,module,exports){\n'use strict';\n\nvar GenericWorker = require('./GenericWorker');\nvar utils = require('../utils');\n\n/**\n * A worker which convert chunks to a specified type.\n * @constructor\n * @param {String} destType the destination type.\n */\nfunction ConvertWorker(destType) {\n GenericWorker.call(this, \"ConvertWorker to \" + destType);\n this.destType = destType;\n}\nutils.inherits(ConvertWorker, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nConvertWorker.prototype.processChunk = function (chunk) {\n this.push({\n data : utils.transformTo(this.destType, chunk.data),\n meta : chunk.meta\n });\n};\nmodule.exports = ConvertWorker;\n\n},{\"../utils\":32,\"./GenericWorker\":28}],25:[function(require,module,exports){\n'use strict';\n\nvar GenericWorker = require('./GenericWorker');\nvar crc32 = require('../crc32');\nvar utils = require('../utils');\n\n/**\n * A worker which calculate the crc32 of the data flowing through.\n * @constructor\n */\nfunction Crc32Probe() {\n GenericWorker.call(this, \"Crc32Probe\");\n this.withStreamInfo(\"crc32\", 0);\n}\nutils.inherits(Crc32Probe, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nCrc32Probe.prototype.processChunk = function (chunk) {\n this.streamInfo.crc32 = crc32(chunk.data, this.streamInfo.crc32 || 0);\n this.push(chunk);\n};\nmodule.exports = Crc32Probe;\n\n},{\"../crc32\":4,\"../utils\":32,\"./GenericWorker\":28}],26:[function(require,module,exports){\n'use strict';\n\nvar utils = require('../utils');\nvar GenericWorker = require('./GenericWorker');\n\n/**\n * A worker which calculate the total length of the data flowing through.\n * @constructor\n * @param {String} propName the name used to expose the length\n */\nfunction DataLengthProbe(propName) {\n GenericWorker.call(this, \"DataLengthProbe for \" + propName);\n this.propName = propName;\n this.withStreamInfo(propName, 0);\n}\nutils.inherits(DataLengthProbe, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nDataLengthProbe.prototype.processChunk = function (chunk) {\n if(chunk) {\n var length = this.streamInfo[this.propName] || 0;\n this.streamInfo[this.propName] = length + chunk.data.length;\n }\n GenericWorker.prototype.processChunk.call(this, chunk);\n};\nmodule.exports = DataLengthProbe;\n\n\n},{\"../utils\":32,\"./GenericWorker\":28}],27:[function(require,module,exports){\n'use strict';\n\nvar utils = require('../utils');\nvar GenericWorker = require('./GenericWorker');\n\n// the size of the generated chunks\n// TODO expose this as a public variable\nvar DEFAULT_BLOCK_SIZE = 16 * 1024;\n\n/**\n * A worker that reads a content and emits chunks.\n * @constructor\n * @param {Promise} dataP the promise of the data to split\n */\nfunction DataWorker(dataP) {\n GenericWorker.call(this, \"DataWorker\");\n var self = this;\n this.dataIsReady = false;\n this.index = 0;\n this.max = 0;\n this.data = null;\n this.type = \"\";\n\n this._tickScheduled = false;\n\n dataP.then(function (data) {\n self.dataIsReady = true;\n self.data = data;\n self.max = data && data.length || 0;\n self.type = utils.getTypeOf(data);\n if(!self.isPaused) {\n self._tickAndRepeat();\n }\n }, function (e) {\n self.error(e);\n });\n}\n\nutils.inherits(DataWorker, GenericWorker);\n\n/**\n * @see GenericWorker.cleanUp\n */\nDataWorker.prototype.cleanUp = function () {\n GenericWorker.prototype.cleanUp.call(this);\n this.data = null;\n};\n\n/**\n * @see GenericWorker.resume\n */\nDataWorker.prototype.resume = function () {\n if(!GenericWorker.prototype.resume.call(this)) {\n return false;\n }\n\n if (!this._tickScheduled && this.dataIsReady) {\n this._tickScheduled = true;\n utils.delay(this._tickAndRepeat, [], this);\n }\n return true;\n};\n\n/**\n * Trigger a tick a schedule an other call to this function.\n */\nDataWorker.prototype._tickAndRepeat = function() {\n this._tickScheduled = false;\n if(this.isPaused || this.isFinished) {\n return;\n }\n this._tick();\n if(!this.isFinished) {\n utils.delay(this._tickAndRepeat, [], this);\n this._tickScheduled = true;\n }\n};\n\n/**\n * Read and push a chunk.\n */\nDataWorker.prototype._tick = function() {\n\n if(this.isPaused || this.isFinished) {\n return false;\n }\n\n var size = DEFAULT_BLOCK_SIZE;\n var data = null, nextIndex = Math.min(this.max, this.index + size);\n if (this.index >= this.max) {\n // EOF\n return this.end();\n } else {\n switch(this.type) {\n case \"string\":\n data = this.data.substring(this.index, nextIndex);\n break;\n case \"uint8array\":\n data = this.data.subarray(this.index, nextIndex);\n break;\n case \"array\":\n case \"nodebuffer\":\n data = this.data.slice(this.index, nextIndex);\n break;\n }\n this.index = nextIndex;\n return this.push({\n data : data,\n meta : {\n percent : this.max ? this.index / this.max * 100 : 0\n }\n });\n }\n};\n\nmodule.exports = DataWorker;\n\n},{\"../utils\":32,\"./GenericWorker\":28}],28:[function(require,module,exports){\n'use strict';\n\n/**\n * A worker that does nothing but passing chunks to the next one. This is like\n * a nodejs stream but with some differences. On the good side :\n * - it works on IE 6-9 without any issue / polyfill\n * - it weights less than the full dependencies bundled with browserify\n * - it forwards errors (no need to declare an error handler EVERYWHERE)\n *\n * A chunk is an object with 2 attributes : `meta` and `data`. The former is an\n * object containing anything (`percent` for example), see each worker for more\n * details. The latter is the real data (String, Uint8Array, etc).\n *\n * @constructor\n * @param {String} name the name of the stream (mainly used for debugging purposes)\n */\nfunction GenericWorker(name) {\n // the name of the worker\n this.name = name || \"default\";\n // an object containing metadata about the workers chain\n this.streamInfo = {};\n // an error which happened when the worker was paused\n this.generatedError = null;\n // an object containing metadata to be merged by this worker into the general metadata\n this.extraStreamInfo = {};\n // true if the stream is paused (and should not do anything), false otherwise\n this.isPaused = true;\n // true if the stream is finished (and should not do anything), false otherwise\n this.isFinished = false;\n // true if the stream is locked to prevent further structure updates (pipe), false otherwise\n this.isLocked = false;\n // the event listeners\n this._listeners = {\n 'data':[],\n 'end':[],\n 'error':[]\n };\n // the previous worker, if any\n this.previous = null;\n}\n\nGenericWorker.prototype = {\n /**\n * Push a chunk to the next workers.\n * @param {Object} chunk the chunk to push\n */\n push : function (chunk) {\n this.emit(\"data\", chunk);\n },\n /**\n * End the stream.\n * @return {Boolean} true if this call ended the worker, false otherwise.\n */\n end : function () {\n if (this.isFinished) {\n return false;\n }\n\n this.flush();\n try {\n this.emit(\"end\");\n this.cleanUp();\n this.isFinished = true;\n } catch (e) {\n this.emit(\"error\", e);\n }\n return true;\n },\n /**\n * End the stream with an error.\n * @param {Error} e the error which caused the premature end.\n * @return {Boolean} true if this call ended the worker with an error, false otherwise.\n */\n error : function (e) {\n if (this.isFinished) {\n return false;\n }\n\n if(this.isPaused) {\n this.generatedError = e;\n } else {\n this.isFinished = true;\n\n this.emit(\"error\", e);\n\n // in the workers chain exploded in the middle of the chain,\n // the error event will go downward but we also need to notify\n // workers upward that there has been an error.\n if(this.previous) {\n this.previous.error(e);\n }\n\n this.cleanUp();\n }\n return true;\n },\n /**\n * Add a callback on an event.\n * @param {String} name the name of the event (data, end, error)\n * @param {Function} listener the function to call when the event is triggered\n * @return {GenericWorker} the current object for chainability\n */\n on : function (name, listener) {\n this._listeners[name].push(listener);\n return this;\n },\n /**\n * Clean any references when a worker is ending.\n */\n cleanUp : function () {\n this.streamInfo = this.generatedError = this.extraStreamInfo = null;\n this._listeners = [];\n },\n /**\n * Trigger an event. This will call registered callback with the provided arg.\n * @param {String} name the name of the event (data, end, error)\n * @param {Object} arg the argument to call the callback with.\n */\n emit : function (name, arg) {\n if (this._listeners[name]) {\n for(var i = 0; i < this._listeners[name].length; i++) {\n this._listeners[name][i].call(this, arg);\n }\n }\n },\n /**\n * Chain a worker with an other.\n * @param {Worker} next the worker receiving events from the current one.\n * @return {worker} the next worker for chainability\n */\n pipe : function (next) {\n return next.registerPrevious(this);\n },\n /**\n * Same as `pipe` in the other direction.\n * Using an API with `pipe(next)` is very easy.\n * Implementing the API with the point of view of the next one registering\n * a source is easier, see the ZipFileWorker.\n * @param {Worker} previous the previous worker, sending events to this one\n * @return {Worker} the current worker for chainability\n */\n registerPrevious : function (previous) {\n if (this.isLocked) {\n throw new Error(\"The stream '\" + this + \"' has already been used.\");\n }\n\n // sharing the streamInfo...\n this.streamInfo = previous.streamInfo;\n // ... and adding our own bits\n this.mergeStreamInfo();\n this.previous = previous;\n var self = this;\n previous.on('data', function (chunk) {\n self.processChunk(chunk);\n });\n previous.on('end', function () {\n self.end();\n });\n previous.on('error', function (e) {\n self.error(e);\n });\n return this;\n },\n /**\n * Pause the stream so it doesn't send events anymore.\n * @return {Boolean} true if this call paused the worker, false otherwise.\n */\n pause : function () {\n if(this.isPaused || this.isFinished) {\n return false;\n }\n this.isPaused = true;\n\n if(this.previous) {\n this.previous.pause();\n }\n return true;\n },\n /**\n * Resume a paused stream.\n * @return {Boolean} true if this call resumed the worker, false otherwise.\n */\n resume : function () {\n if(!this.isPaused || this.isFinished) {\n return false;\n }\n this.isPaused = false;\n\n // if true, the worker tried to resume but failed\n var withError = false;\n if(this.generatedError) {\n this.error(this.generatedError);\n withError = true;\n }\n if(this.previous) {\n this.previous.resume();\n }\n\n return !withError;\n },\n /**\n * Flush any remaining bytes as the stream is ending.\n */\n flush : function () {},\n /**\n * Process a chunk. This is usually the method overridden.\n * @param {Object} chunk the chunk to process.\n */\n processChunk : function(chunk) {\n this.push(chunk);\n },\n /**\n * Add a key/value to be added in the workers chain streamInfo once activated.\n * @param {String} key the key to use\n * @param {Object} value the associated value\n * @return {Worker} the current worker for chainability\n */\n withStreamInfo : function (key, value) {\n this.extraStreamInfo[key] = value;\n this.mergeStreamInfo();\n return this;\n },\n /**\n * Merge this worker's streamInfo into the chain's streamInfo.\n */\n mergeStreamInfo : function () {\n for(var key in this.extraStreamInfo) {\n if (!this.extraStreamInfo.hasOwnProperty(key)) {\n continue;\n }\n this.streamInfo[key] = this.extraStreamInfo[key];\n }\n },\n\n /**\n * Lock the stream to prevent further updates on the workers chain.\n * After calling this method, all calls to pipe will fail.\n */\n lock: function () {\n if (this.isLocked) {\n throw new Error(\"The stream '\" + this + \"' has already been used.\");\n }\n this.isLocked = true;\n if (this.previous) {\n this.previous.lock();\n }\n },\n\n /**\n *\n * Pretty print the workers chain.\n */\n toString : function () {\n var me = \"Worker \" + this.name;\n if (this.previous) {\n return this.previous + \" -> \" + me;\n } else {\n return me;\n }\n }\n};\n\nmodule.exports = GenericWorker;\n\n},{}],29:[function(require,module,exports){\n'use strict';\n\nvar utils = require('../utils');\nvar ConvertWorker = require('./ConvertWorker');\nvar GenericWorker = require('./GenericWorker');\nvar base64 = require('../base64');\nvar support = require(\"../support\");\nvar external = require(\"../external\");\n\nvar NodejsStreamOutputAdapter = null;\nif (support.nodestream) {\n try {\n NodejsStreamOutputAdapter = require('../nodejs/NodejsStreamOutputAdapter');\n } catch(e) {}\n}\n\n/**\n * Apply the final transformation of the data. If the user wants a Blob for\n * example, it's easier to work with an U8intArray and finally do the\n * ArrayBuffer/Blob conversion.\n * @param {String} type the name of the final type\n * @param {String|Uint8Array|Buffer} content the content to transform\n * @param {String} mimeType the mime type of the content, if applicable.\n * @return {String|Uint8Array|ArrayBuffer|Buffer|Blob} the content in the right format.\n */\nfunction transformZipOutput(type, content, mimeType) {\n switch(type) {\n case \"blob\" :\n return utils.newBlob(utils.transformTo(\"arraybuffer\", content), mimeType);\n case \"base64\" :\n return base64.encode(content);\n default :\n return utils.transformTo(type, content);\n }\n}\n\n/**\n * Concatenate an array of data of the given type.\n * @param {String} type the type of the data in the given array.\n * @param {Array} dataArray the array containing the data chunks to concatenate\n * @return {String|Uint8Array|Buffer} the concatenated data\n * @throws Error if the asked type is unsupported\n */\nfunction concat (type, dataArray) {\n var i, index = 0, res = null, totalLength = 0;\n for(i = 0; i < dataArray.length; i++) {\n totalLength += dataArray[i].length;\n }\n switch(type) {\n case \"string\":\n return dataArray.join(\"\");\n case \"array\":\n return Array.prototype.concat.apply([], dataArray);\n case \"uint8array\":\n res = new Uint8Array(totalLength);\n for(i = 0; i < dataArray.length; i++) {\n res.set(dataArray[i], index);\n index += dataArray[i].length;\n }\n return res;\n case \"nodebuffer\":\n return Buffer.concat(dataArray);\n default:\n throw new Error(\"concat : unsupported type '\" + type + \"'\");\n }\n}\n\n/**\n * Listen a StreamHelper, accumulate its content and concatenate it into a\n * complete block.\n * @param {StreamHelper} helper the helper to use.\n * @param {Function} updateCallback a callback called on each update. Called\n * with one arg :\n * - the metadata linked to the update received.\n * @return Promise the promise for the accumulation.\n */\nfunction accumulate(helper, updateCallback) {\n return new external.Promise(function (resolve, reject){\n var dataArray = [];\n var chunkType = helper._internalType,\n resultType = helper._outputType,\n mimeType = helper._mimeType;\n helper\n .on('data', function (data, meta) {\n dataArray.push(data);\n if(updateCallback) {\n updateCallback(meta);\n }\n })\n .on('error', function(err) {\n dataArray = [];\n reject(err);\n })\n .on('end', function (){\n try {\n var result = transformZipOutput(resultType, concat(chunkType, dataArray), mimeType);\n resolve(result);\n } catch (e) {\n reject(e);\n }\n dataArray = [];\n })\n .resume();\n });\n}\n\n/**\n * An helper to easily use workers outside of JSZip.\n * @constructor\n * @param {Worker} worker the worker to wrap\n * @param {String} outputType the type of data expected by the use\n * @param {String} mimeType the mime type of the content, if applicable.\n */\nfunction StreamHelper(worker, outputType, mimeType) {\n var internalType = outputType;\n switch(outputType) {\n case \"blob\":\n case \"arraybuffer\":\n internalType = \"uint8array\";\n break;\n case \"base64\":\n internalType = \"string\";\n break;\n }\n\n try {\n // the type used internally\n this._internalType = internalType;\n // the type used to output results\n this._outputType = outputType;\n // the mime type\n this._mimeType = mimeType;\n utils.checkSupport(internalType);\n this._worker = worker.pipe(new ConvertWorker(internalType));\n // the last workers can be rewired without issues but we need to\n // prevent any updates on previous workers.\n worker.lock();\n } catch(e) {\n this._worker = new GenericWorker(\"error\");\n this._worker.error(e);\n }\n}\n\nStreamHelper.prototype = {\n /**\n * Listen a StreamHelper, accumulate its content and concatenate it into a\n * complete block.\n * @param {Function} updateCb the update callback.\n * @return Promise the promise for the accumulation.\n */\n accumulate : function (updateCb) {\n return accumulate(this, updateCb);\n },\n /**\n * Add a listener on an event triggered on a stream.\n * @param {String} evt the name of the event\n * @param {Function} fn the listener\n * @return {StreamHelper} the current helper.\n */\n on : function (evt, fn) {\n var self = this;\n\n if(evt === \"data\") {\n this._worker.on(evt, function (chunk) {\n fn.call(self, chunk.data, chunk.meta);\n });\n } else {\n this._worker.on(evt, function () {\n utils.delay(fn, arguments, self);\n });\n }\n return this;\n },\n /**\n * Resume the flow of chunks.\n * @return {StreamHelper} the current helper.\n */\n resume : function () {\n utils.delay(this._worker.resume, [], this._worker);\n return this;\n },\n /**\n * Pause the flow of chunks.\n * @return {StreamHelper} the current helper.\n */\n pause : function () {\n this._worker.pause();\n return this;\n },\n /**\n * Return a nodejs stream for this helper.\n * @param {Function} updateCb the update callback.\n * @return {NodejsStreamOutputAdapter} the nodejs stream.\n */\n toNodejsStream : function (updateCb) {\n utils.checkSupport(\"nodestream\");\n if (this._outputType !== \"nodebuffer\") {\n // an object stream containing blob/arraybuffer/uint8array/string\n // is strange and I don't know if it would be useful.\n // I you find this comment and have a good usecase, please open a\n // bug report !\n throw new Error(this._outputType + \" is not supported by this method\");\n }\n\n return new NodejsStreamOutputAdapter(this, {\n objectMode : this._outputType !== \"nodebuffer\"\n }, updateCb);\n }\n};\n\n\nmodule.exports = StreamHelper;\n\n},{\"../base64\":1,\"../external\":6,\"../nodejs/NodejsStreamOutputAdapter\":13,\"../support\":30,\"../utils\":32,\"./ConvertWorker\":24,\"./GenericWorker\":28}],30:[function(require,module,exports){\n'use strict';\n\nexports.base64 = true;\nexports.array = true;\nexports.string = true;\nexports.arraybuffer = typeof ArrayBuffer !== \"undefined\" && typeof Uint8Array !== \"undefined\";\nexports.nodebuffer = typeof Buffer !== \"undefined\";\n// contains true if JSZip can read/generate Uint8Array, false otherwise.\nexports.uint8array = typeof Uint8Array !== \"undefined\";\n\nif (typeof ArrayBuffer === \"undefined\") {\n exports.blob = false;\n}\nelse {\n var buffer = new ArrayBuffer(0);\n try {\n exports.blob = new Blob([buffer], {\n type: \"application/zip\"\n }).size === 0;\n }\n catch (e) {\n try {\n var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;\n var builder = new Builder();\n builder.append(buffer);\n exports.blob = builder.getBlob('application/zip').size === 0;\n }\n catch (e) {\n exports.blob = false;\n }\n }\n}\n\ntry {\n exports.nodestream = !!require('readable-stream').Readable;\n} catch(e) {\n exports.nodestream = false;\n}\n\n},{\"readable-stream\":16}],31:[function(require,module,exports){\n'use strict';\n\nvar utils = require('./utils');\nvar support = require('./support');\nvar nodejsUtils = require('./nodejsUtils');\nvar GenericWorker = require('./stream/GenericWorker');\n\n/**\n * The following functions come from pako, from pako/lib/utils/strings\n * released under the MIT license, see pako https://github.com/nodeca/pako/\n */\n\n// Table with utf8 lengths (calculated by first byte of sequence)\n// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,\n// because max possible codepoint is 0x10ffff\nvar _utf8len = new Array(256);\nfor (var i=0; i<256; i++) {\n _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);\n}\n_utf8len[254]=_utf8len[254]=1; // Invalid sequence start\n\n// convert string to array (typed, when possible)\nvar string2buf = function (str) {\n var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;\n\n // count binary size\n for (m_pos = 0; m_pos < str_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {\n c2 = str.charCodeAt(m_pos+1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;\n }\n\n // allocate buffer\n if (support.uint8array) {\n buf = new Uint8Array(buf_len);\n } else {\n buf = new Array(buf_len);\n }\n\n // convert\n for (i=0, m_pos = 0; i < buf_len; m_pos++) {\n c = str.charCodeAt(m_pos);\n if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {\n c2 = str.charCodeAt(m_pos+1);\n if ((c2 & 0xfc00) === 0xdc00) {\n c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);\n m_pos++;\n }\n }\n if (c < 0x80) {\n /* one byte */\n buf[i++] = c;\n } else if (c < 0x800) {\n /* two bytes */\n buf[i++] = 0xC0 | (c >>> 6);\n buf[i++] = 0x80 | (c & 0x3f);\n } else if (c < 0x10000) {\n /* three bytes */\n buf[i++] = 0xE0 | (c >>> 12);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n } else {\n /* four bytes */\n buf[i++] = 0xf0 | (c >>> 18);\n buf[i++] = 0x80 | (c >>> 12 & 0x3f);\n buf[i++] = 0x80 | (c >>> 6 & 0x3f);\n buf[i++] = 0x80 | (c & 0x3f);\n }\n }\n\n return buf;\n};\n\n// Calculate max possible position in utf8 buffer,\n// that will not break sequence. If that's not possible\n// - (very small limits) return max size as is.\n//\n// buf[] - utf8 bytes array\n// max - length limit (mandatory);\nvar utf8border = function(buf, max) {\n var pos;\n\n max = max || buf.length;\n if (max > buf.length) { max = buf.length; }\n\n // go back from last position, until start of sequence found\n pos = max-1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // Fuckup - very small and broken sequence,\n // return max, because we should return something anyway.\n if (pos < 0) { return max; }\n\n // If we came to start of buffer - that means vuffer is too small,\n // return max too.\n if (pos === 0) { return max; }\n\n return (pos + _utf8len[buf[pos]] > max) ? pos : max;\n};\n\n// convert array to string\nvar buf2string = function (buf) {\n var str, i, out, c, c_len;\n var len = buf.length;\n\n // Reserve max possible length (2 words per char)\n // NB: by unknown reasons, Array is significantly faster for\n // String.fromCharCode.apply than Uint16Array.\n var utf16buf = new Array(len*2);\n\n for (out=0, i=0; i 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }\n\n // apply mask on first byte\n c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;\n // join the rest\n while (c_len > 1 && i < len) {\n c = (c << 6) | (buf[i++] & 0x3f);\n c_len--;\n }\n\n // terminated by end of string?\n if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }\n\n if (c < 0x10000) {\n utf16buf[out++] = c;\n } else {\n c -= 0x10000;\n utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);\n utf16buf[out++] = 0xdc00 | (c & 0x3ff);\n }\n }\n\n // shrinkBuf(utf16buf, out)\n if (utf16buf.length !== out) {\n if(utf16buf.subarray) {\n utf16buf = utf16buf.subarray(0, out);\n } else {\n utf16buf.length = out;\n }\n }\n\n // return String.fromCharCode.apply(null, utf16buf);\n return utils.applyFromCharCode(utf16buf);\n};\n\n\n// That's all for the pako functions.\n\n\n/**\n * Transform a javascript string into an array (typed if possible) of bytes,\n * UTF-8 encoded.\n * @param {String} str the string to encode\n * @return {Array|Uint8Array|Buffer} the UTF-8 encoded string.\n */\nexports.utf8encode = function utf8encode(str) {\n if (support.nodebuffer) {\n return nodejsUtils.newBufferFrom(str, \"utf-8\");\n }\n\n return string2buf(str);\n};\n\n\n/**\n * Transform a bytes array (or a representation) representing an UTF-8 encoded\n * string into a javascript string.\n * @param {Array|Uint8Array|Buffer} buf the data de decode\n * @return {String} the decoded string.\n */\nexports.utf8decode = function utf8decode(buf) {\n if (support.nodebuffer) {\n return utils.transformTo(\"nodebuffer\", buf).toString(\"utf-8\");\n }\n\n buf = utils.transformTo(support.uint8array ? \"uint8array\" : \"array\", buf);\n\n return buf2string(buf);\n};\n\n/**\n * A worker to decode utf8 encoded binary chunks into string chunks.\n * @constructor\n */\nfunction Utf8DecodeWorker() {\n GenericWorker.call(this, \"utf-8 decode\");\n // the last bytes if a chunk didn't end with a complete codepoint.\n this.leftOver = null;\n}\nutils.inherits(Utf8DecodeWorker, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nUtf8DecodeWorker.prototype.processChunk = function (chunk) {\n\n var data = utils.transformTo(support.uint8array ? \"uint8array\" : \"array\", chunk.data);\n\n // 1st step, re-use what's left of the previous chunk\n if (this.leftOver && this.leftOver.length) {\n if(support.uint8array) {\n var previousData = data;\n data = new Uint8Array(previousData.length + this.leftOver.length);\n data.set(this.leftOver, 0);\n data.set(previousData, this.leftOver.length);\n } else {\n data = this.leftOver.concat(data);\n }\n this.leftOver = null;\n }\n\n var nextBoundary = utf8border(data);\n var usableData = data;\n if (nextBoundary !== data.length) {\n if (support.uint8array) {\n usableData = data.subarray(0, nextBoundary);\n this.leftOver = data.subarray(nextBoundary, data.length);\n } else {\n usableData = data.slice(0, nextBoundary);\n this.leftOver = data.slice(nextBoundary, data.length);\n }\n }\n\n this.push({\n data : exports.utf8decode(usableData),\n meta : chunk.meta\n });\n};\n\n/**\n * @see GenericWorker.flush\n */\nUtf8DecodeWorker.prototype.flush = function () {\n if(this.leftOver && this.leftOver.length) {\n this.push({\n data : exports.utf8decode(this.leftOver),\n meta : {}\n });\n this.leftOver = null;\n }\n};\nexports.Utf8DecodeWorker = Utf8DecodeWorker;\n\n/**\n * A worker to endcode string chunks into utf8 encoded binary chunks.\n * @constructor\n */\nfunction Utf8EncodeWorker() {\n GenericWorker.call(this, \"utf-8 encode\");\n}\nutils.inherits(Utf8EncodeWorker, GenericWorker);\n\n/**\n * @see GenericWorker.processChunk\n */\nUtf8EncodeWorker.prototype.processChunk = function (chunk) {\n this.push({\n data : exports.utf8encode(chunk.data),\n meta : chunk.meta\n });\n};\nexports.Utf8EncodeWorker = Utf8EncodeWorker;\n\n},{\"./nodejsUtils\":14,\"./stream/GenericWorker\":28,\"./support\":30,\"./utils\":32}],32:[function(require,module,exports){\n'use strict';\n\nvar support = require('./support');\nvar base64 = require('./base64');\nvar nodejsUtils = require('./nodejsUtils');\nvar setImmediate = require('set-immediate-shim');\nvar external = require(\"./external\");\n\n\n/**\n * Convert a string that pass as a \"binary string\": it should represent a byte\n * array but may have > 255 char codes. Be sure to take only the first byte\n * and returns the byte array.\n * @param {String} str the string to transform.\n * @return {Array|Uint8Array} the string in a binary format.\n */\nfunction string2binary(str) {\n var result = null;\n if (support.uint8array) {\n result = new Uint8Array(str.length);\n } else {\n result = new Array(str.length);\n }\n return stringToArrayLike(str, result);\n}\n\n/**\n * Create a new blob with the given content and the given type.\n * @param {String|ArrayBuffer} part the content to put in the blob. DO NOT use\n * an Uint8Array because the stock browser of android 4 won't accept it (it\n * will be silently converted to a string, \"[object Uint8Array]\").\n *\n * Use only ONE part to build the blob to avoid a memory leak in IE11 / Edge:\n * when a large amount of Array is used to create the Blob, the amount of\n * memory consumed is nearly 100 times the original data amount.\n *\n * @param {String} type the mime type of the blob.\n * @return {Blob} the created blob.\n */\nexports.newBlob = function(part, type) {\n exports.checkSupport(\"blob\");\n\n try {\n // Blob constructor\n return new Blob([part], {\n type: type\n });\n }\n catch (e) {\n\n try {\n // deprecated, browser only, old way\n var Builder = self.BlobBuilder || self.WebKitBlobBuilder || self.MozBlobBuilder || self.MSBlobBuilder;\n var builder = new Builder();\n builder.append(part);\n return builder.getBlob(type);\n }\n catch (e) {\n\n // well, fuck ?!\n throw new Error(\"Bug : can't construct the Blob.\");\n }\n }\n\n\n};\n/**\n * The identity function.\n * @param {Object} input the input.\n * @return {Object} the same input.\n */\nfunction identity(input) {\n return input;\n}\n\n/**\n * Fill in an array with a string.\n * @param {String} str the string to use.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to fill in (will be mutated).\n * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated array.\n */\nfunction stringToArrayLike(str, array) {\n for (var i = 0; i < str.length; ++i) {\n array[i] = str.charCodeAt(i) & 0xFF;\n }\n return array;\n}\n\n/**\n * An helper for the function arrayLikeToString.\n * This contains static information and functions that\n * can be optimized by the browser JIT compiler.\n */\nvar arrayToStringHelper = {\n /**\n * Transform an array of int into a string, chunk by chunk.\n * See the performances notes on arrayLikeToString.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.\n * @param {String} type the type of the array.\n * @param {Integer} chunk the chunk size.\n * @return {String} the resulting string.\n * @throws Error if the chunk is too big for the stack.\n */\n stringifyByChunk: function(array, type, chunk) {\n var result = [], k = 0, len = array.length;\n // shortcut\n if (len <= chunk) {\n return String.fromCharCode.apply(null, array);\n }\n while (k < len) {\n if (type === \"array\" || type === \"nodebuffer\") {\n result.push(String.fromCharCode.apply(null, array.slice(k, Math.min(k + chunk, len))));\n }\n else {\n result.push(String.fromCharCode.apply(null, array.subarray(k, Math.min(k + chunk, len))));\n }\n k += chunk;\n }\n return result.join(\"\");\n },\n /**\n * Call String.fromCharCode on every item in the array.\n * This is the naive implementation, which generate A LOT of intermediate string.\n * This should be used when everything else fail.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.\n * @return {String} the result.\n */\n stringifyByChar: function(array){\n var resultStr = \"\";\n for(var i = 0; i < array.length; i++) {\n resultStr += String.fromCharCode(array[i]);\n }\n return resultStr;\n },\n applyCanBeUsed : {\n /**\n * true if the browser accepts to use String.fromCharCode on Uint8Array\n */\n uint8array : (function () {\n try {\n return support.uint8array && String.fromCharCode.apply(null, new Uint8Array(1)).length === 1;\n } catch (e) {\n return false;\n }\n })(),\n /**\n * true if the browser accepts to use String.fromCharCode on nodejs Buffer.\n */\n nodebuffer : (function () {\n try {\n return support.nodebuffer && String.fromCharCode.apply(null, nodejsUtils.allocBuffer(1)).length === 1;\n } catch (e) {\n return false;\n }\n })()\n }\n};\n\n/**\n * Transform an array-like object to a string.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} array the array to transform.\n * @return {String} the result.\n */\nfunction arrayLikeToString(array) {\n // Performances notes :\n // --------------------\n // String.fromCharCode.apply(null, array) is the fastest, see\n // see http://jsperf.com/converting-a-uint8array-to-a-string/2\n // but the stack is limited (and we can get huge arrays !).\n //\n // result += String.fromCharCode(array[i]); generate too many strings !\n //\n // This code is inspired by http://jsperf.com/arraybuffer-to-string-apply-performance/2\n // TODO : we now have workers that split the work. Do we still need that ?\n var chunk = 65536,\n type = exports.getTypeOf(array),\n canUseApply = true;\n if (type === \"uint8array\") {\n canUseApply = arrayToStringHelper.applyCanBeUsed.uint8array;\n } else if (type === \"nodebuffer\") {\n canUseApply = arrayToStringHelper.applyCanBeUsed.nodebuffer;\n }\n\n if (canUseApply) {\n while (chunk > 1) {\n try {\n return arrayToStringHelper.stringifyByChunk(array, type, chunk);\n } catch (e) {\n chunk = Math.floor(chunk / 2);\n }\n }\n }\n\n // no apply or chunk error : slow and painful algorithm\n // default browser on android 4.*\n return arrayToStringHelper.stringifyByChar(array);\n}\n\nexports.applyFromCharCode = arrayLikeToString;\n\n\n/**\n * Copy the data from an array-like to an other array-like.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayFrom the origin array.\n * @param {Array|ArrayBuffer|Uint8Array|Buffer} arrayTo the destination array which will be mutated.\n * @return {Array|ArrayBuffer|Uint8Array|Buffer} the updated destination array.\n */\nfunction arrayLikeToArrayLike(arrayFrom, arrayTo) {\n for (var i = 0; i < arrayFrom.length; i++) {\n arrayTo[i] = arrayFrom[i];\n }\n return arrayTo;\n}\n\n// a matrix containing functions to transform everything into everything.\nvar transform = {};\n\n// string to ?\ntransform[\"string\"] = {\n \"string\": identity,\n \"array\": function(input) {\n return stringToArrayLike(input, new Array(input.length));\n },\n \"arraybuffer\": function(input) {\n return transform[\"string\"][\"uint8array\"](input).buffer;\n },\n \"uint8array\": function(input) {\n return stringToArrayLike(input, new Uint8Array(input.length));\n },\n \"nodebuffer\": function(input) {\n return stringToArrayLike(input, nodejsUtils.allocBuffer(input.length));\n }\n};\n\n// array to ?\ntransform[\"array\"] = {\n \"string\": arrayLikeToString,\n \"array\": identity,\n \"arraybuffer\": function(input) {\n return (new Uint8Array(input)).buffer;\n },\n \"uint8array\": function(input) {\n return new Uint8Array(input);\n },\n \"nodebuffer\": function(input) {\n return nodejsUtils.newBufferFrom(input);\n }\n};\n\n// arraybuffer to ?\ntransform[\"arraybuffer\"] = {\n \"string\": function(input) {\n return arrayLikeToString(new Uint8Array(input));\n },\n \"array\": function(input) {\n return arrayLikeToArrayLike(new Uint8Array(input), new Array(input.byteLength));\n },\n \"arraybuffer\": identity,\n \"uint8array\": function(input) {\n return new Uint8Array(input);\n },\n \"nodebuffer\": function(input) {\n return nodejsUtils.newBufferFrom(new Uint8Array(input));\n }\n};\n\n// uint8array to ?\ntransform[\"uint8array\"] = {\n \"string\": arrayLikeToString,\n \"array\": function(input) {\n return arrayLikeToArrayLike(input, new Array(input.length));\n },\n \"arraybuffer\": function(input) {\n return input.buffer;\n },\n \"uint8array\": identity,\n \"nodebuffer\": function(input) {\n return nodejsUtils.newBufferFrom(input);\n }\n};\n\n// nodebuffer to ?\ntransform[\"nodebuffer\"] = {\n \"string\": arrayLikeToString,\n \"array\": function(input) {\n return arrayLikeToArrayLike(input, new Array(input.length));\n },\n \"arraybuffer\": function(input) {\n return transform[\"nodebuffer\"][\"uint8array\"](input).buffer;\n },\n \"uint8array\": function(input) {\n return arrayLikeToArrayLike(input, new Uint8Array(input.length));\n },\n \"nodebuffer\": identity\n};\n\n/**\n * Transform an input into any type.\n * The supported output type are : string, array, uint8array, arraybuffer, nodebuffer.\n * If no output type is specified, the unmodified input will be returned.\n * @param {String} outputType the output type.\n * @param {String|Array|ArrayBuffer|Uint8Array|Buffer} input the input to convert.\n * @throws {Error} an Error if the browser doesn't support the requested output type.\n */\nexports.transformTo = function(outputType, input) {\n if (!input) {\n // undefined, null, etc\n // an empty string won't harm.\n input = \"\";\n }\n if (!outputType) {\n return input;\n }\n exports.checkSupport(outputType);\n var inputType = exports.getTypeOf(input);\n var result = transform[inputType][outputType](input);\n return result;\n};\n\n/**\n * Return the type of the input.\n * The type will be in a format valid for JSZip.utils.transformTo : string, array, uint8array, arraybuffer.\n * @param {Object} input the input to identify.\n * @return {String} the (lowercase) type of the input.\n */\nexports.getTypeOf = function(input) {\n if (typeof input === \"string\") {\n return \"string\";\n }\n if (Object.prototype.toString.call(input) === \"[object Array]\") {\n return \"array\";\n }\n if (support.nodebuffer && nodejsUtils.isBuffer(input)) {\n return \"nodebuffer\";\n }\n if (support.uint8array && input instanceof Uint8Array) {\n return \"uint8array\";\n }\n if (support.arraybuffer && input instanceof ArrayBuffer) {\n return \"arraybuffer\";\n }\n};\n\n/**\n * Throw an exception if the type is not supported.\n * @param {String} type the type to check.\n * @throws {Error} an Error if the browser doesn't support the requested type.\n */\nexports.checkSupport = function(type) {\n var supported = support[type.toLowerCase()];\n if (!supported) {\n throw new Error(type + \" is not supported by this platform\");\n }\n};\n\nexports.MAX_VALUE_16BITS = 65535;\nexports.MAX_VALUE_32BITS = -1; // well, \"\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\\xFF\" is parsed as -1\n\n/**\n * Prettify a string read as binary.\n * @param {string} str the string to prettify.\n * @return {string} a pretty string.\n */\nexports.pretty = function(str) {\n var res = '',\n code, i;\n for (i = 0; i < (str || \"\").length; i++) {\n code = str.charCodeAt(i);\n res += '\\\\x' + (code < 16 ? \"0\" : \"\") + code.toString(16).toUpperCase();\n }\n return res;\n};\n\n/**\n * Defer the call of a function.\n * @param {Function} callback the function to call asynchronously.\n * @param {Array} args the arguments to give to the callback.\n */\nexports.delay = function(callback, args, self) {\n setImmediate(function () {\n callback.apply(self || null, args || []);\n });\n};\n\n/**\n * Extends a prototype with an other, without calling a constructor with\n * side effects. Inspired by nodejs' `utils.inherits`\n * @param {Function} ctor the constructor to augment\n * @param {Function} superCtor the parent constructor to use\n */\nexports.inherits = function (ctor, superCtor) {\n var Obj = function() {};\n Obj.prototype = superCtor.prototype;\n ctor.prototype = new Obj();\n};\n\n/**\n * Merge the objects passed as parameters into a new one.\n * @private\n * @param {...Object} var_args All objects to merge.\n * @return {Object} a new object with the data of the others.\n */\nexports.extend = function() {\n var result = {}, i, attr;\n for (i = 0; i < arguments.length; i++) { // arguments is not enumerable in some browsers\n for (attr in arguments[i]) {\n if (arguments[i].hasOwnProperty(attr) && typeof result[attr] === \"undefined\") {\n result[attr] = arguments[i][attr];\n }\n }\n }\n return result;\n};\n\n/**\n * Transform arbitrary content into a Promise.\n * @param {String} name a name for the content being processed.\n * @param {Object} inputData the content to process.\n * @param {Boolean} isBinary true if the content is not an unicode string\n * @param {Boolean} isOptimizedBinaryString true if the string content only has one byte per character.\n * @param {Boolean} isBase64 true if the string content is encoded with base64.\n * @return {Promise} a promise in a format usable by JSZip.\n */\nexports.prepareContent = function(name, inputData, isBinary, isOptimizedBinaryString, isBase64) {\n\n // if inputData is already a promise, this flatten it.\n var promise = external.Promise.resolve(inputData).then(function(data) {\n \n \n var isBlob = support.blob && (data instanceof Blob || ['[object File]', '[object Blob]'].indexOf(Object.prototype.toString.call(data)) !== -1);\n\n if (isBlob && typeof FileReader !== \"undefined\") {\n return new external.Promise(function (resolve, reject) {\n var reader = new FileReader();\n\n reader.onload = function(e) {\n resolve(e.target.result);\n };\n reader.onerror = function(e) {\n reject(e.target.error);\n };\n reader.readAsArrayBuffer(data);\n });\n } else {\n return data;\n }\n });\n\n return promise.then(function(data) {\n var dataType = exports.getTypeOf(data);\n\n if (!dataType) {\n return external.Promise.reject(\n new Error(\"Can't read the data of '\" + name + \"'. Is it \" +\n \"in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?\")\n );\n }\n // special case : it's way easier to work with Uint8Array than with ArrayBuffer\n if (dataType === \"arraybuffer\") {\n data = exports.transformTo(\"uint8array\", data);\n } else if (dataType === \"string\") {\n if (isBase64) {\n data = base64.decode(data);\n }\n else if (isBinary) {\n // optimizedBinaryString === true means that the file has already been filtered with a 0xFF mask\n if (isOptimizedBinaryString !== true) {\n // this is a string, not in a base64 format.\n // Be sure that this is a correct \"binary string\"\n data = string2binary(data);\n }\n }\n }\n return data;\n });\n};\n\n},{\"./base64\":1,\"./external\":6,\"./nodejsUtils\":14,\"./support\":30,\"set-immediate-shim\":54}],33:[function(require,module,exports){\n'use strict';\nvar readerFor = require('./reader/readerFor');\nvar utils = require('./utils');\nvar sig = require('./signature');\nvar ZipEntry = require('./zipEntry');\nvar utf8 = require('./utf8');\nvar support = require('./support');\n// class ZipEntries {{{\n/**\n * All the entries in the zip file.\n * @constructor\n * @param {Object} loadOptions Options for loading the stream.\n */\nfunction ZipEntries(loadOptions) {\n this.files = [];\n this.loadOptions = loadOptions;\n}\nZipEntries.prototype = {\n /**\n * Check that the reader is on the specified signature.\n * @param {string} expectedSignature the expected signature.\n * @throws {Error} if it is an other signature.\n */\n checkSignature: function(expectedSignature) {\n if (!this.reader.readAndCheckSignature(expectedSignature)) {\n this.reader.index -= 4;\n var signature = this.reader.readString(4);\n throw new Error(\"Corrupted zip or bug: unexpected signature \" + \"(\" + utils.pretty(signature) + \", expected \" + utils.pretty(expectedSignature) + \")\");\n }\n },\n /**\n * Check if the given signature is at the given index.\n * @param {number} askedIndex the index to check.\n * @param {string} expectedSignature the signature to expect.\n * @return {boolean} true if the signature is here, false otherwise.\n */\n isSignature: function(askedIndex, expectedSignature) {\n var currentIndex = this.reader.index;\n this.reader.setIndex(askedIndex);\n var signature = this.reader.readString(4);\n var result = signature === expectedSignature;\n this.reader.setIndex(currentIndex);\n return result;\n },\n /**\n * Read the end of the central directory.\n */\n readBlockEndOfCentral: function() {\n this.diskNumber = this.reader.readInt(2);\n this.diskWithCentralDirStart = this.reader.readInt(2);\n this.centralDirRecordsOnThisDisk = this.reader.readInt(2);\n this.centralDirRecords = this.reader.readInt(2);\n this.centralDirSize = this.reader.readInt(4);\n this.centralDirOffset = this.reader.readInt(4);\n\n this.zipCommentLength = this.reader.readInt(2);\n // warning : the encoding depends of the system locale\n // On a linux machine with LANG=en_US.utf8, this field is utf8 encoded.\n // On a windows machine, this field is encoded with the localized windows code page.\n var zipComment = this.reader.readData(this.zipCommentLength);\n var decodeParamType = support.uint8array ? \"uint8array\" : \"array\";\n // To get consistent behavior with the generation part, we will assume that\n // this is utf8 encoded unless specified otherwise.\n var decodeContent = utils.transformTo(decodeParamType, zipComment);\n this.zipComment = this.loadOptions.decodeFileName(decodeContent);\n },\n /**\n * Read the end of the Zip 64 central directory.\n * Not merged with the method readEndOfCentral :\n * The end of central can coexist with its Zip64 brother,\n * I don't want to read the wrong number of bytes !\n */\n readBlockZip64EndOfCentral: function() {\n this.zip64EndOfCentralSize = this.reader.readInt(8);\n this.reader.skip(4);\n // this.versionMadeBy = this.reader.readString(2);\n // this.versionNeeded = this.reader.readInt(2);\n this.diskNumber = this.reader.readInt(4);\n this.diskWithCentralDirStart = this.reader.readInt(4);\n this.centralDirRecordsOnThisDisk = this.reader.readInt(8);\n this.centralDirRecords = this.reader.readInt(8);\n this.centralDirSize = this.reader.readInt(8);\n this.centralDirOffset = this.reader.readInt(8);\n\n this.zip64ExtensibleData = {};\n var extraDataSize = this.zip64EndOfCentralSize - 44,\n index = 0,\n extraFieldId,\n extraFieldLength,\n extraFieldValue;\n while (index < extraDataSize) {\n extraFieldId = this.reader.readInt(2);\n extraFieldLength = this.reader.readInt(4);\n extraFieldValue = this.reader.readData(extraFieldLength);\n this.zip64ExtensibleData[extraFieldId] = {\n id: extraFieldId,\n length: extraFieldLength,\n value: extraFieldValue\n };\n }\n },\n /**\n * Read the end of the Zip 64 central directory locator.\n */\n readBlockZip64EndOfCentralLocator: function() {\n this.diskWithZip64CentralDirStart = this.reader.readInt(4);\n this.relativeOffsetEndOfZip64CentralDir = this.reader.readInt(8);\n this.disksCount = this.reader.readInt(4);\n if (this.disksCount > 1) {\n throw new Error(\"Multi-volumes zip are not supported\");\n }\n },\n /**\n * Read the local files, based on the offset read in the central part.\n */\n readLocalFiles: function() {\n var i, file;\n for (i = 0; i < this.files.length; i++) {\n file = this.files[i];\n this.reader.setIndex(file.localHeaderOffset);\n this.checkSignature(sig.LOCAL_FILE_HEADER);\n file.readLocalPart(this.reader);\n file.handleUTF8();\n file.processAttributes();\n }\n },\n /**\n * Read the central directory.\n */\n readCentralDir: function() {\n var file;\n\n this.reader.setIndex(this.centralDirOffset);\n while (this.reader.readAndCheckSignature(sig.CENTRAL_FILE_HEADER)) {\n file = new ZipEntry({\n zip64: this.zip64\n }, this.loadOptions);\n file.readCentralPart(this.reader);\n this.files.push(file);\n }\n\n if (this.centralDirRecords !== this.files.length) {\n if (this.centralDirRecords !== 0 && this.files.length === 0) {\n // We expected some records but couldn't find ANY.\n // This is really suspicious, as if something went wrong.\n throw new Error(\"Corrupted zip or bug: expected \" + this.centralDirRecords + \" records in central dir, got \" + this.files.length);\n } else {\n // We found some records but not all.\n // Something is wrong but we got something for the user: no error here.\n // console.warn(\"expected\", this.centralDirRecords, \"records in central dir, got\", this.files.length);\n }\n }\n },\n /**\n * Read the end of central directory.\n */\n readEndOfCentral: function() {\n var offset = this.reader.lastIndexOfSignature(sig.CENTRAL_DIRECTORY_END);\n if (offset < 0) {\n // Check if the content is a truncated zip or complete garbage.\n // A \"LOCAL_FILE_HEADER\" is not required at the beginning (auto\n // extractible zip for example) but it can give a good hint.\n // If an ajax request was used without responseType, we will also\n // get unreadable data.\n var isGarbage = !this.isSignature(0, sig.LOCAL_FILE_HEADER);\n\n if (isGarbage) {\n throw new Error(\"Can't find end of central directory : is this a zip file ? \" +\n \"If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html\");\n } else {\n throw new Error(\"Corrupted zip: can't find end of central directory\");\n }\n\n }\n this.reader.setIndex(offset);\n var endOfCentralDirOffset = offset;\n this.checkSignature(sig.CENTRAL_DIRECTORY_END);\n this.readBlockEndOfCentral();\n\n\n /* extract from the zip spec :\n 4) If one of the fields in the end of central directory\n record is too small to hold required data, the field\n should be set to -1 (0xFFFF or 0xFFFFFFFF) and the\n ZIP64 format record should be created.\n 5) The end of central directory record and the\n Zip64 end of central directory locator record must\n reside on the same disk when splitting or spanning\n an archive.\n */\n 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) {\n this.zip64 = true;\n\n /*\n Warning : the zip64 extension is supported, but ONLY if the 64bits integer read from\n the zip file can fit into a 32bits integer. This cannot be solved : JavaScript represents\n all numbers as 64-bit double precision IEEE 754 floating point numbers.\n So, we have 53bits for integers and bitwise operations treat everything as 32bits.\n see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Bitwise_Operators\n and http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf section 8.5\n */\n\n // should look for a zip64 EOCD locator\n offset = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);\n if (offset < 0) {\n throw new Error(\"Corrupted zip: can't find the ZIP64 end of central directory locator\");\n }\n this.reader.setIndex(offset);\n this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_LOCATOR);\n this.readBlockZip64EndOfCentralLocator();\n\n // now the zip64 EOCD record\n if (!this.isSignature(this.relativeOffsetEndOfZip64CentralDir, sig.ZIP64_CENTRAL_DIRECTORY_END)) {\n // console.warn(\"ZIP64 end of central directory not where expected.\");\n this.relativeOffsetEndOfZip64CentralDir = this.reader.lastIndexOfSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);\n if (this.relativeOffsetEndOfZip64CentralDir < 0) {\n throw new Error(\"Corrupted zip: can't find the ZIP64 end of central directory\");\n }\n }\n this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir);\n this.checkSignature(sig.ZIP64_CENTRAL_DIRECTORY_END);\n this.readBlockZip64EndOfCentral();\n }\n\n var expectedEndOfCentralDirOffset = this.centralDirOffset + this.centralDirSize;\n if (this.zip64) {\n expectedEndOfCentralDirOffset += 20; // end of central dir 64 locator\n expectedEndOfCentralDirOffset += 12 /* should not include the leading 12 bytes */ + this.zip64EndOfCentralSize;\n }\n\n var extraBytes = endOfCentralDirOffset - expectedEndOfCentralDirOffset;\n\n if (extraBytes > 0) {\n // console.warn(extraBytes, \"extra bytes at beginning or within zipfile\");\n if (this.isSignature(endOfCentralDirOffset, sig.CENTRAL_FILE_HEADER)) {\n // The offsets seem wrong, but we have something at the specified offset.\n // So… we keep it.\n } else {\n // the offset is wrong, update the \"zero\" of the reader\n // this happens if data has been prepended (crx files for example)\n this.reader.zero = extraBytes;\n }\n } else if (extraBytes < 0) {\n throw new Error(\"Corrupted zip: missing \" + Math.abs(extraBytes) + \" bytes.\");\n }\n },\n prepareReader: function(data) {\n this.reader = readerFor(data);\n },\n /**\n * Read a zip file and create ZipEntries.\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the binary string representing a zip file.\n */\n load: function(data) {\n this.prepareReader(data);\n this.readEndOfCentral();\n this.readCentralDir();\n this.readLocalFiles();\n }\n};\n// }}} end of ZipEntries\nmodule.exports = ZipEntries;\n\n},{\"./reader/readerFor\":22,\"./signature\":23,\"./support\":30,\"./utf8\":31,\"./utils\":32,\"./zipEntry\":34}],34:[function(require,module,exports){\n'use strict';\nvar readerFor = require('./reader/readerFor');\nvar utils = require('./utils');\nvar CompressedObject = require('./compressedObject');\nvar crc32fn = require('./crc32');\nvar utf8 = require('./utf8');\nvar compressions = require('./compressions');\nvar support = require('./support');\n\nvar MADE_BY_DOS = 0x00;\nvar MADE_BY_UNIX = 0x03;\n\n/**\n * Find a compression registered in JSZip.\n * @param {string} compressionMethod the method magic to find.\n * @return {Object|null} the JSZip compression object, null if none found.\n */\nvar findCompression = function(compressionMethod) {\n for (var method in compressions) {\n if (!compressions.hasOwnProperty(method)) {\n continue;\n }\n if (compressions[method].magic === compressionMethod) {\n return compressions[method];\n }\n }\n return null;\n};\n\n// class ZipEntry {{{\n/**\n * An entry in the zip file.\n * @constructor\n * @param {Object} options Options of the current file.\n * @param {Object} loadOptions Options for loading the stream.\n */\nfunction ZipEntry(options, loadOptions) {\n this.options = options;\n this.loadOptions = loadOptions;\n}\nZipEntry.prototype = {\n /**\n * say if the file is encrypted.\n * @return {boolean} true if the file is encrypted, false otherwise.\n */\n isEncrypted: function() {\n // bit 1 is set\n return (this.bitFlag & 0x0001) === 0x0001;\n },\n /**\n * say if the file has utf-8 filename/comment.\n * @return {boolean} true if the filename/comment is in utf-8, false otherwise.\n */\n useUTF8: function() {\n // bit 11 is set\n return (this.bitFlag & 0x0800) === 0x0800;\n },\n /**\n * Read the local part of a zip file and add the info in this object.\n * @param {DataReader} reader the reader to use.\n */\n readLocalPart: function(reader) {\n var compression, localExtraFieldsLength;\n\n // we already know everything from the central dir !\n // If the central dir data are false, we are doomed.\n // On the bright side, the local part is scary : zip64, data descriptors, both, etc.\n // The less data we get here, the more reliable this should be.\n // Let's skip the whole header and dash to the data !\n reader.skip(22);\n // in some zip created on windows, the filename stored in the central dir contains \\ instead of /.\n // Strangely, the filename here is OK.\n // I would love to treat these zip files as corrupted (see http://www.info-zip.org/FAQ.html#backslashes\n // or APPNOTE#4.4.17.1, \"All slashes MUST be forward slashes '/'\") but there are a lot of bad zip generators...\n // Search \"unzip mismatching \"local\" filename continuing with \"central\" filename version\" on\n // the internet.\n //\n // I think I see the logic here : the central directory is used to display\n // content and the local directory is used to extract the files. Mixing / and \\\n // may be used to display \\ to windows users and use / when extracting the files.\n // Unfortunately, this lead also to some issues : http://seclists.org/fulldisclosure/2009/Sep/394\n this.fileNameLength = reader.readInt(2);\n localExtraFieldsLength = reader.readInt(2); // can't be sure this will be the same as the central dir\n // the fileName is stored as binary data, the handleUTF8 method will take care of the encoding.\n this.fileName = reader.readData(this.fileNameLength);\n reader.skip(localExtraFieldsLength);\n\n if (this.compressedSize === -1 || this.uncompressedSize === -1) {\n throw new Error(\"Bug or corrupted zip : didn't get enough information from the central directory \" + \"(compressedSize === -1 || uncompressedSize === -1)\");\n }\n\n compression = findCompression(this.compressionMethod);\n if (compression === null) { // no compression found\n throw new Error(\"Corrupted zip : compression \" + utils.pretty(this.compressionMethod) + \" unknown (inner file : \" + utils.transformTo(\"string\", this.fileName) + \")\");\n }\n this.decompressed = new CompressedObject(this.compressedSize, this.uncompressedSize, this.crc32, compression, reader.readData(this.compressedSize));\n },\n\n /**\n * Read the central part of a zip file and add the info in this object.\n * @param {DataReader} reader the reader to use.\n */\n readCentralPart: function(reader) {\n this.versionMadeBy = reader.readInt(2);\n reader.skip(2);\n // this.versionNeeded = reader.readInt(2);\n this.bitFlag = reader.readInt(2);\n this.compressionMethod = reader.readString(2);\n this.date = reader.readDate();\n this.crc32 = reader.readInt(4);\n this.compressedSize = reader.readInt(4);\n this.uncompressedSize = reader.readInt(4);\n var fileNameLength = reader.readInt(2);\n this.extraFieldsLength = reader.readInt(2);\n this.fileCommentLength = reader.readInt(2);\n this.diskNumberStart = reader.readInt(2);\n this.internalFileAttributes = reader.readInt(2);\n this.externalFileAttributes = reader.readInt(4);\n this.localHeaderOffset = reader.readInt(4);\n\n if (this.isEncrypted()) {\n throw new Error(\"Encrypted zip are not supported\");\n }\n\n // will be read in the local part, see the comments there\n reader.skip(fileNameLength);\n this.readExtraFields(reader);\n this.parseZIP64ExtraField(reader);\n this.fileComment = reader.readData(this.fileCommentLength);\n },\n\n /**\n * Parse the external file attributes and get the unix/dos permissions.\n */\n processAttributes: function () {\n this.unixPermissions = null;\n this.dosPermissions = null;\n var madeBy = this.versionMadeBy >> 8;\n\n // Check if we have the DOS directory flag set.\n // We look for it in the DOS and UNIX permissions\n // but some unknown platform could set it as a compatibility flag.\n this.dir = this.externalFileAttributes & 0x0010 ? true : false;\n\n if(madeBy === MADE_BY_DOS) {\n // first 6 bits (0 to 5)\n this.dosPermissions = this.externalFileAttributes & 0x3F;\n }\n\n if(madeBy === MADE_BY_UNIX) {\n this.unixPermissions = (this.externalFileAttributes >> 16) & 0xFFFF;\n // the octal permissions are in (this.unixPermissions & 0x01FF).toString(8);\n }\n\n // fail safe : if the name ends with a / it probably means a folder\n if (!this.dir && this.fileNameStr.slice(-1) === '/') {\n this.dir = true;\n }\n },\n\n /**\n * Parse the ZIP64 extra field and merge the info in the current ZipEntry.\n * @param {DataReader} reader the reader to use.\n */\n parseZIP64ExtraField: function(reader) {\n\n if (!this.extraFields[0x0001]) {\n return;\n }\n\n // should be something, preparing the extra reader\n var extraReader = readerFor(this.extraFields[0x0001].value);\n\n // I really hope that these 64bits integer can fit in 32 bits integer, because js\n // won't let us have more.\n if (this.uncompressedSize === utils.MAX_VALUE_32BITS) {\n this.uncompressedSize = extraReader.readInt(8);\n }\n if (this.compressedSize === utils.MAX_VALUE_32BITS) {\n this.compressedSize = extraReader.readInt(8);\n }\n if (this.localHeaderOffset === utils.MAX_VALUE_32BITS) {\n this.localHeaderOffset = extraReader.readInt(8);\n }\n if (this.diskNumberStart === utils.MAX_VALUE_32BITS) {\n this.diskNumberStart = extraReader.readInt(4);\n }\n },\n /**\n * Read the central part of a zip file and add the info in this object.\n * @param {DataReader} reader the reader to use.\n */\n readExtraFields: function(reader) {\n var end = reader.index + this.extraFieldsLength,\n extraFieldId,\n extraFieldLength,\n extraFieldValue;\n\n if (!this.extraFields) {\n this.extraFields = {};\n }\n\n while (reader.index + 4 < end) {\n extraFieldId = reader.readInt(2);\n extraFieldLength = reader.readInt(2);\n extraFieldValue = reader.readData(extraFieldLength);\n\n this.extraFields[extraFieldId] = {\n id: extraFieldId,\n length: extraFieldLength,\n value: extraFieldValue\n };\n }\n\n reader.setIndex(end);\n },\n /**\n * Apply an UTF8 transformation if needed.\n */\n handleUTF8: function() {\n var decodeParamType = support.uint8array ? \"uint8array\" : \"array\";\n if (this.useUTF8()) {\n this.fileNameStr = utf8.utf8decode(this.fileName);\n this.fileCommentStr = utf8.utf8decode(this.fileComment);\n } else {\n var upath = this.findExtraFieldUnicodePath();\n if (upath !== null) {\n this.fileNameStr = upath;\n } else {\n // ASCII text or unsupported code page\n var fileNameByteArray = utils.transformTo(decodeParamType, this.fileName);\n this.fileNameStr = this.loadOptions.decodeFileName(fileNameByteArray);\n }\n\n var ucomment = this.findExtraFieldUnicodeComment();\n if (ucomment !== null) {\n this.fileCommentStr = ucomment;\n } else {\n // ASCII text or unsupported code page\n var commentByteArray = utils.transformTo(decodeParamType, this.fileComment);\n this.fileCommentStr = this.loadOptions.decodeFileName(commentByteArray);\n }\n }\n },\n\n /**\n * Find the unicode path declared in the extra field, if any.\n * @return {String} the unicode path, null otherwise.\n */\n findExtraFieldUnicodePath: function() {\n var upathField = this.extraFields[0x7075];\n if (upathField) {\n var extraReader = readerFor(upathField.value);\n\n // wrong version\n if (extraReader.readInt(1) !== 1) {\n return null;\n }\n\n // the crc of the filename changed, this field is out of date.\n if (crc32fn(this.fileName) !== extraReader.readInt(4)) {\n return null;\n }\n\n return utf8.utf8decode(extraReader.readData(upathField.length - 5));\n }\n return null;\n },\n\n /**\n * Find the unicode comment declared in the extra field, if any.\n * @return {String} the unicode comment, null otherwise.\n */\n findExtraFieldUnicodeComment: function() {\n var ucommentField = this.extraFields[0x6375];\n if (ucommentField) {\n var extraReader = readerFor(ucommentField.value);\n\n // wrong version\n if (extraReader.readInt(1) !== 1) {\n return null;\n }\n\n // the crc of the comment changed, this field is out of date.\n if (crc32fn(this.fileComment) !== extraReader.readInt(4)) {\n return null;\n }\n\n return utf8.utf8decode(extraReader.readData(ucommentField.length - 5));\n }\n return null;\n }\n};\nmodule.exports = ZipEntry;\n\n},{\"./compressedObject\":2,\"./compressions\":3,\"./crc32\":4,\"./reader/readerFor\":22,\"./support\":30,\"./utf8\":31,\"./utils\":32}],35:[function(require,module,exports){\n'use strict';\n\nvar StreamHelper = require('./stream/StreamHelper');\nvar DataWorker = require('./stream/DataWorker');\nvar utf8 = require('./utf8');\nvar CompressedObject = require('./compressedObject');\nvar GenericWorker = require('./stream/GenericWorker');\n\n/**\n * A simple object representing a file in the zip file.\n * @constructor\n * @param {string} name the name of the file\n * @param {String|ArrayBuffer|Uint8Array|Buffer} data the data\n * @param {Object} options the options of the file\n */\nvar ZipObject = function(name, data, options) {\n this.name = name;\n this.dir = options.dir;\n this.date = options.date;\n this.comment = options.comment;\n this.unixPermissions = options.unixPermissions;\n this.dosPermissions = options.dosPermissions;\n\n this._data = data;\n this._dataBinary = options.binary;\n // keep only the compression\n this.options = {\n compression : options.compression,\n compressionOptions : options.compressionOptions\n };\n};\n\nZipObject.prototype = {\n /**\n * Create an internal stream for the content of this object.\n * @param {String} type the type of each chunk.\n * @return StreamHelper the stream.\n */\n internalStream: function (type) {\n var result = null, outputType = \"string\";\n try {\n if (!type) {\n throw new Error(\"No output type specified.\");\n }\n outputType = type.toLowerCase();\n var askUnicodeString = outputType === \"string\" || outputType === \"text\";\n if (outputType === \"binarystring\" || outputType === \"text\") {\n outputType = \"string\";\n }\n result = this._decompressWorker();\n\n var isUnicodeString = !this._dataBinary;\n\n if (isUnicodeString && !askUnicodeString) {\n result = result.pipe(new utf8.Utf8EncodeWorker());\n }\n if (!isUnicodeString && askUnicodeString) {\n result = result.pipe(new utf8.Utf8DecodeWorker());\n }\n } catch (e) {\n result = new GenericWorker(\"error\");\n result.error(e);\n }\n\n return new StreamHelper(result, outputType, \"\");\n },\n\n /**\n * Prepare the content in the asked type.\n * @param {String} type the type of the result.\n * @param {Function} onUpdate a function to call on each internal update.\n * @return Promise the promise of the result.\n */\n async: function (type, onUpdate) {\n return this.internalStream(type).accumulate(onUpdate);\n },\n\n /**\n * Prepare the content as a nodejs stream.\n * @param {String} type the type of each chunk.\n * @param {Function} onUpdate a function to call on each internal update.\n * @return Stream the stream.\n */\n nodeStream: function (type, onUpdate) {\n return this.internalStream(type || \"nodebuffer\").toNodejsStream(onUpdate);\n },\n\n /**\n * Return a worker for the compressed content.\n * @private\n * @param {Object} compression the compression object to use.\n * @param {Object} compressionOptions the options to use when compressing.\n * @return Worker the worker.\n */\n _compressWorker: function (compression, compressionOptions) {\n if (\n this._data instanceof CompressedObject &&\n this._data.compression.magic === compression.magic\n ) {\n return this._data.getCompressedWorker();\n } else {\n var result = this._decompressWorker();\n if(!this._dataBinary) {\n result = result.pipe(new utf8.Utf8EncodeWorker());\n }\n return CompressedObject.createWorkerFrom(result, compression, compressionOptions);\n }\n },\n /**\n * Return a worker for the decompressed content.\n * @private\n * @return Worker the worker.\n */\n _decompressWorker : function () {\n if (this._data instanceof CompressedObject) {\n return this._data.getContentWorker();\n } else if (this._data instanceof GenericWorker) {\n return this._data;\n } else {\n return new DataWorker(this._data);\n }\n }\n};\n\nvar removedMethods = [\"asText\", \"asBinary\", \"asNodeBuffer\", \"asUint8Array\", \"asArrayBuffer\"];\nvar removedFn = function () {\n throw new Error(\"This method has been removed in JSZip 3.0, please check the upgrade guide.\");\n};\n\nfor(var i = 0; i < removedMethods.length; i++) {\n ZipObject.prototype[removedMethods[i]] = removedFn;\n}\nmodule.exports = ZipObject;\n\n},{\"./compressedObject\":2,\"./stream/DataWorker\":27,\"./stream/GenericWorker\":28,\"./stream/StreamHelper\":29,\"./utf8\":31}],36:[function(require,module,exports){\n(function (global){\n'use strict';\nvar Mutation = global.MutationObserver || global.WebKitMutationObserver;\n\nvar scheduleDrain;\n\n{\n if (Mutation) {\n var called = 0;\n var observer = new Mutation(nextTick);\n var element = global.document.createTextNode('');\n observer.observe(element, {\n characterData: true\n });\n scheduleDrain = function () {\n element.data = (called = ++called % 2);\n };\n } else if (!global.setImmediate && typeof global.MessageChannel !== 'undefined') {\n var channel = new global.MessageChannel();\n channel.port1.onmessage = nextTick;\n scheduleDrain = function () {\n channel.port2.postMessage(0);\n };\n } else if ('document' in global && 'onreadystatechange' in global.document.createElement('script')) {\n scheduleDrain = function () {\n\n // Create a