{"version":3,"file":"image-js.min.js","sources":["../src/image/core/bitMethods.js","../src/image/core/checkProcessable.js","../node_modules/blob-util/dist/blob-util.es.js","../node_modules/utf8/utf8.js","../node_modules/iobuffer/IOBuffer.js","../node_modules/fast-bmp/src/constants.js","../node_modules/fast-bmp/src/encode.js","../node_modules/fast-bmp/src/index.js","../node_modules/fast-png/node_modules/iobuffer/lib-esm/utf8.browser.js","../node_modules/fast-png/node_modules/iobuffer/lib-esm/IOBuffer.js","../node_modules/pako/dist/pako.esm.mjs","../node_modules/fast-png/lib-esm/common.js","../node_modules/fast-png/lib-esm/internalTypes.js","../node_modules/fast-png/lib-esm/PNGDecoder.js","../node_modules/fast-png/lib-esm/PNGEncoder.js","../node_modules/fast-png/lib-esm/index.js","../node_modules/jpeg-js/lib/encoder.js","../node_modules/jpeg-js/lib/decoder.js","../node_modules/jpeg-js/index.js","../src/util/base64.js","../src/browser/environment.js","../src/image/core/mediaTypes.js","../src/image/core/export.js","../node_modules/has-own/index.js","../src/image/core/extend.js","../src/image/model/model.js","../src/image/core/getRGBAData.js","../src/image/core/kindNames.js","../src/image/core/kind.js","../node_modules/fast-jpeg/node_modules/iobuffer/IOBuffer.js","../node_modules/fast-jpeg/node_modules/tiff/src/tags/standard.js","../node_modules/fast-jpeg/node_modules/tiff/src/tags/exif.js","../node_modules/fast-jpeg/node_modules/tiff/src/tags/gps.js","../node_modules/fast-jpeg/node_modules/tiff/src/ifd.js","../node_modules/fast-jpeg/node_modules/tiff/src/tiffIfd.js","../node_modules/fast-jpeg/node_modules/tiff/src/ifdValue.js","../node_modules/fast-jpeg/node_modules/tiff/src/tiffDecoder.js","../node_modules/fast-jpeg/node_modules/tiff/src/decode.js","../node_modules/fast-jpeg/node_modules/tiff/src/index.js","../node_modules/fast-jpeg/src/decode.js","../node_modules/fast-jpeg/src/index.js","../node_modules/file-type/index.js","../node_modules/image-type/index.js","../node_modules/tiff/node_modules/iobuffer/lib-esm/utf8.browser.js","../node_modules/tiff/node_modules/iobuffer/lib-esm/IOBuffer.js","../node_modules/tiff/lib-esm/horizontalDifferencing.js","../node_modules/tiff/lib-esm/tags/exif.js","../node_modules/tiff/lib-esm/tags/gps.js","../node_modules/tiff/lib-esm/tags/standard.js","../node_modules/tiff/lib-esm/ifd.js","../node_modules/tiff/lib-esm/ifdValue.js","../node_modules/tiff/lib-esm/lzw.js","../node_modules/tiff/lib-esm/tiffIfd.js","../node_modules/tiff/lib-esm/zlib.js","../node_modules/tiff/lib-esm/tiffDecoder.js","../node_modules/tiff/lib-esm/index.js","../src/stack/transform/matchAndCrop.js","../src/stack/compute/min.js","../src/stack/compute/max.js","../src/util/histogram.js","../src/stack/compute/median.js","../src/stack/compute/histogram.js","../src/stack/compute/histograms.js","../src/stack/utility/averageImage.js","../src/stack/utility/maxImage.js","../src/stack/utility/minImage.js","../src/stack/extend.js","../src/stack/Stack.js","../src/image/core/load.js","../src/image/core/valueMethods.js","../src/image/internal/getImageParameters.js","../src/image/internal/getOutputImage.js","../src/image/filter/abs.js","../src/image/internal/copyAlphaChannel.js","../src/image/filter/invert.js","../src/image/filter/flipX.js","../src/image/filter/flipY.js","../src/image/filter/blurFilter.js","../node_modules/median-quickselect/lib/median-quickselect.min.js","../src/util/channel.js","../src/image/filter/medianFilter.js","../src/image/filter/gaussianFilter.js","../src/util/kernels.js","../node_modules/ml-fft/src/fftlib.js","../node_modules/ml-fft/src/FFTUtils.js","../node_modules/ml-fft/src/index.js","../node_modules/ml-matrix-convolution/src/index.js","../node_modules/is-finite/index.js","../node_modules/is-integer/index.js","../src/util/kernel.js","../src/image/internal/clamp.js","../node_modules/ml-convolution/src/directConvolution.js","../src/image/operator/convolutionSeparable.js","../node_modules/is-any-array/src/index.js","../node_modules/ml-array-max/lib-es6/index.js","../node_modules/ml-array-min/lib-es6/index.js","../node_modules/ml-array-rescale/lib-es6/index.js","../node_modules/ml-matrix/src/inspect.js","../node_modules/ml-matrix/src/mathOperations.js","../node_modules/ml-matrix/src/util.js","../node_modules/ml-matrix/src/stat.js","../node_modules/ml-matrix/src/matrix.js","../node_modules/ml-matrix/src/views/base.js","../node_modules/ml-matrix/src/views/column.js","../node_modules/ml-matrix/src/views/columnSelection.js","../node_modules/ml-matrix/src/views/flipColumn.js","../node_modules/ml-matrix/src/views/flipRow.js","../node_modules/ml-matrix/src/views/row.js","../node_modules/ml-matrix/src/views/rowSelection.js","../node_modules/ml-matrix/src/views/selection.js","../node_modules/ml-matrix/src/views/sub.js","../node_modules/ml-matrix/src/views/transpose.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix1D.js","../node_modules/ml-matrix/src/wrap/WrapperMatrix2D.js","../node_modules/ml-matrix/src/wrap/wrap.js","../node_modules/ml-matrix/src/dc/lu.js","../node_modules/ml-matrix/src/dc/util.js","../node_modules/ml-matrix/src/dc/qr.js","../node_modules/ml-matrix/src/dc/svd.js","../node_modules/ml-matrix/src/decompositions.js","../node_modules/ml-matrix/src/determinant.js","../node_modules/ml-matrix/src/linearDependencies.js","../node_modules/ml-matrix/src/pseudoInverse.js","../node_modules/ml-matrix/src/covariance.js","../node_modules/ml-matrix/src/correlation.js","../node_modules/ml-matrix/src/dc/evd.js","../node_modules/ml-matrix/src/dc/cholesky.js","../node_modules/ml-matrix/src/dc/nipals.js","../src/image/operator/getSeparatedKernel.js","../src/image/operator/convolution.js","../src/image/filter/gradientFilter.js","../src/image/filter/sobelFilter.js","../src/image/filter/scharrFilter.js","../node_modules/new-array/index.js","../src/image/filter/level.js","../node_modules/is-array-type/is-array-type.js","../src/util/value.js","../src/image/filter/add.js","../src/image/filter/subtract.js","../src/image/filter/subtractImage.js","../src/image/filter/hypotenuse.js","../src/image/filter/multiply.js","../src/image/filter/divide.js","../node_modules/ml-regression-base/src/index.js","../node_modules/ml-distance-euclidean/lib-es6/euclidean.js","../node_modules/ml-kernel-gaussian/gaussian-kernel.js","../node_modules/ml-kernel-polynomial/polynomial-kernel.js","../node_modules/ml-kernel-sigmoid/sigmoid-kernel.js","../node_modules/ml-kernel/src/kernels/anova-kernel.js","../node_modules/ml-kernel/src/kernels/cauchy-kernel.js","../node_modules/ml-kernel/src/kernels/exponential-kernel.js","../node_modules/ml-kernel/src/kernels/histogram-intersection-kernel.js","../node_modules/ml-kernel/src/kernels/laplacian-kernel.js","../node_modules/ml-kernel/src/kernels/multiquadratic-kernel.js","../node_modules/ml-kernel/src/kernels/rational-quadratic-kernel.js","../node_modules/ml-kernel/src/kernel.js","../node_modules/ml-regression/src/regression/kernel-ridge-regression.js","../src/image/filter/background.js","../src/image/morphology/dilate.js","../src/image/morphology/erode.js","../src/image/morphology/open.js","../src/image/morphology/close.js","../src/image/morphology/topHat.js","../src/image/morphology/blackHat.js","../src/image/morphology/morphologicalGradient.js","../src/image/transform/warping.js","../src/image/transform/crop.js","../src/image/transform/cropAlpha.js","../src/util/converter.js","../src/image/internal/checks.js","../src/image/transform/resize/nearestNeighbor.js","../src/image/transform/resize/resize.js","../src/image/transform/hsv.js","../src/image/transform/hsl.js","../src/image/transform/cmyk.js","../src/image/transform/rgba8.js","../src/image/transform/greyAlgorithms.js","../src/image/transform/grey.js","../src/image/transform/mask/huang.js","../src/image/transform/mask/intermodes.js","../src/image/transform/mask/isodata.js","../src/image/transform/mask/li.js","../src/image/transform/mask/maxEntropy.js","../src/image/transform/mask/mean.js","../src/image/transform/mask/minError.js","../src/image/transform/mask/minimum.js","../src/image/transform/mask/moments.js","../src/image/transform/mask/otsu.js","../src/image/transform/mask/percentile.js","../src/image/transform/mask/renyiEntropy.js","../src/image/transform/mask/shanbhag.js","../src/image/transform/mask/triangle.js","../src/image/transform/mask/yen.js","../src/image/transform/mask/thresholdAlgorithms.js","../src/image/utility/getThreshold.js","../src/image/transform/mask/mask.js","../src/image/internal/copy.js","../src/image/transform/pad.js","../src/image/transform/colorDepth.js","../src/image/transform/rotateFree.js","../src/image/transform/rotate.js","../src/image/transform/insert.js","../src/image/utility/setBorder.js","../src/image/utility/split.js","../src/image/utility/getChannel.js","../src/image/utility/combineChannels.js","../src/image/utility/setChannel.js","../src/image/utility/getSimilarity.js","../src/image/utility/getPixelsGrid.js","../src/util/matrix.js","../src/image/utility/getBestMatch.js","../src/image/utility/getRow.js","../src/image/utility/getColumn.js","../src/image/utility/getMatrix.js","../src/image/utility/setMatrix.js","../src/image/utility/getPixelsArray.js","../src/image/utility/getIntersection.js","../src/image/utility/getClosestCommonParent.js","../node_modules/canny-edge-detector/src/index.js","../src/image/operator/cannyEdge.js","../src/image/operator/extract.js","../node_modules/fast-list/fast-list.js","../src/image/operator/floodFill.js","../node_modules/@babel/runtime/helpers/esm/extends.js","../node_modules/@swiftcarrot/color-fns/dist/index.esm.js","../src/util/color.js","../src/image/operator/paintLabels.js","../src/image/operator/paintMasks.js","../src/util/zerosMatrix.js","../src/util/Shape.js","../src/image/operator/paintPoints.js","../src/image/operator/paintPolyline.js","../src/image/operator/paintPolylines.js","../src/image/operator/paintPolygon.js","../src/image/operator/paintPolygons.js","../src/image/compute/histogram.js","../src/image/compute/colorHistogram.js","../src/image/compute/min.js","../src/image/compute/max.js","../src/image/compute/sum.js","../src/image/compute/moment.js","../src/image/compute/localMaxima.js","../src/image/compute/mean.js","../src/image/compute/median.js","../src/image/compute/points.js","../src/image/compute/extendedPoints.js","../src/image/compute/relativePosition.js","../src/image/compute/countAlphaPixels.js","../node_modules/monotone-chain-convex-hull/src/index.js","../src/image/compute/monotoneChainConvexHull.js","../src/util/points.js","../src/image/compute/minimalBoundingRectangle.js","../src/image/extend.js","../node_modules/js-quantities/build/quantities.js","../src/util/deepValue.js","../node_modules/two-product/two-product.js","../node_modules/robust-sum/robust-sum.js","../node_modules/two-sum/two-sum.js","../node_modules/robust-scale/robust-scale.js","../node_modules/robust-subtract/robust-diff.js","../node_modules/robust-orientation/orientation.js","../node_modules/robust-point-in-polygon/robust-pnp.js","../src/image/roi/feretDiameters.js","../src/image/roi/Roi.js","../src/image/roi/RoiLayer.js","../src/image/roi/util/commonBorderLength.js","../src/image/roi/util/mergeRoi.js","../src/image/roi/RoiMap.js","../src/image/roi/creator/fromMask.js","../node_modules/ml-disjoint-set/src/DisjointSet.js","../src/image/roi/creator/fromMaskConnectedComponentLabelingAlgorithm.js","../src/image/roi/creator/fromMaxima.js","../src/image/roi/creator/fromPoints.js","../node_modules/js-priority-queue/priority-queue.js","../src/util/dxdy.js","../src/image/roi/creator/fromWaterShed.js","../src/image/roi/manager.js","../src/image/Image.js","../src/kernel/laplacianOfGaussian.js","../node_modules/web-worker-manager/src/workerTemplate.js","../node_modules/web-worker-manager/src/index.js","../src/browser/worker/process/background.js","../src/browser/worker/extend.js","../src/browser/worker/worker.js","../src/index.js"],"sourcesContent":["// Those methods can only be called on binary images, but we won't lose time to check.\nconst bitMethods = {\n /**\n * Get the bit of a pixel using a pixel index.\n * This method can only be called on binary images.\n * @memberof Image\n * @instance\n * @param {number} pixel - The pixel index which corresponds to `x * image.width + y`\n * @return {number} 0: bit is unset, 1: bit is set\n */\n getBit(pixel) {\n return this.data[getSlot(pixel)] & (1 << getShift(pixel)) ? 1 : 0;\n },\n\n /**\n * Set the bit of a pixel using a pixel index.\n * This method can only be called on binary images.\n * @memberof Image\n * @instance\n * @param {number} pixel - The pixel index which corresponds to `x * image.width + y`\n */\n setBit(pixel) {\n this.data[getSlot(pixel)] |= 1 << getShift(pixel);\n },\n\n /**\n * Clear the bit of a pixel using a pixel index.\n * This method can only be called on binary images.\n * @memberof Image\n * @instance\n * @param {number} pixel - The pixel index which corresponds to `x * image.width + y`\n */\n clearBit(pixel) {\n this.data[getSlot(pixel)] &= ~(1 << getShift(pixel));\n },\n\n /**\n * Toggle (invert) the bit of a pixel using a pixel index.\n * This method can only be called on binary images.\n * @memberof Image\n * @instance\n * @param {number} pixel - The pixel index which corresponds to `x * image.width + y`\n */\n toggleBit(pixel) {\n this.data[getSlot(pixel)] ^= 1 << getShift(pixel);\n },\n\n /**\n * Get the bit of a pixel using coordinates.\n * This method can only be called on binary images.\n * @memberof Image\n * @instance\n * @param {number} x - x coordinate (0 = left)\n * @param {number} y - y coordinate (0 = top)\n * @return {number} 0: bit is unset, 1: bit is set\n */\n getBitXY(x, y) {\n if (x >= this.width || y >= this.height) return 0;\n return this.getBit(y * this.width + x);\n },\n\n /**\n * Set the bit of a pixel using coordinates.\n * This method can only be called on binary images.\n * @memberof Image\n * @instance\n * @param {number} x - x coordinate (0 = left)\n * @param {number} y - y coordinate (0 = top)\n */\n setBitXY(x, y) {\n this.setBit(y * this.width + x);\n },\n\n /**\n * Clear the bit of a pixel using coordinates.\n * @memberof Image\n * @instance\n * @param {number} x - x coordinate (0 = left)\n * @param {number} y - y coordinate (0 = top)\n */\n clearBitXY(x, y) {\n this.clearBit(y * this.width + x);\n },\n\n /**\n * Toggle (invert) the bit of a pixel using coordinates.\n * @memberof Image\n * @instance\n * @param {number} x - x coordinate (0 = left)\n * @param {number} y - y coordinate (0 = top)\n */\n toggleBitXY(x, y) {\n this.toggleBit(y * this.width + x);\n },\n};\n\nfunction getSlot(pixel) {\n return pixel >> 3;\n}\n\nfunction getShift(pixel) {\n return 7 - (pixel & 0b00000111);\n}\n\nexport default function setBitMethods(Image) {\n for (const i in bitMethods) {\n Image.prototype[i] = bitMethods[i];\n }\n}\n","/**\n * This method checks if a process can be applied on the current image\n * @memberof Image\n * @instance\n * @param {string} processName\n * @param {object} [options]\n */\nexport default function checkProcessable(processName, options = {}) {\n let { bitDepth, alpha, colorModel, components, channels } = options;\n if (typeof processName !== 'string' || processName.length === 0) {\n throw new TypeError('processName must be a string');\n }\n if (bitDepth) {\n if (!Array.isArray(bitDepth)) {\n bitDepth = [bitDepth];\n }\n if (!bitDepth.includes(this.bitDepth)) {\n throw new TypeError(\n `The process: ${processName} can only be applied if bit depth is in: ${bitDepth}`,\n );\n }\n }\n if (alpha) {\n if (!Array.isArray(alpha)) {\n alpha = [alpha];\n }\n if (!alpha.includes(this.alpha)) {\n throw new TypeError(\n `The process: ${processName} can only be applied if alpha is in: ${alpha}`,\n );\n }\n }\n if (colorModel) {\n if (!Array.isArray(colorModel)) {\n colorModel = [colorModel];\n }\n if (!colorModel.includes(this.colorModel)) {\n throw new TypeError(\n `The process: ${processName} can only be applied if color model is in: ${colorModel}`,\n );\n }\n }\n if (components) {\n if (!Array.isArray(components)) {\n components = [components];\n }\n if (!components.includes(this.components)) {\n let errorMessage = `The process: ${processName} can only be applied if the number of components is in: ${components}`;\n if (components.length === 1 && components[0] === 1) {\n throw new TypeError(\n `${errorMessage}.\\rYou should transform your image using \"image.grey()\" before applying the algorithm.`,\n );\n } else {\n throw new TypeError(errorMessage);\n }\n }\n }\n if (channels) {\n if (!Array.isArray(channels)) {\n channels = [channels];\n }\n if (!channels.includes(this.channels)) {\n throw new TypeError(\n `The process: ${processName} can only be applied if the number of channels is in: ${channels}`,\n );\n }\n }\n}\n","// TODO: including these in blob-util.ts causes typedoc to generate docs for them,\n// even with --excludePrivate ¯\\_(ツ)_/¯\n/** @private */\nfunction loadImage(src, crossOrigin) {\n return new Promise(function (resolve, reject) {\n var img = new Image();\n if (crossOrigin) {\n img.crossOrigin = crossOrigin;\n }\n img.onload = function () {\n resolve(img);\n };\n img.onerror = reject;\n img.src = src;\n });\n}\n/** @private */\nfunction imgToCanvas(img) {\n var canvas = document.createElement('canvas');\n canvas.width = img.width;\n canvas.height = img.height;\n // copy the image contents to the canvas\n var context = canvas.getContext('2d');\n context.drawImage(img, 0, 0, img.width, img.height, 0, 0, img.width, img.height);\n return canvas;\n}\n\n/* global Promise, Image, Blob, FileReader, atob, btoa,\n BlobBuilder, MSBlobBuilder, MozBlobBuilder, WebKitBlobBuilder, webkitURL */\n/**\n * Shim for\n * [`new Blob()`](https://developer.mozilla.org/en-US/docs/Web/API/Blob.Blob)\n * to support\n * [older browsers that use the deprecated `BlobBuilder` API](http://caniuse.com/blob).\n *\n * Example:\n *\n * ```js\n * var myBlob = blobUtil.createBlob(['hello world'], {type: 'text/plain'});\n * ```\n *\n * @param parts - content of the Blob\n * @param properties - usually `{type: myContentType}`,\n * you can also pass a string for the content type\n * @returns Blob\n */\nfunction createBlob(parts, properties) {\n parts = parts || [];\n properties = properties || {};\n if (typeof properties === 'string') {\n properties = { type: properties }; // infer content type\n }\n try {\n return new Blob(parts, properties);\n }\n catch (e) {\n if (e.name !== 'TypeError') {\n throw e;\n }\n var Builder = typeof BlobBuilder !== 'undefined'\n ? BlobBuilder : typeof MSBlobBuilder !== 'undefined'\n ? MSBlobBuilder : typeof MozBlobBuilder !== 'undefined'\n ? MozBlobBuilder : WebKitBlobBuilder;\n var builder = new Builder();\n for (var i = 0; i < parts.length; i += 1) {\n builder.append(parts[i]);\n }\n return builder.getBlob(properties.type);\n }\n}\n/**\n * Shim for\n * [`URL.createObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL.createObjectURL)\n * to support browsers that only have the prefixed\n * `webkitURL` (e.g. Android <4.4).\n *\n * Example:\n *\n * ```js\n * var myUrl = blobUtil.createObjectURL(blob);\n * ```\n *\n * @param blob\n * @returns url\n */\nfunction createObjectURL(blob) {\n return (typeof URL !== 'undefined' ? URL : webkitURL).createObjectURL(blob);\n}\n/**\n * Shim for\n * [`URL.revokeObjectURL()`](https://developer.mozilla.org/en-US/docs/Web/API/URL.revokeObjectURL)\n * to support browsers that only have the prefixed\n * `webkitURL` (e.g. Android <4.4).\n *\n * Example:\n *\n * ```js\n * blobUtil.revokeObjectURL(myUrl);\n * ```\n *\n * @param url\n */\nfunction revokeObjectURL(url) {\n return (typeof URL !== 'undefined' ? URL : webkitURL).revokeObjectURL(url);\n}\n/**\n * Convert a `Blob` to a binary string.\n *\n * Example:\n *\n * ```js\n * blobUtil.blobToBinaryString(blob).then(function (binaryString) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * @param blob\n * @returns Promise that resolves with the binary string\n */\nfunction blobToBinaryString(blob) {\n return new Promise(function (resolve, reject) {\n var reader = new FileReader();\n var hasBinaryString = typeof reader.readAsBinaryString === 'function';\n reader.onloadend = function () {\n var result = reader.result || '';\n if (hasBinaryString) {\n return resolve(result);\n }\n resolve(arrayBufferToBinaryString(result));\n };\n reader.onerror = reject;\n if (hasBinaryString) {\n reader.readAsBinaryString(blob);\n }\n else {\n reader.readAsArrayBuffer(blob);\n }\n });\n}\n/**\n * Convert a base64-encoded string to a `Blob`.\n *\n * Example:\n *\n * ```js\n * var blob = blobUtil.base64StringToBlob(base64String);\n * ```\n * @param base64 - base64-encoded string\n * @param type - the content type (optional)\n * @returns Blob\n */\nfunction base64StringToBlob(base64, type) {\n var parts = [binaryStringToArrayBuffer(atob(base64))];\n return type ? createBlob(parts, { type: type }) : createBlob(parts);\n}\n/**\n * Convert a binary string to a `Blob`.\n *\n * Example:\n *\n * ```js\n * var blob = blobUtil.binaryStringToBlob(binaryString);\n * ```\n *\n * @param binary - binary string\n * @param type - the content type (optional)\n * @returns Blob\n */\nfunction binaryStringToBlob(binary, type) {\n return base64StringToBlob(btoa(binary), type);\n}\n/**\n * Convert a `Blob` to a binary string.\n *\n * Example:\n *\n * ```js\n * blobUtil.blobToBase64String(blob).then(function (base64String) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * @param blob\n * @returns Promise that resolves with the binary string\n */\nfunction blobToBase64String(blob) {\n return blobToBinaryString(blob).then(btoa);\n}\n/**\n * Convert a data URL string\n * (e.g. `'data:image/png;base64,iVBORw0KG...'`)\n * to a `Blob`.\n *\n * Example:\n *\n * ```js\n * var blob = blobUtil.dataURLToBlob(dataURL);\n * ```\n *\n * @param dataURL - dataURL-encoded string\n * @returns Blob\n */\nfunction dataURLToBlob(dataURL) {\n var type = dataURL.match(/data:([^;]+)/)[1];\n var base64 = dataURL.replace(/^[^,]+,/, '');\n var buff = binaryStringToArrayBuffer(atob(base64));\n return createBlob([buff], { type: type });\n}\n/**\n * Convert a `Blob` to a data URL string\n * (e.g. `'data:image/png;base64,iVBORw0KG...'`).\n *\n * Example:\n *\n * ```js\n * var dataURL = blobUtil.blobToDataURL(blob);\n * ```\n *\n * @param blob\n * @returns Promise that resolves with the data URL string\n */\nfunction blobToDataURL(blob) {\n return blobToBase64String(blob).then(function (base64String) {\n return 'data:' + blob.type + ';base64,' + base64String;\n });\n}\n/**\n * Convert an image's `src` URL to a data URL by loading the image and painting\n * it to a `canvas`.\n *\n * Note: this will coerce the image to the desired content type, and it\n * will only paint the first frame of an animated GIF.\n *\n * Examples:\n *\n * ```js\n * blobUtil.imgSrcToDataURL('http://mysite.com/img.png').then(function (dataURL) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * ```js\n * blobUtil.imgSrcToDataURL('http://some-other-site.com/img.jpg', 'image/jpeg',\n * 'Anonymous', 1.0).then(function (dataURL) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * @param src - image src\n * @param type - the content type (optional, defaults to 'image/png')\n * @param crossOrigin - for CORS-enabled images, set this to\n * 'Anonymous' to avoid \"tainted canvas\" errors\n * @param quality - a number between 0 and 1 indicating image quality\n * if the requested type is 'image/jpeg' or 'image/webp'\n * @returns Promise that resolves with the data URL string\n */\nfunction imgSrcToDataURL(src, type, crossOrigin, quality) {\n type = type || 'image/png';\n return loadImage(src, crossOrigin).then(imgToCanvas).then(function (canvas) {\n return canvas.toDataURL(type, quality);\n });\n}\n/**\n * Convert a `canvas` to a `Blob`.\n *\n * Examples:\n *\n * ```js\n * blobUtil.canvasToBlob(canvas).then(function (blob) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * Most browsers support converting a canvas to both `'image/png'` and `'image/jpeg'`. You may\n * also want to try `'image/webp'`, which will work in some browsers like Chrome (and in other browsers, will just fall back to `'image/png'`):\n *\n * ```js\n * blobUtil.canvasToBlob(canvas, 'image/webp').then(function (blob) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * @param canvas - HTMLCanvasElement\n * @param type - the content type (optional, defaults to 'image/png')\n * @param quality - a number between 0 and 1 indicating image quality\n * if the requested type is 'image/jpeg' or 'image/webp'\n * @returns Promise that resolves with the `Blob`\n */\nfunction canvasToBlob(canvas, type, quality) {\n if (typeof canvas.toBlob === 'function') {\n return new Promise(function (resolve) {\n canvas.toBlob(resolve, type, quality);\n });\n }\n return Promise.resolve(dataURLToBlob(canvas.toDataURL(type, quality)));\n}\n/**\n * Convert an image's `src` URL to a `Blob` by loading the image and painting\n * it to a `canvas`.\n *\n * Note: this will coerce the image to the desired content type, and it\n * will only paint the first frame of an animated GIF.\n *\n * Examples:\n *\n * ```js\n * blobUtil.imgSrcToBlob('http://mysite.com/img.png').then(function (blob) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * ```js\n * blobUtil.imgSrcToBlob('http://some-other-site.com/img.jpg', 'image/jpeg',\n * 'Anonymous', 1.0).then(function (blob) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * @param src - image src\n * @param type - the content type (optional, defaults to 'image/png')\n * @param crossOrigin - for CORS-enabled images, set this to\n * 'Anonymous' to avoid \"tainted canvas\" errors\n * @param quality - a number between 0 and 1 indicating image quality\n * if the requested type is 'image/jpeg' or 'image/webp'\n * @returns Promise that resolves with the `Blob`\n */\nfunction imgSrcToBlob(src, type, crossOrigin, quality) {\n type = type || 'image/png';\n return loadImage(src, crossOrigin).then(imgToCanvas).then(function (canvas) {\n return canvasToBlob(canvas, type, quality);\n });\n}\n/**\n * Convert an `ArrayBuffer` to a `Blob`.\n *\n * Example:\n *\n * ```js\n * var blob = blobUtil.arrayBufferToBlob(arrayBuff, 'audio/mpeg');\n * ```\n *\n * @param buffer\n * @param type - the content type (optional)\n * @returns Blob\n */\nfunction arrayBufferToBlob(buffer, type) {\n return createBlob([buffer], type);\n}\n/**\n * Convert a `Blob` to an `ArrayBuffer`.\n *\n * Example:\n *\n * ```js\n * blobUtil.blobToArrayBuffer(blob).then(function (arrayBuff) {\n * // success\n * }).catch(function (err) {\n * // error\n * });\n * ```\n *\n * @param blob\n * @returns Promise that resolves with the `ArrayBuffer`\n */\nfunction blobToArrayBuffer(blob) {\n return new Promise(function (resolve, reject) {\n var reader = new FileReader();\n reader.onloadend = function () {\n var result = reader.result || new ArrayBuffer(0);\n resolve(result);\n };\n reader.onerror = reject;\n reader.readAsArrayBuffer(blob);\n });\n}\n/**\n * Convert an `ArrayBuffer` to a binary string.\n *\n * Example:\n *\n * ```js\n * var myString = blobUtil.arrayBufferToBinaryString(arrayBuff)\n * ```\n *\n * @param buffer - array buffer\n * @returns binary string\n */\nfunction arrayBufferToBinaryString(buffer) {\n var binary = '';\n var bytes = new Uint8Array(buffer);\n var length = bytes.byteLength;\n var i = -1;\n while (++i < length) {\n binary += String.fromCharCode(bytes[i]);\n }\n return binary;\n}\n/**\n * Convert a binary string to an `ArrayBuffer`.\n *\n * ```js\n * var myBuffer = blobUtil.binaryStringToArrayBuffer(binaryString)\n * ```\n *\n * @param binary - binary string\n * @returns array buffer\n */\nfunction binaryStringToArrayBuffer(binary) {\n var length = binary.length;\n var buf = new ArrayBuffer(length);\n var arr = new Uint8Array(buf);\n var i = -1;\n while (++i < length) {\n arr[i] = binary.charCodeAt(i);\n }\n return buf;\n}\n\nexport { createBlob, createObjectURL, revokeObjectURL, blobToBinaryString, base64StringToBlob, binaryStringToBlob, blobToBase64String, dataURLToBlob, blobToDataURL, imgSrcToDataURL, canvasToBlob, imgSrcToBlob, arrayBufferToBlob, blobToArrayBuffer, arrayBufferToBinaryString, binaryStringToArrayBuffer };\n","/*! https://mths.be/utf8js v2.1.2 by @mathias */\n;(function(root) {\n\n\t// Detect free variables `exports`\n\tvar freeExports = typeof exports == 'object' && exports;\n\n\t// Detect free variable `module`\n\tvar freeModule = typeof module == 'object' && module &&\n\t\tmodule.exports == freeExports && module;\n\n\t// Detect free variable `global`, from Node.js or Browserified code,\n\t// and use it as `root`\n\tvar freeGlobal = typeof global == 'object' && global;\n\tif (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {\n\t\troot = freeGlobal;\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar stringFromCharCode = String.fromCharCode;\n\n\t// Taken from https://mths.be/punycode\n\tfunction ucs2decode(string) {\n\t\tvar output = [];\n\t\tvar counter = 0;\n\t\tvar length = string.length;\n\t\tvar value;\n\t\tvar extra;\n\t\twhile (counter < length) {\n\t\t\tvalue = string.charCodeAt(counter++);\n\t\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t\t// high surrogate, and there is a next character\n\t\t\t\textra = string.charCodeAt(counter++);\n\t\t\t\tif ((extra & 0xFC00) == 0xDC00) { // low surrogate\n\t\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t\t} else {\n\t\t\t\t\t// unmatched surrogate; only append this code unit, in case the next\n\t\t\t\t\t// code unit is the high surrogate of a surrogate pair\n\t\t\t\t\toutput.push(value);\n\t\t\t\t\tcounter--;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\toutput.push(value);\n\t\t\t}\n\t\t}\n\t\treturn output;\n\t}\n\n\t// Taken from https://mths.be/punycode\n\tfunction ucs2encode(array) {\n\t\tvar length = array.length;\n\t\tvar index = -1;\n\t\tvar value;\n\t\tvar output = '';\n\t\twhile (++index < length) {\n\t\t\tvalue = array[index];\n\t\t\tif (value > 0xFFFF) {\n\t\t\t\tvalue -= 0x10000;\n\t\t\t\toutput += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);\n\t\t\t\tvalue = 0xDC00 | value & 0x3FF;\n\t\t\t}\n\t\t\toutput += stringFromCharCode(value);\n\t\t}\n\t\treturn output;\n\t}\n\n\tfunction checkScalarValue(codePoint) {\n\t\tif (codePoint >= 0xD800 && codePoint <= 0xDFFF) {\n\t\t\tthrow Error(\n\t\t\t\t'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +\n\t\t\t\t' is not a scalar value'\n\t\t\t);\n\t\t}\n\t}\n\t/*--------------------------------------------------------------------------*/\n\n\tfunction createByte(codePoint, shift) {\n\t\treturn stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);\n\t}\n\n\tfunction encodeCodePoint(codePoint) {\n\t\tif ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence\n\t\t\treturn stringFromCharCode(codePoint);\n\t\t}\n\t\tvar symbol = '';\n\t\tif ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);\n\t\t}\n\t\telse if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence\n\t\t\tcheckScalarValue(codePoint);\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);\n\t\t\tsymbol += createByte(codePoint, 6);\n\t\t}\n\t\telse if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence\n\t\t\tsymbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);\n\t\t\tsymbol += createByte(codePoint, 12);\n\t\t\tsymbol += createByte(codePoint, 6);\n\t\t}\n\t\tsymbol += stringFromCharCode((codePoint & 0x3F) | 0x80);\n\t\treturn symbol;\n\t}\n\n\tfunction utf8encode(string) {\n\t\tvar codePoints = ucs2decode(string);\n\t\tvar length = codePoints.length;\n\t\tvar index = -1;\n\t\tvar codePoint;\n\t\tvar byteString = '';\n\t\twhile (++index < length) {\n\t\t\tcodePoint = codePoints[index];\n\t\t\tbyteString += encodeCodePoint(codePoint);\n\t\t}\n\t\treturn byteString;\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\tfunction readContinuationByte() {\n\t\tif (byteIndex >= byteCount) {\n\t\t\tthrow Error('Invalid byte index');\n\t\t}\n\n\t\tvar continuationByte = byteArray[byteIndex] & 0xFF;\n\t\tbyteIndex++;\n\n\t\tif ((continuationByte & 0xC0) == 0x80) {\n\t\t\treturn continuationByte & 0x3F;\n\t\t}\n\n\t\t// If we end up here, it’s not a continuation byte\n\t\tthrow Error('Invalid continuation byte');\n\t}\n\n\tfunction decodeSymbol() {\n\t\tvar byte1;\n\t\tvar byte2;\n\t\tvar byte3;\n\t\tvar byte4;\n\t\tvar codePoint;\n\n\t\tif (byteIndex > byteCount) {\n\t\t\tthrow Error('Invalid byte index');\n\t\t}\n\n\t\tif (byteIndex == byteCount) {\n\t\t\treturn false;\n\t\t}\n\n\t\t// Read first byte\n\t\tbyte1 = byteArray[byteIndex] & 0xFF;\n\t\tbyteIndex++;\n\n\t\t// 1-byte sequence (no continuation bytes)\n\t\tif ((byte1 & 0x80) == 0) {\n\t\t\treturn byte1;\n\t\t}\n\n\t\t// 2-byte sequence\n\t\tif ((byte1 & 0xE0) == 0xC0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x1F) << 6) | byte2;\n\t\t\tif (codePoint >= 0x80) {\n\t\t\t\treturn codePoint;\n\t\t\t} else {\n\t\t\t\tthrow Error('Invalid continuation byte');\n\t\t\t}\n\t\t}\n\n\t\t// 3-byte sequence (may include unpaired surrogates)\n\t\tif ((byte1 & 0xF0) == 0xE0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tbyte3 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;\n\t\t\tif (codePoint >= 0x0800) {\n\t\t\t\tcheckScalarValue(codePoint);\n\t\t\t\treturn codePoint;\n\t\t\t} else {\n\t\t\t\tthrow Error('Invalid continuation byte');\n\t\t\t}\n\t\t}\n\n\t\t// 4-byte sequence\n\t\tif ((byte1 & 0xF8) == 0xF0) {\n\t\t\tbyte2 = readContinuationByte();\n\t\t\tbyte3 = readContinuationByte();\n\t\t\tbyte4 = readContinuationByte();\n\t\t\tcodePoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0C) |\n\t\t\t\t(byte3 << 0x06) | byte4;\n\t\t\tif (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {\n\t\t\t\treturn codePoint;\n\t\t\t}\n\t\t}\n\n\t\tthrow Error('Invalid UTF-8 detected');\n\t}\n\n\tvar byteArray;\n\tvar byteCount;\n\tvar byteIndex;\n\tfunction utf8decode(byteString) {\n\t\tbyteArray = ucs2decode(byteString);\n\t\tbyteCount = byteArray.length;\n\t\tbyteIndex = 0;\n\t\tvar codePoints = [];\n\t\tvar tmp;\n\t\twhile ((tmp = decodeSymbol()) !== false) {\n\t\t\tcodePoints.push(tmp);\n\t\t}\n\t\treturn ucs2encode(codePoints);\n\t}\n\n\t/*--------------------------------------------------------------------------*/\n\n\tvar utf8 = {\n\t\t'version': '2.1.2',\n\t\t'encode': utf8encode,\n\t\t'decode': utf8decode\n\t};\n\n\t// Some AMD build optimizers, like r.js, check for specific condition patterns\n\t// like the following:\n\tif (\n\t\ttypeof define == 'function' &&\n\t\ttypeof define.amd == 'object' &&\n\t\tdefine.amd\n\t) {\n\t\tdefine(function() {\n\t\t\treturn utf8;\n\t\t});\n\t}\telse if (freeExports && !freeExports.nodeType) {\n\t\tif (freeModule) { // in Node.js or RingoJS v0.8.0+\n\t\t\tfreeModule.exports = utf8;\n\t\t} else { // in Narwhal or RingoJS v0.7.0-\n\t\t\tvar object = {};\n\t\t\tvar hasOwnProperty = object.hasOwnProperty;\n\t\t\tfor (var key in utf8) {\n\t\t\t\thasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);\n\t\t\t}\n\t\t}\n\t} else { // in Rhino or a web browser\n\t\troot.utf8 = utf8;\n\t}\n\n}(this));\n","'use strict';\n\nconst utf8 = require('utf8');\n\nconst defaultByteLength = 1024 * 8;\nconst charArray = [];\n\n/**\n * IOBuffer\n * @constructor\n * @param {undefined|number|ArrayBuffer|TypedArray|IOBuffer|Buffer} data - The data to construct the IOBuffer with.\n *\n * If it's a number, it will initialize the buffer with the number as the buffer's length
\n * If it's undefined, it will initialize the buffer with a default length of 8 Kb
\n * If its an ArrayBuffer, a TypedArray, an IOBuffer instance,\n * or a Node.js Buffer, it will create a view over the underlying ArrayBuffer.\n * @param {object} [options]\n * @param {number} [options.offset=0] - Ignore the first n bytes of the ArrayBuffer\n * @property {ArrayBuffer} buffer - Reference to the internal ArrayBuffer object\n * @property {number} length - Byte length of the internal ArrayBuffer\n * @property {number} offset - The current offset of the buffer's pointer\n * @property {number} byteLength - Byte length of the internal ArrayBuffer\n * @property {number} byteOffset - Byte offset of the internal ArrayBuffer\n */\nclass IOBuffer {\n constructor(data, options) {\n options = options || {};\n var dataIsGiven = false;\n if (data === undefined) {\n data = defaultByteLength;\n }\n if (typeof data === 'number') {\n data = new ArrayBuffer(data);\n } else {\n dataIsGiven = true;\n this._lastWrittenByte = data.byteLength;\n }\n\n const offset = options.offset ? options.offset >>> 0 : 0;\n let byteLength = data.byteLength - offset;\n let dvOffset = offset;\n if (data.buffer) {\n if (data.byteLength !== data.buffer.byteLength) {\n dvOffset = data.byteOffset + offset;\n }\n data = data.buffer;\n }\n if (dataIsGiven) {\n this._lastWrittenByte = byteLength;\n } else {\n this._lastWrittenByte = 0;\n }\n this.buffer = data;\n this.length = byteLength;\n this.byteLength = byteLength;\n this.byteOffset = dvOffset;\n this.offset = 0;\n this.littleEndian = true;\n this._data = new DataView(this.buffer, dvOffset, byteLength);\n this._mark = 0;\n this._marks = [];\n }\n\n /**\n * Checks if the memory allocated to the buffer is sufficient to store more bytes after the offset\n * @param {number} [byteLength=1] The needed memory in bytes\n * @return {boolean} Returns true if there is sufficient space and false otherwise\n */\n available(byteLength) {\n if (byteLength === undefined) byteLength = 1;\n return (this.offset + byteLength) <= this.length;\n }\n\n /**\n * Check if little-endian mode is used for reading and writing multi-byte values\n * @return {boolean} Returns true if little-endian mode is used, false otherwise\n */\n isLittleEndian() {\n return this.littleEndian;\n }\n\n /**\n * Set little-endian mode for reading and writing multi-byte values\n * @return {IOBuffer}\n */\n setLittleEndian() {\n this.littleEndian = true;\n return this;\n }\n\n /**\n * Check if big-endian mode is used for reading and writing multi-byte values\n * @return {boolean} Returns true if big-endian mode is used, false otherwise\n */\n isBigEndian() {\n return !this.littleEndian;\n }\n\n /**\n * Switches to big-endian mode for reading and writing multi-byte values\n * @return {IOBuffer}\n */\n setBigEndian() {\n this.littleEndian = false;\n return this;\n }\n\n /**\n * Move the pointer n bytes forward\n * @param {number} n\n * @return {IOBuffer}\n */\n skip(n) {\n if (n === undefined) n = 1;\n this.offset += n;\n return this;\n }\n\n /**\n * Move the pointer to the given offset\n * @param {number} offset\n * @return {IOBuffer}\n */\n seek(offset) {\n this.offset = offset;\n return this;\n }\n\n /**\n * Store the current pointer offset.\n * @see {@link IOBuffer#reset}\n * @return {IOBuffer}\n */\n mark() {\n this._mark = this.offset;\n return this;\n }\n\n /**\n * Move the pointer back to the last pointer offset set by mark\n * @see {@link IOBuffer#mark}\n * @return {IOBuffer}\n */\n reset() {\n this.offset = this._mark;\n return this;\n }\n\n /**\n * Push the current pointer offset to the mark stack\n * @see {@link IOBuffer#popMark}\n * @return {IOBuffer}\n */\n pushMark() {\n this._marks.push(this.offset);\n return this;\n }\n\n /**\n * Pop the last pointer offset from the mark stack, and set the current pointer offset to the popped value\n * @see {@link IOBuffer#pushMark}\n * @return {IOBuffer}\n */\n popMark() {\n const offset = this._marks.pop();\n if (offset === undefined) throw new Error('Mark stack empty');\n this.seek(offset);\n return this;\n }\n\n /**\n * Move the pointer offset back to 0\n * @return {IOBuffer}\n */\n rewind() {\n this.offset = 0;\n return this;\n }\n\n /**\n * Make sure the buffer has sufficient memory to write a given byteLength at the current pointer offset\n * If the buffer's memory is insufficient, this method will create a new buffer (a copy) with a length\n * that is twice (byteLength + current offset)\n * @param {number} [byteLength = 1]\n * @return {IOBuffer}\n */\n ensureAvailable(byteLength) {\n if (byteLength === undefined) byteLength = 1;\n if (!this.available(byteLength)) {\n const lengthNeeded = this.offset + byteLength;\n const newLength = lengthNeeded * 2;\n const newArray = new Uint8Array(newLength);\n newArray.set(new Uint8Array(this.buffer));\n this.buffer = newArray.buffer;\n this.length = this.byteLength = newLength;\n this._data = new DataView(this.buffer);\n }\n return this;\n }\n\n /**\n * Read a byte and return false if the byte's value is 0, or true otherwise\n * Moves pointer forward\n * @return {boolean}\n */\n readBoolean() {\n return this.readUint8() !== 0;\n }\n\n /**\n * Read a signed 8-bit integer and move pointer forward\n * @return {number}\n */\n readInt8() {\n return this._data.getInt8(this.offset++);\n }\n\n /**\n * Read an unsigned 8-bit integer and move pointer forward\n * @return {number}\n */\n readUint8() {\n return this._data.getUint8(this.offset++);\n }\n\n /**\n * Alias for {@link IOBuffer#readUint8}\n * @return {number}\n */\n readByte() {\n return this.readUint8();\n }\n\n /**\n * Read n bytes and move pointer forward.\n * @param {number} n\n * @return {Uint8Array}\n */\n readBytes(n) {\n if (n === undefined) n = 1;\n var bytes = new Uint8Array(n);\n for (var i = 0; i < n; i++) {\n bytes[i] = this.readByte();\n }\n return bytes;\n }\n\n /**\n * Read a 16-bit signed integer and move pointer forward\n * @return {number}\n */\n readInt16() {\n var value = this._data.getInt16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n\n /**\n * Read a 16-bit unsigned integer and move pointer forward\n * @return {number}\n */\n readUint16() {\n var value = this._data.getUint16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n\n /**\n * Read a 32-bit signed integer and move pointer forward\n * @return {number}\n */\n readInt32() {\n var value = this._data.getInt32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n\n /**\n * Read a 32-bit unsigned integer and move pointer forward\n * @return {number}\n */\n readUint32() {\n var value = this._data.getUint32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n\n /**\n * Read a 32-bit floating number and move pointer forward\n * @return {number}\n */\n readFloat32() {\n var value = this._data.getFloat32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n\n /**\n * Read a 64-bit floating number and move pointer forward\n * @return {number}\n */\n readFloat64() {\n var value = this._data.getFloat64(this.offset, this.littleEndian);\n this.offset += 8;\n return value;\n }\n\n /**\n * Read 1-byte ascii character and move pointer forward\n * @return {string}\n */\n readChar() {\n return String.fromCharCode(this.readInt8());\n }\n\n /**\n * Read n 1-byte ascii characters and move pointer forward\n * @param {number} n\n * @return {string}\n */\n readChars(n) {\n if (n === undefined) n = 1;\n charArray.length = n;\n for (var i = 0; i < n; i++) {\n charArray[i] = this.readChar();\n }\n return charArray.join('');\n }\n\n /**\n * Read the next n bytes, return a UTF-8 decoded string and move pointer forward\n * @param {number} n\n * @return {string}\n */\n readUtf8(n) {\n if (n === undefined) n = 1;\n const bString = this.readChars(n);\n return utf8.decode(bString);\n }\n\n /**\n * Write 0xff if the passed value is truthy, 0x00 otherwise\n * @param {any} value\n * @return {IOBuffer}\n */\n writeBoolean(value) {\n this.writeUint8(value ? 0xff : 0x00);\n return this;\n }\n\n /**\n * Write value as an 8-bit signed integer\n * @param {number} value\n * @return {IOBuffer}\n */\n writeInt8(value) {\n this.ensureAvailable(1);\n this._data.setInt8(this.offset++, value);\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * Write value as a 8-bit unsigned integer\n * @param {number} value\n * @return {IOBuffer}\n */\n writeUint8(value) {\n this.ensureAvailable(1);\n this._data.setUint8(this.offset++, value);\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * An alias for {@link IOBuffer#writeUint8}\n * @param {number} value\n * @return {IOBuffer}\n */\n writeByte(value) {\n return this.writeUint8(value);\n }\n\n /**\n * Write bytes\n * @param {Array|Uint8Array} bytes\n * @return {IOBuffer}\n */\n writeBytes(bytes) {\n this.ensureAvailable(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n this._data.setUint8(this.offset++, bytes[i]);\n }\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * Write value as an 16-bit signed integer\n * @param {number} value\n * @return {IOBuffer}\n */\n writeInt16(value) {\n this.ensureAvailable(2);\n this._data.setInt16(this.offset, value, this.littleEndian);\n this.offset += 2;\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * Write value as a 16-bit unsigned integer\n * @param {number} value\n * @return {IOBuffer}\n */\n writeUint16(value) {\n this.ensureAvailable(2);\n this._data.setUint16(this.offset, value, this.littleEndian);\n this.offset += 2;\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * Write a 32-bit signed integer at the current pointer offset\n * @param {number} value\n * @return {IOBuffer}\n */\n writeInt32(value) {\n this.ensureAvailable(4);\n this._data.setInt32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * Write a 32-bit unsigned integer at the current pointer offset\n * @param {number} value - The value to set\n * @return {IOBuffer}\n */\n writeUint32(value) {\n this.ensureAvailable(4);\n this._data.setUint32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * Write a 32-bit floating number at the current pointer offset\n * @param {number} value - The value to set\n * @return {IOBuffer}\n */\n writeFloat32(value) {\n this.ensureAvailable(4);\n this._data.setFloat32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * Write a 64-bit floating number at the current pointer offset\n * @param {number} value\n * @return {IOBuffer}\n */\n writeFloat64(value) {\n this.ensureAvailable(8);\n this._data.setFloat64(this.offset, value, this.littleEndian);\n this.offset += 8;\n this._updateLastWrittenByte();\n return this;\n }\n\n /**\n * Write the charCode of the passed string's first character to the current pointer offset\n * @param {string} str - The character to set\n * @return {IOBuffer}\n */\n writeChar(str) {\n return this.writeUint8(str.charCodeAt(0));\n }\n\n /**\n * Write the charCodes of the passed string's characters to the current pointer offset\n * @param {string} str\n * @return {IOBuffer}\n */\n writeChars(str) {\n for (var i = 0; i < str.length; i++) {\n this.writeUint8(str.charCodeAt(i));\n }\n return this;\n }\n\n /**\n * UTF-8 encode and write the passed string to the current pointer offset\n * @param {string} str\n * @return {IOBuffer}\n */\n writeUtf8(str) {\n const bString = utf8.encode(str);\n return this.writeChars(bString);\n }\n\n /**\n * Export a Uint8Array view of the internal buffer.\n * The view starts at the byte offset and its length\n * is calculated to stop at the last written byte or the original length.\n * @return {Uint8Array}\n */\n toArray() {\n return new Uint8Array(this.buffer, this.byteOffset, this._lastWrittenByte);\n }\n\n /**\n * Same as {@link IOBuffer#toArray} but returns a Buffer if possible. Otherwise returns a Uint8Array.\n * @return {Buffer|Uint8Array}\n */\n getBuffer() {\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(this.toArray());\n } else {\n return this.toArray();\n }\n }\n\n /**\n * Update the last written byte offset\n * @private\n */\n _updateLastWrittenByte() {\n if (this.offset > this._lastWrittenByte) {\n this._lastWrittenByte = this.offset;\n }\n }\n}\n\nmodule.exports = IOBuffer;\n","'use strict';\n\nmodule.exports = {\n BITMAPV5HEADER: {\n LogicalColorSpace: { // https://msdn.microsoft.com/en-us/library/cc250396.aspx\n LCS_CALIBRATED_RGB: 0x00000000,\n LCS_sRGB: 0x73524742, // eslint-disable-line camelcase\n LCS_WINDOWS_COLOR_SPACE: 0x57696E20\n },\n Compression: { // https://msdn.microsoft.com/en-us/library/cc250415.aspx\n BI_RGB: 0x0000, // No compression\n BI_RLE8: 0x0001,\n BI_RLE4: 0x0002,\n BI_BITFIELDS: 0x0003,\n BI_JPEG: 0x0004,\n BI_PNG: 0x0005,\n BI_CMYK: 0x000B,\n BI_CMYKRLE8: 0x000C,\n BI_CMYKRLE4: 0x000D\n },\n GamutMappingIntent: { // https://msdn.microsoft.com/en-us/library/cc250392.aspx\n LCS_GM_ABS_COLORIMETRIC: 0x00000008,\n LCS_GM_BUSINESS: 0x00000001,\n LCS_GM_GRAPHICS: 0x00000002,\n LCS_GM_IMAGES: 0x00000004\n }\n }\n};\n","'use strict';\n\nconst IOBuffer = require('iobuffer');\nconst constants = require('./constants');\nconst tableLeft = [];\nfor (var i = 0; i <= 8; i++) {\n tableLeft.push(0b11111111 << i);\n}\nmodule.exports = function (imageData) {\n if (imageData.bitDepth !== 1) {\n throw new Error('Only bitDepth of 1 is supported');\n }\n if (!imageData.height || !imageData.width) {\n throw new Error('ImageData width and height are required');\n }\n\n if (imageData.components !== 1) {\n throw new Error('Only 1 component is supported');\n }\n\n if (imageData.channels !== 1) {\n throw new Error('Only 1 channel is supported');\n }\n\n var io = new IOBuffer();\n // skip header\n io.skip(14);\n writeBitmapV5Header(io, imageData);\n writeColorTable(io, imageData);\n const imageOffset = io.offset;\n writePixelArray(io, imageData);\n\n // write header at the end\n io.rewind();\n writeBitmapFileHeader(io, imageOffset);\n return io.getBuffer();\n};\n\nfunction writePixelArray(io, imgData) {\n const rowSize = Math.floor((imgData.bitDepth * imgData.width + 31) / 32) * 4;\n const dataRowSize = Math.ceil(imgData.bitDepth * imgData.width / 8);\n const skipSize = rowSize - dataRowSize;\n const bitOverflow = (imgData.bitDepth * imgData.width) % 8;\n const bitSkip = bitOverflow === 0 ? 0 : 8 - bitOverflow;\n const totalBytes = rowSize * imgData.height;\n\n var byteA, byteB;\n const ioData = new IOBuffer(imgData.data);\n let offset = 0; // Current off set in the ioData\n let relOffset = 0, iOffset = 8;\n io.mark();\n byteB = ioData.readUint8();\n for (var i = imgData.height - 1; i >= 0; i--) {\n const lastRow = (i === 0);\n io.reset();\n io.skip(i * rowSize);\n for (var j = 0; j < dataRowSize; j++) {\n const lastCol = (j === dataRowSize - 1);\n if (relOffset <= bitSkip && lastCol) {\n // no need to read new data\n io.writeByte((byteB << relOffset));\n if ((bitSkip === 0 || bitSkip === relOffset) && !lastRow) {\n byteA = byteB;\n byteB = ioData.readByte();\n }\n } else if (relOffset === 0) {\n byteA = byteB;\n byteB = ioData.readUint8();\n io.writeByte(byteA);\n } else {\n byteA = byteB;\n byteB = ioData.readUint8();\n io.writeByte(((byteA << relOffset) & tableLeft[relOffset]) | (byteB >> iOffset));\n }\n if (lastCol) {\n offset += (bitOverflow || 8);\n io.skip(skipSize);\n relOffset = offset % 8;\n iOffset = 8 - relOffset;\n } else {\n offset += 8;\n }\n }\n }\n if (rowSize > dataRowSize) {\n // make sure last written byte is correct\n io.reset();\n io.skip(totalBytes - 1);\n io.writeUint8(0);\n }\n\n}\n\nfunction writeColorTable(io, imgData) {\n // Color table is optional for bitDepth >= 8\n if (imgData.bitDepth > 8) return;\n // We only handle 1-bit images\n io\n .writeUint32(0x00000000) // black\n .writeUint32(0x00ffffff); //white\n}\n\nfunction writeBitmapFileHeader(io, imageOffset) {\n // 14 bytes bitmap file header\n io.writeChars('BM');\n // Size of BMP file in bytes\n io.writeInt32(io._lastWrittenByte);\n io.writeUint16(0);\n io.writeUint16(0);\n io.writeUint32(imageOffset);\n}\n\nfunction writeBitmapV5Header(io, imgData) {\n // Size of the header\n io\n .writeUint32(124) // Header size\n .writeInt32(imgData.width) // bV5Width\n .writeInt32(imgData.height) // bV5Height\n .writeUint16(1) // bv5Planes - must be set to 1\n .writeUint16(imgData.bitDepth) // bV5BitCount\n .writeUint32(constants.BITMAPV5HEADER.Compression.BI_RGB) // bV5Compression - No compression\n .writeUint32(imgData.width * imgData.height * imgData.bitDepth) // bv5SizeImage - buffer size (optional if uncompressed)\n .writeInt32(0) // bV5XPelsPerMeter - resolution\n .writeInt32(0) // bV5YPelsPerMeter - resolution\n .writeUint32(Math.pow(2, imgData.bitDepth))\n .writeUint32(Math.pow(2, imgData.bitDepth))\n .writeUint32(0xff000000) // bV5RedMask\n .writeUint32(0x00ff0000) // bV5GreenMask\n .writeUint32(0x0000ff00) // bV5BlueMask\n .writeUint32(0x000000ff) // bV5AlphaMask\n .writeUint32(constants.BITMAPV5HEADER.LogicalColorSpace.LCS_sRGB)\n .skip(36) // bV5Endpoints\n .skip(12) // bV5GammaRed, Green, Blue\n .writeUint32(constants.BITMAPV5HEADER.GamutMappingIntent.LCS_GM_IMAGES)\n .skip(12); // ProfileData, ProfileSize, Reserved\n}\n","'use strict';\n\nexports.encode = require('./encode');\n\n","// eslint-disable-next-line import/no-unassigned-import\nimport './text-encoding-polyfill';\nconst decoder = new TextDecoder('utf-8');\nexport function decode(bytes) {\n return decoder.decode(bytes);\n}\nconst encoder = new TextEncoder();\nexport function encode(str) {\n return encoder.encode(str);\n}\n//# sourceMappingURL=utf8.browser.js.map","import { decode, encode } from './utf8';\nconst defaultByteLength = 1024 * 8;\nexport class IOBuffer {\n /**\n * @param data - The data to construct the IOBuffer with.\n * If data is a number, it will be the new buffer's length
\n * If data is `undefined`, the buffer will be initialized with a default length of 8Kb
\n * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,\n * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.\n * @param options\n */\n constructor(data = defaultByteLength, options = {}) {\n let dataIsGiven = false;\n if (typeof data === 'number') {\n data = new ArrayBuffer(data);\n }\n else {\n dataIsGiven = true;\n this.lastWrittenByte = data.byteLength;\n }\n const offset = options.offset ? options.offset >>> 0 : 0;\n const byteLength = data.byteLength - offset;\n let dvOffset = offset;\n if (ArrayBuffer.isView(data) || data instanceof IOBuffer) {\n if (data.byteLength !== data.buffer.byteLength) {\n dvOffset = data.byteOffset + offset;\n }\n data = data.buffer;\n }\n if (dataIsGiven) {\n this.lastWrittenByte = byteLength;\n }\n else {\n this.lastWrittenByte = 0;\n }\n this.buffer = data;\n this.length = byteLength;\n this.byteLength = byteLength;\n this.byteOffset = dvOffset;\n this.offset = 0;\n this.littleEndian = true;\n this._data = new DataView(this.buffer, dvOffset, byteLength);\n this._mark = 0;\n this._marks = [];\n }\n /**\n * Checks if the memory allocated to the buffer is sufficient to store more\n * bytes after the offset.\n * @param byteLength - The needed memory in bytes.\n * @returns `true` if there is sufficient space and `false` otherwise.\n */\n available(byteLength = 1) {\n return this.offset + byteLength <= this.length;\n }\n /**\n * Check if little-endian mode is used for reading and writing multi-byte\n * values.\n * @returns `true` if little-endian mode is used, `false` otherwise.\n */\n isLittleEndian() {\n return this.littleEndian;\n }\n /**\n * Set little-endian mode for reading and writing multi-byte values.\n */\n setLittleEndian() {\n this.littleEndian = true;\n return this;\n }\n /**\n * Check if big-endian mode is used for reading and writing multi-byte values.\n * @returns `true` if big-endian mode is used, `false` otherwise.\n */\n isBigEndian() {\n return !this.littleEndian;\n }\n /**\n * Switches to big-endian mode for reading and writing multi-byte values.\n */\n setBigEndian() {\n this.littleEndian = false;\n return this;\n }\n /**\n * Move the pointer n bytes forward.\n * @param n - Number of bytes to skip.\n */\n skip(n = 1) {\n this.offset += n;\n return this;\n }\n /**\n * Move the pointer to the given offset.\n * @param offset\n */\n seek(offset) {\n this.offset = offset;\n return this;\n }\n /**\n * Store the current pointer offset.\n * @see {@link IOBuffer#reset}\n */\n mark() {\n this._mark = this.offset;\n return this;\n }\n /**\n * Move the pointer back to the last pointer offset set by mark.\n * @see {@link IOBuffer#mark}\n */\n reset() {\n this.offset = this._mark;\n return this;\n }\n /**\n * Push the current pointer offset to the mark stack.\n * @see {@link IOBuffer#popMark}\n */\n pushMark() {\n this._marks.push(this.offset);\n return this;\n }\n /**\n * Pop the last pointer offset from the mark stack, and set the current\n * pointer offset to the popped value.\n * @see {@link IOBuffer#pushMark}\n */\n popMark() {\n const offset = this._marks.pop();\n if (offset === undefined) {\n throw new Error('Mark stack empty');\n }\n this.seek(offset);\n return this;\n }\n /**\n * Move the pointer offset back to 0.\n */\n rewind() {\n this.offset = 0;\n return this;\n }\n /**\n * Make sure the buffer has sufficient memory to write a given byteLength at\n * the current pointer offset.\n * If the buffer's memory is insufficient, this method will create a new\n * buffer (a copy) with a length that is twice (byteLength + current offset).\n * @param byteLength\n */\n ensureAvailable(byteLength = 1) {\n if (!this.available(byteLength)) {\n const lengthNeeded = this.offset + byteLength;\n const newLength = lengthNeeded * 2;\n const newArray = new Uint8Array(newLength);\n newArray.set(new Uint8Array(this.buffer));\n this.buffer = newArray.buffer;\n this.length = this.byteLength = newLength;\n this._data = new DataView(this.buffer);\n }\n return this;\n }\n /**\n * Read a byte and return false if the byte's value is 0, or true otherwise.\n * Moves pointer forward by one byte.\n */\n readBoolean() {\n return this.readUint8() !== 0;\n }\n /**\n * Read a signed 8-bit integer and move pointer forward by 1 byte.\n */\n readInt8() {\n return this._data.getInt8(this.offset++);\n }\n /**\n * Read an unsigned 8-bit integer and move pointer forward by 1 byte.\n */\n readUint8() {\n return this._data.getUint8(this.offset++);\n }\n /**\n * Alias for {@link IOBuffer#readUint8}.\n */\n readByte() {\n return this.readUint8();\n }\n /**\n * Read `n` bytes and move pointer forward by `n` bytes.\n */\n readBytes(n = 1) {\n const bytes = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n bytes[i] = this.readByte();\n }\n return bytes;\n }\n /**\n * Read a 16-bit signed integer and move pointer forward by 2 bytes.\n */\n readInt16() {\n const value = this._data.getInt16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n /**\n * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.\n */\n readUint16() {\n const value = this._data.getUint16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n /**\n * Read a 32-bit signed integer and move pointer forward by 4 bytes.\n */\n readInt32() {\n const value = this._data.getInt32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.\n */\n readUint32() {\n const value = this._data.getUint32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 32-bit floating number and move pointer forward by 4 bytes.\n */\n readFloat32() {\n const value = this._data.getFloat32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 64-bit floating number and move pointer forward by 8 bytes.\n */\n readFloat64() {\n const value = this._data.getFloat64(this.offset, this.littleEndian);\n this.offset += 8;\n return value;\n }\n /**\n * Read a 1-byte ASCII character and move pointer forward by 1 byte.\n */\n readChar() {\n return String.fromCharCode(this.readInt8());\n }\n /**\n * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.\n */\n readChars(n = 1) {\n let result = '';\n for (let i = 0; i < n; i++) {\n result += this.readChar();\n }\n return result;\n }\n /**\n * Read the next `n` bytes, return a UTF-8 decoded string and move pointer\n * forward by `n` bytes.\n */\n readUtf8(n = 1) {\n return decode(this.readBytes(n));\n }\n /**\n * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer\n * forward by 1 byte.\n */\n writeBoolean(value) {\n this.writeUint8(value ? 0xff : 0x00);\n return this;\n }\n /**\n * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.\n */\n writeInt8(value) {\n this.ensureAvailable(1);\n this._data.setInt8(this.offset++, value);\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as an 8-bit unsigned integer and move pointer forward by 1\n * byte.\n */\n writeUint8(value) {\n this.ensureAvailable(1);\n this._data.setUint8(this.offset++, value);\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * An alias for {@link IOBuffer#writeUint8}.\n */\n writeByte(value) {\n return this.writeUint8(value);\n }\n /**\n * Write all elements of `bytes` as uint8 values and move pointer forward by\n * `bytes.length` bytes.\n */\n writeBytes(bytes) {\n this.ensureAvailable(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n this._data.setUint8(this.offset++, bytes[i]);\n }\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 16-bit signed integer and move pointer forward by 2\n * bytes.\n */\n writeInt16(value) {\n this.ensureAvailable(2);\n this._data.setInt16(this.offset, value, this.littleEndian);\n this.offset += 2;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 16-bit unsigned integer and move pointer forward by 2\n * bytes.\n */\n writeUint16(value) {\n this.ensureAvailable(2);\n this._data.setUint16(this.offset, value, this.littleEndian);\n this.offset += 2;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit signed integer and move pointer forward by 4\n * bytes.\n */\n writeInt32(value) {\n this.ensureAvailable(4);\n this._data.setInt32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit unsigned integer and move pointer forward by 4\n * bytes.\n */\n writeUint32(value) {\n this.ensureAvailable(4);\n this._data.setUint32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit floating number and move pointer forward by 4\n * bytes.\n */\n writeFloat32(value) {\n this.ensureAvailable(4);\n this._data.setFloat32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 64-bit floating number and move pointer forward by 8\n * bytes.\n */\n writeFloat64(value) {\n this.ensureAvailable(8);\n this._data.setFloat64(this.offset, value, this.littleEndian);\n this.offset += 8;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write the charCode of `str`'s first character as an 8-bit unsigned integer\n * and move pointer forward by 1 byte.\n */\n writeChar(str) {\n return this.writeUint8(str.charCodeAt(0));\n }\n /**\n * Write the charCodes of all `str`'s characters as 8-bit unsigned integers\n * and move pointer forward by `str.length` bytes.\n */\n writeChars(str) {\n for (let i = 0; i < str.length; i++) {\n this.writeUint8(str.charCodeAt(i));\n }\n return this;\n }\n /**\n * UTF-8 encode and write `str` to the current pointer offset and move pointer\n * forward according to the encoded length.\n */\n writeUtf8(str) {\n return this.writeBytes(encode(str));\n }\n /**\n * Export a Uint8Array view of the internal buffer.\n * The view starts at the byte offset and its length\n * is calculated to stop at the last written byte or the original length.\n */\n toArray() {\n return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);\n }\n /**\n * Update the last written byte offset\n * @private\n */\n _updateLastWrittenByte() {\n if (this.offset > this.lastWrittenByte) {\n this.lastWrittenByte = this.offset;\n }\n }\n}\n//# sourceMappingURL=IOBuffer.js.map","\n/*! pako 2.0.3 https://github.com/nodeca/pako @license (MIT AND Zlib) */\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n/* eslint-disable space-unary-ops */\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\n\n//const Z_FILTERED = 1;\n//const Z_HUFFMAN_ONLY = 2;\n//const Z_RLE = 3;\nconst Z_FIXED = 4;\n//const Z_DEFAULT_STRATEGY = 0;\n\n/* Possible values of the data_type field (though see inflate()) */\nconst Z_BINARY = 0;\nconst Z_TEXT = 1;\n//const Z_ASCII = 1; // = Z_TEXT\nconst Z_UNKNOWN = 2;\n\n/*============================================================================*/\n\n\nfunction zero(buf) { let len = buf.length; while (--len >= 0) { buf[len] = 0; } }\n\n// From zutil.h\n\nconst STORED_BLOCK = 0;\nconst STATIC_TREES = 1;\nconst DYN_TREES = 2;\n/* The three kinds of block type */\n\nconst MIN_MATCH = 3;\nconst MAX_MATCH = 258;\n/* The minimum and maximum match lengths */\n\n// From deflate.h\n/* ===========================================================================\n * Internal compression state.\n */\n\nconst LENGTH_CODES = 29;\n/* number of length codes, not counting the special END_BLOCK code */\n\nconst LITERALS = 256;\n/* number of literal bytes 0..255 */\n\nconst L_CODES = LITERALS + 1 + LENGTH_CODES;\n/* number of Literal or Length codes, including the END_BLOCK code */\n\nconst D_CODES = 30;\n/* number of distance codes */\n\nconst BL_CODES = 19;\n/* number of codes used to transfer the bit lengths */\n\nconst HEAP_SIZE = 2 * L_CODES + 1;\n/* maximum heap size */\n\nconst MAX_BITS = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst Buf_size = 16;\n/* size of bit buffer in bi_buf */\n\n\n/* ===========================================================================\n * Constants\n */\n\nconst MAX_BL_BITS = 7;\n/* Bit length codes must not exceed MAX_BL_BITS bits */\n\nconst END_BLOCK = 256;\n/* end of block literal code */\n\nconst REP_3_6 = 16;\n/* repeat previous bit length 3-6 times (2 bits of repeat count) */\n\nconst REPZ_3_10 = 17;\n/* repeat a zero length 3-10 times (3 bits of repeat count) */\n\nconst REPZ_11_138 = 18;\n/* repeat a zero length 11-138 times (7 bits of repeat count) */\n\n/* eslint-disable comma-spacing,array-bracket-spacing */\nconst extra_lbits = /* extra bits for each length code */\n new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);\n\nconst extra_dbits = /* extra bits for each distance code */\n new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);\n\nconst extra_blbits = /* extra bits for each bit length code */\n new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);\n\nconst bl_order =\n new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);\n/* eslint-enable comma-spacing,array-bracket-spacing */\n\n/* The lengths of the bit length codes are sent in order of decreasing\n * probability, to avoid transmitting the lengths for unused bit length codes.\n */\n\n/* ===========================================================================\n * Local data. These are initialized only once.\n */\n\n// We pre-fill arrays with 0 to avoid uninitialized gaps\n\nconst DIST_CODE_LEN = 512; /* see definition of array dist_code below */\n\n// !!!! Use flat array instead of structure, Freq = i*2, Len = i*2+1\nconst static_ltree = new Array((L_CODES + 2) * 2);\nzero(static_ltree);\n/* The static literal tree. Since the bit lengths are imposed, there is no\n * need for the L_CODES extra codes used during heap construction. However\n * The codes 286 and 287 are needed to build a canonical tree (see _tr_init\n * below).\n */\n\nconst static_dtree = new Array(D_CODES * 2);\nzero(static_dtree);\n/* The static distance tree. (Actually a trivial tree since all codes use\n * 5 bits.)\n */\n\nconst _dist_code = new Array(DIST_CODE_LEN);\nzero(_dist_code);\n/* Distance codes. The first 256 values correspond to the distances\n * 3 .. 258, the last 256 values correspond to the top 8 bits of\n * the 15 bit distances.\n */\n\nconst _length_code = new Array(MAX_MATCH - MIN_MATCH + 1);\nzero(_length_code);\n/* length code for each normalized match length (0 == MIN_MATCH) */\n\nconst base_length = new Array(LENGTH_CODES);\nzero(base_length);\n/* First normalized length for each code (0 = MIN_MATCH) */\n\nconst base_dist = new Array(D_CODES);\nzero(base_dist);\n/* First normalized distance for each code (0 = distance of 1) */\n\n\nfunction StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) {\n\n this.static_tree = static_tree; /* static tree or NULL */\n this.extra_bits = extra_bits; /* extra bits for each code or NULL */\n this.extra_base = extra_base; /* base index for extra_bits */\n this.elems = elems; /* max number of elements in the tree */\n this.max_length = max_length; /* max bit length for the codes */\n\n // show if `static_tree` has data or dummy - needed for monomorphic objects\n this.has_stree = static_tree && static_tree.length;\n}\n\n\nlet static_l_desc;\nlet static_d_desc;\nlet static_bl_desc;\n\n\nfunction TreeDesc(dyn_tree, stat_desc) {\n this.dyn_tree = dyn_tree; /* the dynamic tree */\n this.max_code = 0; /* largest code with non zero frequency */\n this.stat_desc = stat_desc; /* the corresponding static tree */\n}\n\n\n\nconst d_code = (dist) => {\n\n return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];\n};\n\n\n/* ===========================================================================\n * Output a short LSB first on the stream.\n * IN assertion: there is enough room in pendingBuf.\n */\nconst put_short = (s, w) => {\n// put_byte(s, (uch)((w) & 0xff));\n// put_byte(s, (uch)((ush)(w) >> 8));\n s.pending_buf[s.pending++] = (w) & 0xff;\n s.pending_buf[s.pending++] = (w >>> 8) & 0xff;\n};\n\n\n/* ===========================================================================\n * Send a value on a given number of bits.\n * IN assertion: length <= 16 and value fits in length bits.\n */\nconst send_bits = (s, value, length) => {\n\n if (s.bi_valid > (Buf_size - length)) {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n put_short(s, s.bi_buf);\n s.bi_buf = value >> (Buf_size - s.bi_valid);\n s.bi_valid += length - Buf_size;\n } else {\n s.bi_buf |= (value << s.bi_valid) & 0xffff;\n s.bi_valid += length;\n }\n};\n\n\nconst send_code = (s, c, tree) => {\n\n send_bits(s, tree[c * 2]/*.Code*/, tree[c * 2 + 1]/*.Len*/);\n};\n\n\n/* ===========================================================================\n * Reverse the first len bits of a code, using straightforward code (a faster\n * method would use a table)\n * IN assertion: 1 <= len <= 15\n */\nconst bi_reverse = (code, len) => {\n\n let res = 0;\n do {\n res |= code & 1;\n code >>>= 1;\n res <<= 1;\n } while (--len > 0);\n return res >>> 1;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer, keeping at most 7 bits in it.\n */\nconst bi_flush = (s) => {\n\n if (s.bi_valid === 16) {\n put_short(s, s.bi_buf);\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n } else if (s.bi_valid >= 8) {\n s.pending_buf[s.pending++] = s.bi_buf & 0xff;\n s.bi_buf >>= 8;\n s.bi_valid -= 8;\n }\n};\n\n\n/* ===========================================================================\n * Compute the optimal bit lengths for a tree and update the total bit length\n * for the current block.\n * IN assertion: the fields freq and dad are set, heap[heap_max] and\n * above are the tree nodes sorted by increasing frequency.\n * OUT assertions: the field len is set to the optimal bit length, the\n * array bl_count contains the frequencies for each bit length.\n * The length opt_len is updated; static_len is also updated if stree is\n * not null.\n */\nconst gen_bitlen = (s, desc) =>\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const max_code = desc.max_code;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const extra = desc.stat_desc.extra_bits;\n const base = desc.stat_desc.extra_base;\n const max_length = desc.stat_desc.max_length;\n let h; /* heap index */\n let n, m; /* iterate over the tree elements */\n let bits; /* bit length */\n let xbits; /* extra bits */\n let f; /* frequency */\n let overflow = 0; /* number of elements with bit length too large */\n\n for (bits = 0; bits <= MAX_BITS; bits++) {\n s.bl_count[bits] = 0;\n }\n\n /* In a first pass, compute the optimal bit lengths (which may\n * overflow in the case of the bit length tree).\n */\n tree[s.heap[s.heap_max] * 2 + 1]/*.Len*/ = 0; /* root of the heap */\n\n for (h = s.heap_max + 1; h < HEAP_SIZE; h++) {\n n = s.heap[h];\n bits = tree[tree[n * 2 + 1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;\n if (bits > max_length) {\n bits = max_length;\n overflow++;\n }\n tree[n * 2 + 1]/*.Len*/ = bits;\n /* We overwrite tree[n].Dad which is no longer needed */\n\n if (n > max_code) { continue; } /* not a leaf node */\n\n s.bl_count[bits]++;\n xbits = 0;\n if (n >= base) {\n xbits = extra[n - base];\n }\n f = tree[n * 2]/*.Freq*/;\n s.opt_len += f * (bits + xbits);\n if (has_stree) {\n s.static_len += f * (stree[n * 2 + 1]/*.Len*/ + xbits);\n }\n }\n if (overflow === 0) { return; }\n\n // Trace((stderr,\"\\nbit length overflow\\n\"));\n /* This happens for example on obj2 and pic of the Calgary corpus */\n\n /* Find the first bit length which could increase: */\n do {\n bits = max_length - 1;\n while (s.bl_count[bits] === 0) { bits--; }\n s.bl_count[bits]--; /* move one leaf down the tree */\n s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */\n s.bl_count[max_length]--;\n /* The brother of the overflow item also moves one step up,\n * but this does not affect bl_count[max_length]\n */\n overflow -= 2;\n } while (overflow > 0);\n\n /* Now recompute all bit lengths, scanning in increasing frequency.\n * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all\n * lengths instead of fixing only the wrong ones. This idea is taken\n * from 'ar' written by Haruhiko Okumura.)\n */\n for (bits = max_length; bits !== 0; bits--) {\n n = s.bl_count[bits];\n while (n !== 0) {\n m = s.heap[--h];\n if (m > max_code) { continue; }\n if (tree[m * 2 + 1]/*.Len*/ !== bits) {\n // Trace((stderr,\"code %d bits %d->%d\\n\", m, tree[m].Len, bits));\n s.opt_len += (bits - tree[m * 2 + 1]/*.Len*/) * tree[m * 2]/*.Freq*/;\n tree[m * 2 + 1]/*.Len*/ = bits;\n }\n n--;\n }\n }\n};\n\n\n/* ===========================================================================\n * Generate the codes for a given tree and bit counts (which need not be\n * optimal).\n * IN assertion: the array bl_count contains the bit length statistics for\n * the given tree and the field len is set for all tree elements.\n * OUT assertion: the field code is set for all tree elements of non\n * zero code length.\n */\nconst gen_codes = (tree, max_code, bl_count) =>\n// ct_data *tree; /* the tree to decorate */\n// int max_code; /* largest code with non zero frequency */\n// ushf *bl_count; /* number of codes at each bit length */\n{\n const next_code = new Array(MAX_BITS + 1); /* next code value for each bit length */\n let code = 0; /* running code value */\n let bits; /* bit index */\n let n; /* code index */\n\n /* The distribution counts are first used to generate the code values\n * without bit reversal.\n */\n for (bits = 1; bits <= MAX_BITS; bits++) {\n next_code[bits] = code = (code + bl_count[bits - 1]) << 1;\n }\n /* Check that the bit counts in bl_count are consistent. The last code\n * must be all ones.\n */\n //Assert (code + bl_count[MAX_BITS]-1 == (1< {\n\n let n; /* iterates over tree elements */\n let bits; /* bit counter */\n let length; /* length value */\n let code; /* code value */\n let dist; /* distance index */\n const bl_count = new Array(MAX_BITS + 1);\n /* number of codes at each bit length for an optimal tree */\n\n // do check in _tr_init()\n //if (static_init_done) return;\n\n /* For some embedded targets, global variables are not initialized: */\n/*#ifdef NO_INIT_GLOBAL_POINTERS\n static_l_desc.static_tree = static_ltree;\n static_l_desc.extra_bits = extra_lbits;\n static_d_desc.static_tree = static_dtree;\n static_d_desc.extra_bits = extra_dbits;\n static_bl_desc.extra_bits = extra_blbits;\n#endif*/\n\n /* Initialize the mapping length (0..255) -> length code (0..28) */\n length = 0;\n for (code = 0; code < LENGTH_CODES - 1; code++) {\n base_length[code] = length;\n for (n = 0; n < (1 << extra_lbits[code]); n++) {\n _length_code[length++] = code;\n }\n }\n //Assert (length == 256, \"tr_static_init: length != 256\");\n /* Note that the length 255 (match length 258) can be represented\n * in two different ways: code 284 + 5 bits or code 285, so we\n * overwrite length_code[255] to use the best encoding:\n */\n _length_code[length - 1] = code;\n\n /* Initialize the mapping dist (0..32K) -> dist code (0..29) */\n dist = 0;\n for (code = 0; code < 16; code++) {\n base_dist[code] = dist;\n for (n = 0; n < (1 << extra_dbits[code]); n++) {\n _dist_code[dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: dist != 256\");\n dist >>= 7; /* from now on, all distances are divided by 128 */\n for (; code < D_CODES; code++) {\n base_dist[code] = dist << 7;\n for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) {\n _dist_code[256 + dist++] = code;\n }\n }\n //Assert (dist == 256, \"tr_static_init: 256+dist != 512\");\n\n /* Construct the codes of the static literal tree */\n for (bits = 0; bits <= MAX_BITS; bits++) {\n bl_count[bits] = 0;\n }\n\n n = 0;\n while (n <= 143) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n while (n <= 255) {\n static_ltree[n * 2 + 1]/*.Len*/ = 9;\n n++;\n bl_count[9]++;\n }\n while (n <= 279) {\n static_ltree[n * 2 + 1]/*.Len*/ = 7;\n n++;\n bl_count[7]++;\n }\n while (n <= 287) {\n static_ltree[n * 2 + 1]/*.Len*/ = 8;\n n++;\n bl_count[8]++;\n }\n /* Codes 286 and 287 do not exist, but we must include them in the\n * tree construction to get a canonical Huffman tree (longest code\n * all ones)\n */\n gen_codes(static_ltree, L_CODES + 1, bl_count);\n\n /* The static distance tree is trivial: */\n for (n = 0; n < D_CODES; n++) {\n static_dtree[n * 2 + 1]/*.Len*/ = 5;\n static_dtree[n * 2]/*.Code*/ = bi_reverse(n, 5);\n }\n\n // Now data ready and we can init static trees\n static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS + 1, L_CODES, MAX_BITS);\n static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);\n static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);\n\n //static_init_done = true;\n};\n\n\n/* ===========================================================================\n * Initialize a new block.\n */\nconst init_block = (s) => {\n\n let n; /* iterates over tree elements */\n\n /* Initialize the trees. */\n for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n * 2]/*.Freq*/ = 0; }\n for (n = 0; n < BL_CODES; n++) { s.bl_tree[n * 2]/*.Freq*/ = 0; }\n\n s.dyn_ltree[END_BLOCK * 2]/*.Freq*/ = 1;\n s.opt_len = s.static_len = 0;\n s.last_lit = s.matches = 0;\n};\n\n\n/* ===========================================================================\n * Flush the bit buffer and align the output on a byte boundary\n */\nconst bi_windup = (s) =>\n{\n if (s.bi_valid > 8) {\n put_short(s, s.bi_buf);\n } else if (s.bi_valid > 0) {\n //put_byte(s, (Byte)s->bi_buf);\n s.pending_buf[s.pending++] = s.bi_buf;\n }\n s.bi_buf = 0;\n s.bi_valid = 0;\n};\n\n/* ===========================================================================\n * Copy a stored block, storing first the length and its\n * one's complement if requested.\n */\nconst copy_block = (s, buf, len, header) =>\n//DeflateState *s;\n//charf *buf; /* the input data */\n//unsigned len; /* its length */\n//int header; /* true if block header must be written */\n{\n bi_windup(s); /* align on byte boundary */\n\n if (header) {\n put_short(s, len);\n put_short(s, ~len);\n }\n// while (len--) {\n// put_byte(s, *buf++);\n// }\n s.pending_buf.set(s.window.subarray(buf, buf + len), s.pending);\n s.pending += len;\n};\n\n/* ===========================================================================\n * Compares to subtrees, using the tree depth as tie breaker when\n * the subtrees have equal frequency. This minimizes the worst case length.\n */\nconst smaller = (tree, n, m, depth) => {\n\n const _n2 = n * 2;\n const _m2 = m * 2;\n return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||\n (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));\n};\n\n/* ===========================================================================\n * Restore the heap property by moving down the tree starting at node k,\n * exchanging a node with the smallest of its two sons if necessary, stopping\n * when the heap property is re-established (each father smaller than its\n * two sons).\n */\nconst pqdownheap = (s, tree, k) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to restore */\n// int k; /* node to move down */\n{\n const v = s.heap[k];\n let j = k << 1; /* left son of k */\n while (j <= s.heap_len) {\n /* Set j to the smallest of the two sons: */\n if (j < s.heap_len &&\n smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) {\n j++;\n }\n /* Exit if v is smaller than both sons */\n if (smaller(tree, v, s.heap[j], s.depth)) { break; }\n\n /* Exchange v with the smallest son */\n s.heap[k] = s.heap[j];\n k = j;\n\n /* And continue down the tree, setting j to the left son of k */\n j <<= 1;\n }\n s.heap[k] = v;\n};\n\n\n// inlined manually\n// const SMALLEST = 1;\n\n/* ===========================================================================\n * Send the block data compressed using the given Huffman trees\n */\nconst compress_block = (s, ltree, dtree) =>\n// deflate_state *s;\n// const ct_data *ltree; /* literal tree */\n// const ct_data *dtree; /* distance tree */\n{\n let dist; /* distance of matched string */\n let lc; /* match length or unmatched char (if dist == 0) */\n let lx = 0; /* running index in l_buf */\n let code; /* the code to send */\n let extra; /* number of extra bits to send */\n\n if (s.last_lit !== 0) {\n do {\n dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]);\n lc = s.pending_buf[s.l_buf + lx];\n lx++;\n\n if (dist === 0) {\n send_code(s, lc, ltree); /* send a literal byte */\n //Tracecv(isgraph(lc), (stderr,\" '%c' \", lc));\n } else {\n /* Here, lc is the match length - MIN_MATCH */\n code = _length_code[lc];\n send_code(s, code + LITERALS + 1, ltree); /* send the length code */\n extra = extra_lbits[code];\n if (extra !== 0) {\n lc -= base_length[code];\n send_bits(s, lc, extra); /* send the extra length bits */\n }\n dist--; /* dist is now the match distance - 1 */\n code = d_code(dist);\n //Assert (code < D_CODES, \"bad d_code\");\n\n send_code(s, code, dtree); /* send the distance code */\n extra = extra_dbits[code];\n if (extra !== 0) {\n dist -= base_dist[code];\n send_bits(s, dist, extra); /* send the extra distance bits */\n }\n } /* literal or match pair ? */\n\n /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */\n //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,\n // \"pendingBuf overflow\");\n\n } while (lx < s.last_lit);\n }\n\n send_code(s, END_BLOCK, ltree);\n};\n\n\n/* ===========================================================================\n * Construct one Huffman tree and assigns the code bit strings and lengths.\n * Update the total bit length for the current block.\n * IN assertion: the field freq is set for all tree elements.\n * OUT assertions: the fields len and code are set to the optimal bit length\n * and corresponding code. The length opt_len is updated; static_len is\n * also updated if stree is not null. The field max_code is set.\n */\nconst build_tree = (s, desc) =>\n// deflate_state *s;\n// tree_desc *desc; /* the tree descriptor */\n{\n const tree = desc.dyn_tree;\n const stree = desc.stat_desc.static_tree;\n const has_stree = desc.stat_desc.has_stree;\n const elems = desc.stat_desc.elems;\n let n, m; /* iterate over heap elements */\n let max_code = -1; /* largest code with non zero frequency */\n let node; /* new node being created */\n\n /* Construct the initial heap, with least frequent element in\n * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].\n * heap[0] is not used.\n */\n s.heap_len = 0;\n s.heap_max = HEAP_SIZE;\n\n for (n = 0; n < elems; n++) {\n if (tree[n * 2]/*.Freq*/ !== 0) {\n s.heap[++s.heap_len] = max_code = n;\n s.depth[n] = 0;\n\n } else {\n tree[n * 2 + 1]/*.Len*/ = 0;\n }\n }\n\n /* The pkzip format requires that at least one distance code exists,\n * and that at least one bit should be sent even if there is only one\n * possible code. So to avoid special checks later on we force at least\n * two codes of non zero frequency.\n */\n while (s.heap_len < 2) {\n node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);\n tree[node * 2]/*.Freq*/ = 1;\n s.depth[node] = 0;\n s.opt_len--;\n\n if (has_stree) {\n s.static_len -= stree[node * 2 + 1]/*.Len*/;\n }\n /* node is 0 or 1 so it does not have extra bits */\n }\n desc.max_code = max_code;\n\n /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,\n * establish sub-heaps of increasing lengths:\n */\n for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }\n\n /* Construct the Huffman tree by repeatedly combining the least two\n * frequent nodes.\n */\n node = elems; /* next internal node of the tree */\n do {\n //pqremove(s, tree, n); /* n = node of least frequency */\n /*** pqremove ***/\n n = s.heap[1/*SMALLEST*/];\n s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];\n pqdownheap(s, tree, 1/*SMALLEST*/);\n /***/\n\n m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */\n\n s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */\n s.heap[--s.heap_max] = m;\n\n /* Create a new node father of n and m */\n tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;\n s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;\n tree[n * 2 + 1]/*.Dad*/ = tree[m * 2 + 1]/*.Dad*/ = node;\n\n /* and insert the new node in the heap */\n s.heap[1/*SMALLEST*/] = node++;\n pqdownheap(s, tree, 1/*SMALLEST*/);\n\n } while (s.heap_len >= 2);\n\n s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];\n\n /* At this point, the fields freq and dad are set. We can now\n * generate the bit lengths.\n */\n gen_bitlen(s, desc);\n\n /* The field len is now set, we can generate the bit codes */\n gen_codes(tree, max_code, s.bl_count);\n};\n\n\n/* ===========================================================================\n * Scan a literal or distance tree to determine the frequencies of the codes\n * in the bit length tree.\n */\nconst scan_tree = (s, tree, max_code) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n tree[(max_code + 1) * 2 + 1]/*.Len*/ = 0xffff; /* guard */\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n s.bl_tree[curlen * 2]/*.Freq*/ += count;\n\n } else if (curlen !== 0) {\n\n if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }\n s.bl_tree[REP_3_6 * 2]/*.Freq*/++;\n\n } else if (count <= 10) {\n s.bl_tree[REPZ_3_10 * 2]/*.Freq*/++;\n\n } else {\n s.bl_tree[REPZ_11_138 * 2]/*.Freq*/++;\n }\n\n count = 0;\n prevlen = curlen;\n\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Send a literal or distance tree in compressed form, using the codes in\n * bl_tree.\n */\nconst send_tree = (s, tree, max_code) =>\n// deflate_state *s;\n// ct_data *tree; /* the tree to be scanned */\n// int max_code; /* and its largest code of non zero frequency */\n{\n let n; /* iterates over all tree elements */\n let prevlen = -1; /* last emitted length */\n let curlen; /* length of current code */\n\n let nextlen = tree[0 * 2 + 1]/*.Len*/; /* length of next code */\n\n let count = 0; /* repeat count of the current code */\n let max_count = 7; /* max repeat count */\n let min_count = 4; /* min repeat count */\n\n /* tree[max_code+1].Len = -1; */ /* guard already set */\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n }\n\n for (n = 0; n <= max_code; n++) {\n curlen = nextlen;\n nextlen = tree[(n + 1) * 2 + 1]/*.Len*/;\n\n if (++count < max_count && curlen === nextlen) {\n continue;\n\n } else if (count < min_count) {\n do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);\n\n } else if (curlen !== 0) {\n if (curlen !== prevlen) {\n send_code(s, curlen, s.bl_tree);\n count--;\n }\n //Assert(count >= 3 && count <= 6, \" 3_6?\");\n send_code(s, REP_3_6, s.bl_tree);\n send_bits(s, count - 3, 2);\n\n } else if (count <= 10) {\n send_code(s, REPZ_3_10, s.bl_tree);\n send_bits(s, count - 3, 3);\n\n } else {\n send_code(s, REPZ_11_138, s.bl_tree);\n send_bits(s, count - 11, 7);\n }\n\n count = 0;\n prevlen = curlen;\n if (nextlen === 0) {\n max_count = 138;\n min_count = 3;\n\n } else if (curlen === nextlen) {\n max_count = 6;\n min_count = 3;\n\n } else {\n max_count = 7;\n min_count = 4;\n }\n }\n};\n\n\n/* ===========================================================================\n * Construct the Huffman tree for the bit lengths and return the index in\n * bl_order of the last bit length code to send.\n */\nconst build_bl_tree = (s) => {\n\n let max_blindex; /* index of last bit length code of non zero freq */\n\n /* Determine the bit length frequencies for literal and distance trees */\n scan_tree(s, s.dyn_ltree, s.l_desc.max_code);\n scan_tree(s, s.dyn_dtree, s.d_desc.max_code);\n\n /* Build the bit length tree: */\n build_tree(s, s.bl_desc);\n /* opt_len now includes the length of the tree representations, except\n * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.\n */\n\n /* Determine the number of bit length codes to send. The pkzip format\n * requires that at least 4 bit length codes be sent. (appnote.txt says\n * 3 but the actual value used is 4.)\n */\n for (max_blindex = BL_CODES - 1; max_blindex >= 3; max_blindex--) {\n if (s.bl_tree[bl_order[max_blindex] * 2 + 1]/*.Len*/ !== 0) {\n break;\n }\n }\n /* Update opt_len to include the bit length tree and counts */\n s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4;\n //Tracev((stderr, \"\\ndyn trees: dyn %ld, stat %ld\",\n // s->opt_len, s->static_len));\n\n return max_blindex;\n};\n\n\n/* ===========================================================================\n * Send the header for a block using dynamic Huffman trees: the counts, the\n * lengths of the bit length codes, the literal tree and the distance tree.\n * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.\n */\nconst send_all_trees = (s, lcodes, dcodes, blcodes) =>\n// deflate_state *s;\n// int lcodes, dcodes, blcodes; /* number of codes for each tree */\n{\n let rank; /* index in bl_order */\n\n //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, \"not enough codes\");\n //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,\n // \"too many codes\");\n //Tracev((stderr, \"\\nbl counts: \"));\n send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */\n send_bits(s, dcodes - 1, 5);\n send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */\n for (rank = 0; rank < blcodes; rank++) {\n //Tracev((stderr, \"\\nbl code %2d \", bl_order[rank]));\n send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1]/*.Len*/, 3);\n }\n //Tracev((stderr, \"\\nbl tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */\n //Tracev((stderr, \"\\nlit tree: sent %ld\", s->bits_sent));\n\n send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */\n //Tracev((stderr, \"\\ndist tree: sent %ld\", s->bits_sent));\n};\n\n\n/* ===========================================================================\n * Check if the data type is TEXT or BINARY, using the following algorithm:\n * - TEXT if the two conditions below are satisfied:\n * a) There are no non-portable control characters belonging to the\n * \"black list\" (0..6, 14..25, 28..31).\n * b) There is at least one printable character belonging to the\n * \"white list\" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).\n * - BINARY otherwise.\n * - The following partially-portable control characters form a\n * \"gray list\" that is ignored in this detection algorithm:\n * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).\n * IN assertion: the fields Freq of dyn_ltree are set.\n */\nconst detect_data_type = (s) => {\n /* black_mask is the bit mask of black-listed bytes\n * set bits 0..6, 14..25, and 28..31\n * 0xf3ffc07f = binary 11110011111111111100000001111111\n */\n let black_mask = 0xf3ffc07f;\n let n;\n\n /* Check for non-textual (\"black-listed\") bytes. */\n for (n = 0; n <= 31; n++, black_mask >>>= 1) {\n if ((black_mask & 1) && (s.dyn_ltree[n * 2]/*.Freq*/ !== 0)) {\n return Z_BINARY;\n }\n }\n\n /* Check for textual (\"white-listed\") bytes. */\n if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||\n s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n for (n = 32; n < LITERALS; n++) {\n if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {\n return Z_TEXT;\n }\n }\n\n /* There are no \"black-listed\" or \"white-listed\" bytes:\n * this stream either is empty or has tolerated (\"gray-listed\") bytes only.\n */\n return Z_BINARY;\n};\n\n\nlet static_init_done = false;\n\n/* ===========================================================================\n * Initialize the tree data structures for a new zlib stream.\n */\nconst _tr_init = (s) =>\n{\n\n if (!static_init_done) {\n tr_static_init();\n static_init_done = true;\n }\n\n s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);\n s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);\n s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);\n\n s.bi_buf = 0;\n s.bi_valid = 0;\n\n /* Initialize the first block of the first file: */\n init_block(s);\n};\n\n\n/* ===========================================================================\n * Send a stored block\n */\nconst _tr_stored_block = (s, buf, stored_len, last) =>\n//DeflateState *s;\n//charf *buf; /* input block */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */\n copy_block(s, buf, stored_len, true); /* with header */\n};\n\n\n/* ===========================================================================\n * Send one empty static block to give enough lookahead for inflate.\n * This takes 10 bits, of which 7 may remain in the bit buffer.\n */\nconst _tr_align = (s) => {\n send_bits(s, STATIC_TREES << 1, 3);\n send_code(s, END_BLOCK, static_ltree);\n bi_flush(s);\n};\n\n\n/* ===========================================================================\n * Determine the best encoding for the current block: dynamic trees, static\n * trees or store, and output the encoded block to the zip file.\n */\nconst _tr_flush_block = (s, buf, stored_len, last) =>\n//DeflateState *s;\n//charf *buf; /* input block, or NULL if too old */\n//ulg stored_len; /* length of input block */\n//int last; /* one if this is the last block for a file */\n{\n let opt_lenb, static_lenb; /* opt_len and static_len in bytes */\n let max_blindex = 0; /* index of last bit length code of non zero freq */\n\n /* Build the Huffman trees unless a stored block is forced */\n if (s.level > 0) {\n\n /* Check if the file is binary or text */\n if (s.strm.data_type === Z_UNKNOWN) {\n s.strm.data_type = detect_data_type(s);\n }\n\n /* Construct the literal and distance trees */\n build_tree(s, s.l_desc);\n // Tracev((stderr, \"\\nlit data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n\n build_tree(s, s.d_desc);\n // Tracev((stderr, \"\\ndist data: dyn %ld, stat %ld\", s->opt_len,\n // s->static_len));\n /* At this point, opt_len and static_len are the total bit lengths of\n * the compressed block data, excluding the tree representations.\n */\n\n /* Build the bit length tree for the above two trees, and get the index\n * in bl_order of the last bit length code to send.\n */\n max_blindex = build_bl_tree(s);\n\n /* Determine the best encoding. Compute the block lengths in bytes. */\n opt_lenb = (s.opt_len + 3 + 7) >>> 3;\n static_lenb = (s.static_len + 3 + 7) >>> 3;\n\n // Tracev((stderr, \"\\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u \",\n // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,\n // s->last_lit));\n\n if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }\n\n } else {\n // Assert(buf != (char*)0, \"lost buf\");\n opt_lenb = static_lenb = stored_len + 5; /* force a stored block */\n }\n\n if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) {\n /* 4: two words for the lengths */\n\n /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.\n * Otherwise we can't have processed more than WSIZE input bytes since\n * the last block flush, because compression would have been\n * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to\n * transform a block into a stored block.\n */\n _tr_stored_block(s, buf, stored_len, last);\n\n } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {\n\n send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3);\n compress_block(s, static_ltree, static_dtree);\n\n } else {\n send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3);\n send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1);\n compress_block(s, s.dyn_ltree, s.dyn_dtree);\n }\n // Assert (s->compressed_len == s->bits_sent, \"bad compressed size\");\n /* The above check is made mod 2^32, for files larger than 512 MB\n * and uLong implemented on 32 bits.\n */\n init_block(s);\n\n if (last) {\n bi_windup(s);\n }\n // Tracev((stderr,\"\\ncomprlen %lu(%lu) \", s->compressed_len>>3,\n // s->compressed_len-7*last));\n};\n\n/* ===========================================================================\n * Save the match info and tally the frequency counts. Return true if\n * the current block must be flushed.\n */\nconst _tr_tally = (s, dist, lc) =>\n// deflate_state *s;\n// unsigned dist; /* distance of matched string */\n// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */\n{\n //let out_length, in_length, dcode;\n\n s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;\n s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;\n\n s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;\n s.last_lit++;\n\n if (dist === 0) {\n /* lc is the unmatched char */\n s.dyn_ltree[lc * 2]/*.Freq*/++;\n } else {\n s.matches++;\n /* Here, lc is the match length - MIN_MATCH */\n dist--; /* dist = match distance - 1 */\n //Assert((ush)dist < (ush)MAX_DIST(s) &&\n // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&\n // (ush)d_code(dist) < (ush)D_CODES, \"_tr_tally: bad match\");\n\n s.dyn_ltree[(_length_code[lc] + LITERALS + 1) * 2]/*.Freq*/++;\n s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n\n//#ifdef TRUNCATE_BLOCK\n// /* Try to guess if it is profitable to stop the current block here */\n// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {\n// /* Compute an upper bound for the compressed length */\n// out_length = s.last_lit*8;\n// in_length = s.strstart - s.block_start;\n//\n// for (dcode = 0; dcode < D_CODES; dcode++) {\n// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);\n// }\n// out_length >>>= 3;\n// //Tracev((stderr,\"\\nlast_lit %u, in %ld, out ~%ld(%ld%%) \",\n// // s->last_lit, in_length, out_length,\n// // 100L - out_length*100L/in_length));\n// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {\n// return true;\n// }\n// }\n//#endif\n\n return (s.last_lit === s.lit_bufsize - 1);\n /* We avoid equality with lit_bufsize because of wraparound at 64K\n * on 16 bit machines and because stored blocks are restricted to\n * 64K-1 bytes.\n */\n};\n\nvar _tr_init_1 = _tr_init;\nvar _tr_stored_block_1 = _tr_stored_block;\nvar _tr_flush_block_1 = _tr_flush_block;\nvar _tr_tally_1 = _tr_tally;\nvar _tr_align_1 = _tr_align;\n\nvar trees = {\n\t_tr_init: _tr_init_1,\n\t_tr_stored_block: _tr_stored_block_1,\n\t_tr_flush_block: _tr_flush_block_1,\n\t_tr_tally: _tr_tally_1,\n\t_tr_align: _tr_align_1\n};\n\n// Note: adler32 takes 12% for level 0 and 2% for level 6.\n// It isn't worth it to make additional optimizations as in original.\n// Small size is preferable.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst adler32 = (adler, buf, len, pos) => {\n let s1 = (adler & 0xffff) |0,\n s2 = ((adler >>> 16) & 0xffff) |0,\n n = 0;\n\n while (len !== 0) {\n // Set limit ~ twice less than 5552, to keep\n // s2 in 31-bits, because we force signed ints.\n // in other case %= will fail.\n n = len > 2000 ? 2000 : len;\n len -= n;\n\n do {\n s1 = (s1 + buf[pos++]) |0;\n s2 = (s2 + s1) |0;\n } while (--n);\n\n s1 %= 65521;\n s2 %= 65521;\n }\n\n return (s1 | (s2 << 16)) |0;\n};\n\n\nvar adler32_1 = adler32;\n\n// Note: we can't get significant speed boost here.\n// So write code to minimize size - no pregenerated tables\n// and array tools dependencies.\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// Use ordinary array, since untyped makes no boost here\nconst makeTable = () => {\n let 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.\nconst crcTable = new Uint32Array(makeTable());\n\n\nconst crc32 = (crc, buf, len, pos) => {\n const t = crcTable;\n const end = pos + len;\n\n crc ^= -1;\n\n for (let i = pos; i < end; i++) {\n crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];\n }\n\n return (crc ^ (-1)); // >>> 0;\n};\n\n\nvar crc32_1 = crc32;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar messages = {\n 2: 'need dictionary', /* Z_NEED_DICT 2 */\n 1: 'stream end', /* Z_STREAM_END 1 */\n 0: '', /* Z_OK 0 */\n '-1': 'file error', /* Z_ERRNO (-1) */\n '-2': 'stream error', /* Z_STREAM_ERROR (-2) */\n '-3': 'data error', /* Z_DATA_ERROR (-3) */\n '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */\n '-5': 'buffer error', /* Z_BUF_ERROR (-5) */\n '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nvar constants = {\n\n /* Allowed flush values; see deflate() and inflate() below for details */\n Z_NO_FLUSH: 0,\n Z_PARTIAL_FLUSH: 1,\n Z_SYNC_FLUSH: 2,\n Z_FULL_FLUSH: 3,\n Z_FINISH: 4,\n Z_BLOCK: 5,\n Z_TREES: 6,\n\n /* Return codes for the compression/decompression functions. Negative values\n * are errors, positive values are used for special but normal events.\n */\n Z_OK: 0,\n Z_STREAM_END: 1,\n Z_NEED_DICT: 2,\n Z_ERRNO: -1,\n Z_STREAM_ERROR: -2,\n Z_DATA_ERROR: -3,\n Z_MEM_ERROR: -4,\n Z_BUF_ERROR: -5,\n //Z_VERSION_ERROR: -6,\n\n /* compression levels */\n Z_NO_COMPRESSION: 0,\n Z_BEST_SPEED: 1,\n Z_BEST_COMPRESSION: 9,\n Z_DEFAULT_COMPRESSION: -1,\n\n\n Z_FILTERED: 1,\n Z_HUFFMAN_ONLY: 2,\n Z_RLE: 3,\n Z_FIXED: 4,\n Z_DEFAULT_STRATEGY: 0,\n\n /* Possible values of the data_type field (though see inflate()) */\n Z_BINARY: 0,\n Z_TEXT: 1,\n //Z_ASCII: 1, // = Z_TEXT (deprecated)\n Z_UNKNOWN: 2,\n\n /* The deflate compression method */\n Z_DEFLATED: 8\n //Z_NULL: null // Use -1 or null inline, depending on var type\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst { _tr_init: _tr_init$1, _tr_stored_block: _tr_stored_block$1, _tr_flush_block: _tr_flush_block$1, _tr_tally: _tr_tally$1, _tr_align: _tr_align$1 } = trees;\n\n\n\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_FULL_FLUSH, Z_FINISH, Z_BLOCK,\n Z_OK, Z_STREAM_END, Z_STREAM_ERROR, Z_DATA_ERROR, Z_BUF_ERROR,\n Z_DEFAULT_COMPRESSION,\n Z_FILTERED, Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED: Z_FIXED$1, Z_DEFAULT_STRATEGY,\n Z_UNKNOWN: Z_UNKNOWN$1,\n Z_DEFLATED\n} = constants;\n\n/*============================================================================*/\n\n\nconst MAX_MEM_LEVEL = 9;\n/* Maximum value for memLevel in deflateInit2 */\nconst MAX_WBITS = 15;\n/* 32K LZ77 window */\nconst DEF_MEM_LEVEL = 8;\n\n\nconst LENGTH_CODES$1 = 29;\n/* number of length codes, not counting the special END_BLOCK code */\nconst LITERALS$1 = 256;\n/* number of literal bytes 0..255 */\nconst L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1;\n/* number of Literal or Length codes, including the END_BLOCK code */\nconst D_CODES$1 = 30;\n/* number of distance codes */\nconst BL_CODES$1 = 19;\n/* number of codes used to transfer the bit lengths */\nconst HEAP_SIZE$1 = 2 * L_CODES$1 + 1;\n/* maximum heap size */\nconst MAX_BITS$1 = 15;\n/* All codes must not exceed MAX_BITS bits */\n\nconst MIN_MATCH$1 = 3;\nconst MAX_MATCH$1 = 258;\nconst MIN_LOOKAHEAD = (MAX_MATCH$1 + MIN_MATCH$1 + 1);\n\nconst PRESET_DICT = 0x20;\n\nconst INIT_STATE = 42;\nconst EXTRA_STATE = 69;\nconst NAME_STATE = 73;\nconst COMMENT_STATE = 91;\nconst HCRC_STATE = 103;\nconst BUSY_STATE = 113;\nconst FINISH_STATE = 666;\n\nconst BS_NEED_MORE = 1; /* block not completed, need more input or more output */\nconst BS_BLOCK_DONE = 2; /* block flush performed */\nconst BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */\nconst BS_FINISH_DONE = 4; /* finish done, accept no more input or output */\n\nconst OS_CODE = 0x03; // Unix :) . Don't detect, use this default.\n\nconst err = (strm, errorCode) => {\n strm.msg = messages[errorCode];\n return errorCode;\n};\n\nconst rank = (f) => {\n return ((f) << 1) - ((f) > 4 ? 9 : 0);\n};\n\nconst zero$1 = (buf) => {\n let len = buf.length; while (--len >= 0) { buf[len] = 0; }\n};\n\n\n/* eslint-disable new-cap */\nlet HASH_ZLIB = (s, prev, data) => ((prev << s.hash_shift) ^ data) & s.hash_mask;\n// This hash causes less collisions, https://github.com/nodeca/pako/issues/135\n// But breaks binary compatibility\n//let HASH_FAST = (s, prev, data) => ((prev << 8) + (prev >> 8) + (data << 4)) & s.hash_mask;\nlet HASH = HASH_ZLIB;\n\n/* =========================================================================\n * Flush as much pending output as possible. All deflate() output goes\n * through this function so some applications may wish to modify it\n * to avoid allocating a large strm->output buffer and copying into it.\n * (See also read_buf()).\n */\nconst flush_pending = (strm) => {\n const s = strm.state;\n\n //_tr_flush_bits(s);\n let len = s.pending;\n if (len > strm.avail_out) {\n len = strm.avail_out;\n }\n if (len === 0) { return; }\n\n strm.output.set(s.pending_buf.subarray(s.pending_out, s.pending_out + len), strm.next_out);\n strm.next_out += len;\n s.pending_out += len;\n strm.total_out += len;\n strm.avail_out -= len;\n s.pending -= len;\n if (s.pending === 0) {\n s.pending_out = 0;\n }\n};\n\n\nconst flush_block_only = (s, last) => {\n _tr_flush_block$1(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);\n s.block_start = s.strstart;\n flush_pending(s.strm);\n};\n\n\nconst put_byte = (s, b) => {\n s.pending_buf[s.pending++] = b;\n};\n\n\n/* =========================================================================\n * Put a short in the pending buffer. The 16-bit value is put in MSB order.\n * IN assertion: the stream state is correct and there is enough room in\n * pending_buf.\n */\nconst putShortMSB = (s, b) => {\n\n // put_byte(s, (Byte)(b >> 8));\n// put_byte(s, (Byte)(b & 0xff));\n s.pending_buf[s.pending++] = (b >>> 8) & 0xff;\n s.pending_buf[s.pending++] = b & 0xff;\n};\n\n\n/* ===========================================================================\n * Read a new buffer from the current input stream, update the adler32\n * and total number of bytes read. All deflate() input goes through\n * this function so some applications may wish to modify it to avoid\n * allocating a large strm->input buffer and copying from it.\n * (See also flush_pending()).\n */\nconst read_buf = (strm, buf, start, size) => {\n\n let len = strm.avail_in;\n\n if (len > size) { len = size; }\n if (len === 0) { return 0; }\n\n strm.avail_in -= len;\n\n // zmemcpy(buf, strm->next_in, len);\n buf.set(strm.input.subarray(strm.next_in, strm.next_in + len), start);\n if (strm.state.wrap === 1) {\n strm.adler = adler32_1(strm.adler, buf, len, start);\n }\n\n else if (strm.state.wrap === 2) {\n strm.adler = crc32_1(strm.adler, buf, len, start);\n }\n\n strm.next_in += len;\n strm.total_in += len;\n\n return len;\n};\n\n\n/* ===========================================================================\n * Set match_start to the longest match starting at the given string and\n * return its length. Matches shorter or equal to prev_length are discarded,\n * in which case the result is equal to prev_length and match_start is\n * garbage.\n * IN assertions: cur_match is the head of the hash chain for the current\n * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1\n * OUT assertion: the match length is not greater than s->lookahead.\n */\nconst longest_match = (s, cur_match) => {\n\n let chain_length = s.max_chain_length; /* max hash chain length */\n let scan = s.strstart; /* current string */\n let match; /* matched string */\n let len; /* length of current match */\n let best_len = s.prev_length; /* best match length so far */\n let nice_match = s.nice_match; /* stop if match long enough */\n const limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?\n s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;\n\n const _win = s.window; // shortcut\n\n const wmask = s.w_mask;\n const prev = s.prev;\n\n /* Stop when cur_match becomes <= limit. To simplify the code,\n * we prevent matches with the string of window index 0.\n */\n\n const strend = s.strstart + MAX_MATCH$1;\n let scan_end1 = _win[scan + best_len - 1];\n let scan_end = _win[scan + best_len];\n\n /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.\n * It is easy to get rid of this optimization if necessary.\n */\n // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, \"Code too clever\");\n\n /* Do not waste too much time if we already have a good match: */\n if (s.prev_length >= s.good_match) {\n chain_length >>= 2;\n }\n /* Do not look for matches beyond the end of the input. This is necessary\n * to make deflate deterministic.\n */\n if (nice_match > s.lookahead) { nice_match = s.lookahead; }\n\n // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, \"need lookahead\");\n\n do {\n // Assert(cur_match < s->strstart, \"no future\");\n match = cur_match;\n\n /* Skip to next match if the match length cannot increase\n * or if the match length is less than 2. Note that the checks below\n * for insufficient lookahead only occur occasionally for performance\n * reasons. Therefore uninitialized memory will be accessed, and\n * conditional jumps will be made that depend on those values.\n * However the length of the match is limited to the lookahead, so\n * the output of deflate is not affected by the uninitialized values.\n */\n\n if (_win[match + best_len] !== scan_end ||\n _win[match + best_len - 1] !== scan_end1 ||\n _win[match] !== _win[scan] ||\n _win[++match] !== _win[scan + 1]) {\n continue;\n }\n\n /* The check at best_len-1 can be removed because it will be made\n * again later. (This heuristic is not always a win.)\n * It is not necessary to compare scan[2] and match[2] since they\n * are always equal when the other bytes match, given that\n * the hash keys are equal and that HASH_BITS >= 8.\n */\n scan += 2;\n match++;\n // Assert(*scan == *match, \"match[2]?\");\n\n /* We check for insufficient lookahead only every 8th comparison;\n * the 256th check will be made at strstart+258.\n */\n do {\n /*jshint noempty:false*/\n } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&\n scan < strend);\n\n // Assert(scan <= s->window+(unsigned)(s->window_size-1), \"wild scan\");\n\n len = MAX_MATCH$1 - (strend - scan);\n scan = strend - MAX_MATCH$1;\n\n if (len > best_len) {\n s.match_start = cur_match;\n best_len = len;\n if (len >= nice_match) {\n break;\n }\n scan_end1 = _win[scan + best_len - 1];\n scan_end = _win[scan + best_len];\n }\n } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);\n\n if (best_len <= s.lookahead) {\n return best_len;\n }\n return s.lookahead;\n};\n\n\n/* ===========================================================================\n * Fill the window when the lookahead becomes insufficient.\n * Updates strstart and lookahead.\n *\n * IN assertion: lookahead < MIN_LOOKAHEAD\n * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD\n * At least one byte has been read, or avail_in == 0; reads are\n * performed for at least two bytes (required for the zip translate_eol\n * option -- not supported here).\n */\nconst fill_window = (s) => {\n\n const _w_size = s.w_size;\n let p, n, m, more, str;\n\n //Assert(s->lookahead < MIN_LOOKAHEAD, \"already enough lookahead\");\n\n do {\n more = s.window_size - s.lookahead - s.strstart;\n\n // JS ints have 32 bit, block below not needed\n /* Deal with !@#$% 64K limit: */\n //if (sizeof(int) <= 2) {\n // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {\n // more = wsize;\n //\n // } else if (more == (unsigned)(-1)) {\n // /* Very unlikely, but possible on 16 bit machine if\n // * strstart == 0 && lookahead == 1 (input done a byte at time)\n // */\n // more--;\n // }\n //}\n\n\n /* If the window is almost full and there is insufficient lookahead,\n * move the upper half to the lower one to make room in the upper half.\n */\n if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {\n\n s.window.set(s.window.subarray(_w_size, _w_size + _w_size), 0);\n s.match_start -= _w_size;\n s.strstart -= _w_size;\n /* we now have strstart >= MAX_DIST */\n s.block_start -= _w_size;\n\n /* Slide the hash table (could be avoided with 32 bit values\n at the expense of memory usage). We slide even when level == 0\n to keep the hash table consistent if we switch back to level > 0\n later. (Using level 0 permanently is not an optimal usage of\n zlib, so we don't care about this pathological case.)\n */\n\n n = s.hash_size;\n p = n;\n\n do {\n m = s.head[--p];\n s.head[p] = (m >= _w_size ? m - _w_size : 0);\n } while (--n);\n\n n = _w_size;\n p = n;\n\n do {\n m = s.prev[--p];\n s.prev[p] = (m >= _w_size ? m - _w_size : 0);\n /* If n is not on any hash chain, prev[n] is garbage but\n * its value will never be used.\n */\n } while (--n);\n\n more += _w_size;\n }\n if (s.strm.avail_in === 0) {\n break;\n }\n\n /* If there was no sliding:\n * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&\n * more == window_size - lookahead - strstart\n * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)\n * => more >= window_size - 2*WSIZE + 2\n * In the BIG_MEM or MMAP case (not yet supported),\n * window_size == input_size + MIN_LOOKAHEAD &&\n * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.\n * Otherwise, window_size == 2*WSIZE so more >= 2.\n * If there was sliding, more >= WSIZE. So in all cases, more >= 2.\n */\n //Assert(more >= 2, \"more < 2\");\n n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);\n s.lookahead += n;\n\n /* Initialize the hash value now that we have some input: */\n if (s.lookahead + s.insert >= MIN_MATCH$1) {\n str = s.strstart - s.insert;\n s.ins_h = s.window[str];\n\n /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + 1]);\n//#if MIN_MATCH != 3\n// Call update_hash() MIN_MATCH-3 more times\n//#endif\n while (s.insert) {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH$1 - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = str;\n str++;\n s.insert--;\n if (s.lookahead + s.insert < MIN_MATCH$1) {\n break;\n }\n }\n }\n /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,\n * but this is not important since only literal bytes will be emitted.\n */\n\n } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);\n\n /* If the WIN_INIT bytes after the end of the current data have never been\n * written, then zero those bytes in order to avoid memory check reports of\n * the use of uninitialized (or uninitialised as Julian writes) bytes by\n * the longest match routines. Update the high water mark for the next\n * time through here. WIN_INIT is set to MAX_MATCH since the longest match\n * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.\n */\n// if (s.high_water < s.window_size) {\n// const curr = s.strstart + s.lookahead;\n// let init = 0;\n//\n// if (s.high_water < curr) {\n// /* Previous high water mark below current data -- zero WIN_INIT\n// * bytes or up to end of window, whichever is less.\n// */\n// init = s.window_size - curr;\n// if (init > WIN_INIT)\n// init = WIN_INIT;\n// zmemzero(s->window + curr, (unsigned)init);\n// s->high_water = curr + init;\n// }\n// else if (s->high_water < (ulg)curr + WIN_INIT) {\n// /* High water mark at or above current data, but below current data\n// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up\n// * to end of window, whichever is less.\n// */\n// init = (ulg)curr + WIN_INIT - s->high_water;\n// if (init > s->window_size - s->high_water)\n// init = s->window_size - s->high_water;\n// zmemzero(s->window + s->high_water, (unsigned)init);\n// s->high_water += init;\n// }\n// }\n//\n// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,\n// \"not enough room for search\");\n};\n\n/* ===========================================================================\n * Copy without compression as much as possible from the input stream, return\n * the current block state.\n * This function does not insert new strings in the dictionary since\n * uncompressible data is probably not useful. This function is used\n * only for the level=0 compression option.\n * NOTE: this function should be optimized to avoid extra copying from\n * window to pending_buf.\n */\nconst deflate_stored = (s, flush) => {\n\n /* Stored blocks are limited to 0xffff bytes, pending_buf is limited\n * to pending_buf_size, and each stored block has a 5 byte header:\n */\n let max_block_size = 0xffff;\n\n if (max_block_size > s.pending_buf_size - 5) {\n max_block_size = s.pending_buf_size - 5;\n }\n\n /* Copy as much as possible from input to output: */\n for (;;) {\n /* Fill the window as much as possible: */\n if (s.lookahead <= 1) {\n\n //Assert(s->strstart < s->w_size+MAX_DIST(s) ||\n // s->block_start >= (long)s->w_size, \"slide too late\");\n// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||\n// s.block_start >= s.w_size)) {\n// throw new Error(\"slide too late\");\n// }\n\n fill_window(s);\n if (s.lookahead === 0 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n\n if (s.lookahead === 0) {\n break;\n }\n /* flush the current block */\n }\n //Assert(s->block_start >= 0L, \"block gone\");\n// if (s.block_start < 0) throw new Error(\"block gone\");\n\n s.strstart += s.lookahead;\n s.lookahead = 0;\n\n /* Emit a stored block if pending_buf will be full: */\n const max_start = s.block_start + max_block_size;\n\n if (s.strstart === 0 || s.strstart >= max_start) {\n /* strstart == 0 is possible when wraparound on 16-bit machine */\n s.lookahead = s.strstart - max_start;\n s.strstart = max_start;\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n\n\n }\n /* Flush if we may have to slide, otherwise block_start may become\n * negative and the data will be gone:\n */\n if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n\n s.insert = 0;\n\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n\n if (s.strstart > s.block_start) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_NEED_MORE;\n};\n\n/* ===========================================================================\n * Compress as much as possible from the input stream, return the current\n * block state.\n * This function does not perform lazy evaluation of matches and inserts\n * new strings in the dictionary only for unmatched strings or for short\n * matches. It is used only for the fast compression options.\n */\nconst deflate_fast = (s, flush) => {\n\n let hash_head; /* head of the hash chain */\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) {\n break; /* flush the current block */\n }\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH$1) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n * At this point we have always match_length < MIN_MATCH\n */\n if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n }\n if (s.match_length >= MIN_MATCH$1) {\n // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only\n\n /*** _tr_tally_dist(s, s.strstart - s.match_start,\n s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally$1(s, s.strstart - s.match_start, s.match_length - MIN_MATCH$1);\n\n s.lookahead -= s.match_length;\n\n /* Insert new strings in the hash table only if the match length\n * is not too large. This saves time but degrades compression.\n */\n if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH$1) {\n s.match_length--; /* string at strstart already in table */\n do {\n s.strstart++;\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n /* strstart never exceeds WSIZE-MAX_MATCH, so there are\n * always MIN_MATCH bytes ahead.\n */\n } while (--s.match_length !== 0);\n s.strstart++;\n } else\n {\n s.strstart += s.match_length;\n s.match_length = 0;\n s.ins_h = s.window[s.strstart];\n /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + 1]);\n\n//#if MIN_MATCH != 3\n// Call UPDATE_HASH() MIN_MATCH-3 more times\n//#endif\n /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not\n * matter since it will be recomputed at next deflate call.\n */\n }\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s.window[s.strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = ((s.strstart < (MIN_MATCH$1 - 1)) ? s.strstart : MIN_MATCH$1 - 1);\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * Same as above, but achieves better compression. We use a lazy\n * evaluation for matches: a match is finally adopted only if there is\n * no better match at the next window position.\n */\nconst deflate_slow = (s, flush) => {\n\n let hash_head; /* head of hash chain */\n let bflush; /* set if current block must be flushed */\n\n let max_insert;\n\n /* Process the input block. */\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the next match, plus MIN_MATCH bytes to insert the\n * string following the next match.\n */\n if (s.lookahead < MIN_LOOKAHEAD) {\n fill_window(s);\n if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* Insert the string window[strstart .. strstart+2] in the\n * dictionary, and set hash_head to the head of the hash chain:\n */\n hash_head = 0/*NIL*/;\n if (s.lookahead >= MIN_MATCH$1) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n\n /* Find the longest match, discarding those <= prev_length.\n */\n s.prev_length = s.match_length;\n s.prev_match = s.match_start;\n s.match_length = MIN_MATCH$1 - 1;\n\n if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&\n s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {\n /* To simplify the code, we prevent matches with the string\n * of window index 0 (in particular we have to avoid a match\n * of the string with itself at the start of the input file).\n */\n s.match_length = longest_match(s, hash_head);\n /* longest_match() sets match_start */\n\n if (s.match_length <= 5 &&\n (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH$1 && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {\n\n /* If prev_match is also MIN_MATCH, match_start is garbage\n * but we will ignore the current match anyway.\n */\n s.match_length = MIN_MATCH$1 - 1;\n }\n }\n /* If there was a match at the previous step and the current\n * match is not better, output the previous match:\n */\n if (s.prev_length >= MIN_MATCH$1 && s.match_length <= s.prev_length) {\n max_insert = s.strstart + s.lookahead - MIN_MATCH$1;\n /* Do not insert strings in hash table beyond this. */\n\n //check_match(s, s.strstart-1, s.prev_match, s.prev_length);\n\n /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,\n s.prev_length - MIN_MATCH, bflush);***/\n bflush = _tr_tally$1(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH$1);\n /* Insert in hash table all strings up to the end of the match.\n * strstart-1 and strstart are already inserted. If there is not\n * enough lookahead, the last two strings are not inserted in\n * the hash table.\n */\n s.lookahead -= s.prev_length - 1;\n s.prev_length -= 2;\n do {\n if (++s.strstart <= max_insert) {\n /*** INSERT_STRING(s, s.strstart, hash_head); ***/\n s.ins_h = HASH(s, s.ins_h, s.window[s.strstart + MIN_MATCH$1 - 1]);\n hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];\n s.head[s.ins_h] = s.strstart;\n /***/\n }\n } while (--s.prev_length !== 0);\n s.match_available = 0;\n s.match_length = MIN_MATCH$1 - 1;\n s.strstart++;\n\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n } else if (s.match_available) {\n /* If there was no match at the previous position, output a\n * single literal. If there was a match but the current match\n * is longer, truncate the previous match to a single literal.\n */\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart - 1]);\n\n if (bflush) {\n /*** FLUSH_BLOCK_ONLY(s, 0) ***/\n flush_block_only(s, false);\n /***/\n }\n s.strstart++;\n s.lookahead--;\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n } else {\n /* There is no previous match to compare with, wait for\n * the next step to decide.\n */\n s.match_available = 1;\n s.strstart++;\n s.lookahead--;\n }\n }\n //Assert (flush != Z_NO_FLUSH, \"no flush?\");\n if (s.match_available) {\n //Tracevv((stderr,\"%c\", s->window[s->strstart-1]));\n /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart - 1]);\n\n s.match_available = 0;\n }\n s.insert = s.strstart < MIN_MATCH$1 - 1 ? s.strstart : MIN_MATCH$1 - 1;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n\n return BS_BLOCK_DONE;\n};\n\n\n/* ===========================================================================\n * For Z_RLE, simply look for runs of bytes, generate matches only of distance\n * one. Do not maintain a hash table. (It will be regenerated if this run of\n * deflate switches away from Z_RLE.)\n */\nconst deflate_rle = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n let prev; /* byte at distance one to match */\n let scan, strend; /* scan goes up to strend for length of run */\n\n const _win = s.window;\n\n for (;;) {\n /* Make sure that we always have enough lookahead, except\n * at the end of the input file. We need MAX_MATCH bytes\n * for the longest run, plus one for the unrolled loop.\n */\n if (s.lookahead <= MAX_MATCH$1) {\n fill_window(s);\n if (s.lookahead <= MAX_MATCH$1 && flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n if (s.lookahead === 0) { break; } /* flush the current block */\n }\n\n /* See how many times the previous byte repeats */\n s.match_length = 0;\n if (s.lookahead >= MIN_MATCH$1 && s.strstart > 0) {\n scan = s.strstart - 1;\n prev = _win[scan];\n if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {\n strend = s.strstart + MAX_MATCH$1;\n do {\n /*jshint noempty:false*/\n } while (prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n prev === _win[++scan] && prev === _win[++scan] &&\n scan < strend);\n s.match_length = MAX_MATCH$1 - (strend - scan);\n if (s.match_length > s.lookahead) {\n s.match_length = s.lookahead;\n }\n }\n //Assert(scan <= s->window+(uInt)(s->window_size-1), \"wild scan\");\n }\n\n /* Emit match if have run of MIN_MATCH or longer, else emit literal */\n if (s.match_length >= MIN_MATCH$1) {\n //check_match(s, s.strstart, s.strstart - 1, s.match_length);\n\n /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/\n bflush = _tr_tally$1(s, 1, s.match_length - MIN_MATCH$1);\n\n s.lookahead -= s.match_length;\n s.strstart += s.match_length;\n s.match_length = 0;\n } else {\n /* No match, output a literal byte */\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n\n s.lookahead--;\n s.strstart++;\n }\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* ===========================================================================\n * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.\n * (It will be regenerated if this run of deflate switches away from Huffman.)\n */\nconst deflate_huff = (s, flush) => {\n\n let bflush; /* set if current block must be flushed */\n\n for (;;) {\n /* Make sure that we have a literal to write. */\n if (s.lookahead === 0) {\n fill_window(s);\n if (s.lookahead === 0) {\n if (flush === Z_NO_FLUSH) {\n return BS_NEED_MORE;\n }\n break; /* flush the current block */\n }\n }\n\n /* Output a literal byte */\n s.match_length = 0;\n //Tracevv((stderr,\"%c\", s->window[s->strstart]));\n /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/\n bflush = _tr_tally$1(s, 0, s.window[s.strstart]);\n s.lookahead--;\n s.strstart++;\n if (bflush) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n }\n s.insert = 0;\n if (flush === Z_FINISH) {\n /*** FLUSH_BLOCK(s, 1); ***/\n flush_block_only(s, true);\n if (s.strm.avail_out === 0) {\n return BS_FINISH_STARTED;\n }\n /***/\n return BS_FINISH_DONE;\n }\n if (s.last_lit) {\n /*** FLUSH_BLOCK(s, 0); ***/\n flush_block_only(s, false);\n if (s.strm.avail_out === 0) {\n return BS_NEED_MORE;\n }\n /***/\n }\n return BS_BLOCK_DONE;\n};\n\n/* Values for max_lazy_match, good_match and max_chain_length, depending on\n * the desired pack level (0..9). The values given below have been tuned to\n * exclude worst case performance for pathological files. Better values may be\n * found for specific files.\n */\nfunction Config(good_length, max_lazy, nice_length, max_chain, func) {\n\n this.good_length = good_length;\n this.max_lazy = max_lazy;\n this.nice_length = nice_length;\n this.max_chain = max_chain;\n this.func = func;\n}\n\nconst configuration_table = [\n /* good lazy nice chain */\n new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */\n new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */\n new Config(4, 5, 16, 8, deflate_fast), /* 2 */\n new Config(4, 6, 32, 32, deflate_fast), /* 3 */\n\n new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */\n new Config(8, 16, 32, 32, deflate_slow), /* 5 */\n new Config(8, 16, 128, 128, deflate_slow), /* 6 */\n new Config(8, 32, 128, 256, deflate_slow), /* 7 */\n new Config(32, 128, 258, 1024, deflate_slow), /* 8 */\n new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */\n];\n\n\n/* ===========================================================================\n * Initialize the \"longest match\" routines for a new zlib stream\n */\nconst lm_init = (s) => {\n\n s.window_size = 2 * s.w_size;\n\n /*** CLEAR_HASH(s); ***/\n zero$1(s.head); // Fill with NIL (= 0);\n\n /* Set the default configuration parameters:\n */\n s.max_lazy_match = configuration_table[s.level].max_lazy;\n s.good_match = configuration_table[s.level].good_length;\n s.nice_match = configuration_table[s.level].nice_length;\n s.max_chain_length = configuration_table[s.level].max_chain;\n\n s.strstart = 0;\n s.block_start = 0;\n s.lookahead = 0;\n s.insert = 0;\n s.match_length = s.prev_length = MIN_MATCH$1 - 1;\n s.match_available = 0;\n s.ins_h = 0;\n};\n\n\nfunction DeflateState() {\n this.strm = null; /* pointer back to this zlib stream */\n this.status = 0; /* as the name implies */\n this.pending_buf = null; /* output still pending */\n this.pending_buf_size = 0; /* size of pending_buf */\n this.pending_out = 0; /* next pending byte to output to the stream */\n this.pending = 0; /* nb of bytes in the pending buffer */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.gzhead = null; /* gzip header information to write */\n this.gzindex = 0; /* where in extra, name, or comment */\n this.method = Z_DEFLATED; /* can only be DEFLATED */\n this.last_flush = -1; /* value of flush param for previous deflate call */\n\n this.w_size = 0; /* LZ77 window size (32K by default) */\n this.w_bits = 0; /* log2(w_size) (8..16) */\n this.w_mask = 0; /* w_size - 1 */\n\n this.window = null;\n /* Sliding window. Input bytes are read into the second half of the window,\n * and move to the first half later to keep a dictionary of at least wSize\n * bytes. With this organization, matches are limited to a distance of\n * wSize-MAX_MATCH bytes, but this ensures that IO is always\n * performed with a length multiple of the block size.\n */\n\n this.window_size = 0;\n /* Actual size of window: 2*wSize, except when the user input buffer\n * is directly used as sliding window.\n */\n\n this.prev = null;\n /* Link to older string with same hash index. To limit the size of this\n * array to 64K, this link is maintained only for the last 32K strings.\n * An index in this array is thus a window index modulo 32K.\n */\n\n this.head = null; /* Heads of the hash chains or NIL. */\n\n this.ins_h = 0; /* hash index of string to be inserted */\n this.hash_size = 0; /* number of elements in hash table */\n this.hash_bits = 0; /* log2(hash_size) */\n this.hash_mask = 0; /* hash_size-1 */\n\n this.hash_shift = 0;\n /* Number of bits by which ins_h must be shifted at each input\n * step. It must be such that after MIN_MATCH steps, the oldest\n * byte no longer takes part in the hash key, that is:\n * hash_shift * MIN_MATCH >= hash_bits\n */\n\n this.block_start = 0;\n /* Window position at the beginning of the current output block. Gets\n * negative when the window is moved backwards.\n */\n\n this.match_length = 0; /* length of best match */\n this.prev_match = 0; /* previous match */\n this.match_available = 0; /* set if previous match exists */\n this.strstart = 0; /* start of string to insert */\n this.match_start = 0; /* start of matching string */\n this.lookahead = 0; /* number of valid bytes ahead in window */\n\n this.prev_length = 0;\n /* Length of the best match at previous step. Matches not greater than this\n * are discarded. This is used in the lazy match evaluation.\n */\n\n this.max_chain_length = 0;\n /* To speed up deflation, hash chains are never searched beyond this\n * length. A higher limit improves compression ratio but degrades the\n * speed.\n */\n\n this.max_lazy_match = 0;\n /* Attempt to find a better match only when the current match is strictly\n * smaller than this value. This mechanism is used only for compression\n * levels >= 4.\n */\n // That's alias to max_lazy_match, don't use directly\n //this.max_insert_length = 0;\n /* Insert new strings in the hash table only if the match length is not\n * greater than this length. This saves time but degrades compression.\n * max_insert_length is used only for compression levels <= 3.\n */\n\n this.level = 0; /* compression level (1..9) */\n this.strategy = 0; /* favor or force Huffman coding*/\n\n this.good_match = 0;\n /* Use a faster search when the previous match is longer than this */\n\n this.nice_match = 0; /* Stop searching when current match exceeds this */\n\n /* used by trees.c: */\n\n /* Didn't use ct_data typedef below to suppress compiler warning */\n\n // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */\n // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */\n // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */\n\n // Use flat array of DOUBLE size, with interleaved fata,\n // because JS does not support effective\n this.dyn_ltree = new Uint16Array(HEAP_SIZE$1 * 2);\n this.dyn_dtree = new Uint16Array((2 * D_CODES$1 + 1) * 2);\n this.bl_tree = new Uint16Array((2 * BL_CODES$1 + 1) * 2);\n zero$1(this.dyn_ltree);\n zero$1(this.dyn_dtree);\n zero$1(this.bl_tree);\n\n this.l_desc = null; /* desc. for literal tree */\n this.d_desc = null; /* desc. for distance tree */\n this.bl_desc = null; /* desc. for bit length tree */\n\n //ush bl_count[MAX_BITS+1];\n this.bl_count = new Uint16Array(MAX_BITS$1 + 1);\n /* number of codes at each bit length for an optimal tree */\n\n //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */\n this.heap = new Uint16Array(2 * L_CODES$1 + 1); /* heap used to build the Huffman trees */\n zero$1(this.heap);\n\n this.heap_len = 0; /* number of elements in the heap */\n this.heap_max = 0; /* element of largest frequency */\n /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.\n * The same heap array is used to build all trees.\n */\n\n this.depth = new Uint16Array(2 * L_CODES$1 + 1); //uch depth[2*L_CODES+1];\n zero$1(this.depth);\n /* Depth of each subtree used as tie breaker for trees of equal frequency\n */\n\n this.l_buf = 0; /* buffer index for literals or lengths */\n\n this.lit_bufsize = 0;\n /* Size of match buffer for literals/lengths. There are 4 reasons for\n * limiting lit_bufsize to 64K:\n * - frequencies can be kept in 16 bit counters\n * - if compression is not successful for the first block, all input\n * data is still in the window so we can still emit a stored block even\n * when input comes from standard input. (This can also be done for\n * all blocks if lit_bufsize is not greater than 32K.)\n * - if compression is not successful for a file smaller than 64K, we can\n * even emit a stored file instead of a stored block (saving 5 bytes).\n * This is applicable only for zip (not gzip or zlib).\n * - creating new Huffman trees less frequently may not provide fast\n * adaptation to changes in the input data statistics. (Take for\n * example a binary file with poorly compressible code followed by\n * a highly compressible string table.) Smaller buffer sizes give\n * fast adaptation but have of course the overhead of transmitting\n * trees more frequently.\n * - I can't count above 4\n */\n\n this.last_lit = 0; /* running index in l_buf */\n\n this.d_buf = 0;\n /* Buffer index for distances. To simplify the code, d_buf and l_buf have\n * the same number of elements. To use different lengths, an extra flag\n * array would be necessary.\n */\n\n this.opt_len = 0; /* bit length of current block with optimal trees */\n this.static_len = 0; /* bit length of current block with static trees */\n this.matches = 0; /* number of string matches in current block */\n this.insert = 0; /* bytes at end of window left to insert */\n\n\n this.bi_buf = 0;\n /* Output buffer. bits are inserted starting at the bottom (least\n * significant bits).\n */\n this.bi_valid = 0;\n /* Number of valid bits in bi_buf. All bits above the last valid bit\n * are always zero.\n */\n\n // Used for window memory init. We safely ignore it for JS. That makes\n // sense only for pointers and memory check tools.\n //this.high_water = 0;\n /* High water mark offset in window for initialized bytes -- bytes above\n * this are set to zero in order to avoid memory check warnings when\n * longest match routines access bytes past the input. This is then\n * updated to the new high water mark.\n */\n}\n\n\nconst deflateResetKeep = (strm) => {\n\n if (!strm || !strm.state) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.total_in = strm.total_out = 0;\n strm.data_type = Z_UNKNOWN$1;\n\n const s = strm.state;\n s.pending = 0;\n s.pending_out = 0;\n\n if (s.wrap < 0) {\n s.wrap = -s.wrap;\n /* was made negative by deflate(..., Z_FINISH); */\n }\n s.status = (s.wrap ? INIT_STATE : BUSY_STATE);\n strm.adler = (s.wrap === 2) ?\n 0 // crc32(0, Z_NULL, 0)\n :\n 1; // adler32(0, Z_NULL, 0)\n s.last_flush = Z_NO_FLUSH;\n _tr_init$1(s);\n return Z_OK;\n};\n\n\nconst deflateReset = (strm) => {\n\n const ret = deflateResetKeep(strm);\n if (ret === Z_OK) {\n lm_init(strm.state);\n }\n return ret;\n};\n\n\nconst deflateSetHeader = (strm, head) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR; }\n if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }\n strm.state.gzhead = head;\n return Z_OK;\n};\n\n\nconst deflateInit2 = (strm, level, method, windowBits, memLevel, strategy) => {\n\n if (!strm) { // === Z_NULL\n return Z_STREAM_ERROR;\n }\n let wrap = 1;\n\n if (level === Z_DEFAULT_COMPRESSION) {\n level = 6;\n }\n\n if (windowBits < 0) { /* suppress zlib wrapper */\n wrap = 0;\n windowBits = -windowBits;\n }\n\n else if (windowBits > 15) {\n wrap = 2; /* write gzip wrapper instead */\n windowBits -= 16;\n }\n\n\n if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||\n windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||\n strategy < 0 || strategy > Z_FIXED$1) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n\n if (windowBits === 8) {\n windowBits = 9;\n }\n /* until 256-byte window bug fixed */\n\n const s = new DeflateState();\n\n strm.state = s;\n s.strm = strm;\n\n s.wrap = wrap;\n s.gzhead = null;\n s.w_bits = windowBits;\n s.w_size = 1 << s.w_bits;\n s.w_mask = s.w_size - 1;\n\n s.hash_bits = memLevel + 7;\n s.hash_size = 1 << s.hash_bits;\n s.hash_mask = s.hash_size - 1;\n s.hash_shift = ~~((s.hash_bits + MIN_MATCH$1 - 1) / MIN_MATCH$1);\n\n s.window = new Uint8Array(s.w_size * 2);\n s.head = new Uint16Array(s.hash_size);\n s.prev = new Uint16Array(s.w_size);\n\n // Don't need mem init magic for JS.\n //s.high_water = 0; /* nothing written to s->window yet */\n\n s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */\n\n s.pending_buf_size = s.lit_bufsize * 4;\n\n //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);\n //s->pending_buf = (uchf *) overlay;\n s.pending_buf = new Uint8Array(s.pending_buf_size);\n\n // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`)\n //s->d_buf = overlay + s->lit_bufsize/sizeof(ush);\n s.d_buf = 1 * s.lit_bufsize;\n\n //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;\n s.l_buf = (1 + 2) * s.lit_bufsize;\n\n s.level = level;\n s.strategy = strategy;\n s.method = method;\n\n return deflateReset(strm);\n};\n\nconst deflateInit = (strm, level) => {\n\n return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);\n};\n\n\nconst deflate = (strm, flush) => {\n\n let beg, val; // for gzip header write only\n\n if (!strm || !strm.state ||\n flush > Z_BLOCK || flush < 0) {\n return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;\n }\n\n const s = strm.state;\n\n if (!strm.output ||\n (!strm.input && strm.avail_in !== 0) ||\n (s.status === FINISH_STATE && flush !== Z_FINISH)) {\n return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);\n }\n\n s.strm = strm; /* just in case */\n const old_flush = s.last_flush;\n s.last_flush = flush;\n\n /* Write the header */\n if (s.status === INIT_STATE) {\n\n if (s.wrap === 2) { // GZIP header\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n put_byte(s, 31);\n put_byte(s, 139);\n put_byte(s, 8);\n if (!s.gzhead) { // s->gzhead == Z_NULL\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, 0);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, OS_CODE);\n s.status = BUSY_STATE;\n }\n else {\n put_byte(s, (s.gzhead.text ? 1 : 0) +\n (s.gzhead.hcrc ? 2 : 0) +\n (!s.gzhead.extra ? 0 : 4) +\n (!s.gzhead.name ? 0 : 8) +\n (!s.gzhead.comment ? 0 : 16)\n );\n put_byte(s, s.gzhead.time & 0xff);\n put_byte(s, (s.gzhead.time >> 8) & 0xff);\n put_byte(s, (s.gzhead.time >> 16) & 0xff);\n put_byte(s, (s.gzhead.time >> 24) & 0xff);\n put_byte(s, s.level === 9 ? 2 :\n (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?\n 4 : 0));\n put_byte(s, s.gzhead.os & 0xff);\n if (s.gzhead.extra && s.gzhead.extra.length) {\n put_byte(s, s.gzhead.extra.length & 0xff);\n put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);\n }\n if (s.gzhead.hcrc) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending, 0);\n }\n s.gzindex = 0;\n s.status = EXTRA_STATE;\n }\n }\n else // DEFLATE header\n {\n let header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;\n let level_flags = -1;\n\n if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {\n level_flags = 0;\n } else if (s.level < 6) {\n level_flags = 1;\n } else if (s.level === 6) {\n level_flags = 2;\n } else {\n level_flags = 3;\n }\n header |= (level_flags << 6);\n if (s.strstart !== 0) { header |= PRESET_DICT; }\n header += 31 - (header % 31);\n\n s.status = BUSY_STATE;\n putShortMSB(s, header);\n\n /* Save the adler32 of the preset dictionary: */\n if (s.strstart !== 0) {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n strm.adler = 1; // adler32(0L, Z_NULL, 0);\n }\n }\n\n//#ifdef GZIP\n if (s.status === EXTRA_STATE) {\n if (s.gzhead.extra/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n\n while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n break;\n }\n }\n put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);\n s.gzindex++;\n }\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (s.gzindex === s.gzhead.extra.length) {\n s.gzindex = 0;\n s.status = NAME_STATE;\n }\n }\n else {\n s.status = NAME_STATE;\n }\n }\n if (s.status === NAME_STATE) {\n if (s.gzhead.name/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.name.length) {\n val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.gzindex = 0;\n s.status = COMMENT_STATE;\n }\n }\n else {\n s.status = COMMENT_STATE;\n }\n }\n if (s.status === COMMENT_STATE) {\n if (s.gzhead.comment/* != Z_NULL*/) {\n beg = s.pending; /* start of bytes to update crc */\n //int val;\n\n do {\n if (s.pending === s.pending_buf_size) {\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n flush_pending(strm);\n beg = s.pending;\n if (s.pending === s.pending_buf_size) {\n val = 1;\n break;\n }\n }\n // JS specific: little magic to add zero terminator to end of string\n if (s.gzindex < s.gzhead.comment.length) {\n val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;\n } else {\n val = 0;\n }\n put_byte(s, val);\n } while (val !== 0);\n\n if (s.gzhead.hcrc && s.pending > beg) {\n strm.adler = crc32_1(strm.adler, s.pending_buf, s.pending - beg, beg);\n }\n if (val === 0) {\n s.status = HCRC_STATE;\n }\n }\n else {\n s.status = HCRC_STATE;\n }\n }\n if (s.status === HCRC_STATE) {\n if (s.gzhead.hcrc) {\n if (s.pending + 2 > s.pending_buf_size) {\n flush_pending(strm);\n }\n if (s.pending + 2 <= s.pending_buf_size) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n strm.adler = 0; //crc32(0L, Z_NULL, 0);\n s.status = BUSY_STATE;\n }\n }\n else {\n s.status = BUSY_STATE;\n }\n }\n//#endif\n\n /* Flush as much pending output as possible */\n if (s.pending !== 0) {\n flush_pending(strm);\n if (strm.avail_out === 0) {\n /* Since avail_out is 0, deflate will be called again with\n * more output space, but possibly with both pending and\n * avail_in equal to zero. There won't be anything to do,\n * but this is not an error situation so make sure we\n * return OK instead of BUF_ERROR at next call of deflate:\n */\n s.last_flush = -1;\n return Z_OK;\n }\n\n /* Make sure there is something to do and avoid duplicate consecutive\n * flushes. For repeated and useless calls with Z_FINISH, we keep\n * returning Z_STREAM_END instead of Z_BUF_ERROR.\n */\n } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&\n flush !== Z_FINISH) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* User must not provide more input after the first FINISH: */\n if (s.status === FINISH_STATE && strm.avail_in !== 0) {\n return err(strm, Z_BUF_ERROR);\n }\n\n /* Start a new block or continue the current one.\n */\n if (strm.avail_in !== 0 || s.lookahead !== 0 ||\n (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {\n let bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :\n (s.strategy === Z_RLE ? deflate_rle(s, flush) :\n configuration_table[s.level].func(s, flush));\n\n if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {\n s.status = FINISH_STATE;\n }\n if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {\n if (strm.avail_out === 0) {\n s.last_flush = -1;\n /* avoid BUF_ERROR next call, see above */\n }\n return Z_OK;\n /* If flush != Z_NO_FLUSH && avail_out == 0, the next call\n * of deflate should use the same flush parameter to make sure\n * that the flush is complete. So we don't have to output an\n * empty block here, this will be done at next call. This also\n * ensures that for a very small output buffer, we emit at most\n * one empty block.\n */\n }\n if (bstate === BS_BLOCK_DONE) {\n if (flush === Z_PARTIAL_FLUSH) {\n _tr_align$1(s);\n }\n else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */\n\n _tr_stored_block$1(s, 0, 0, false);\n /* For a full flush, this empty block will be recognized\n * as a special marker by inflate_sync().\n */\n if (flush === Z_FULL_FLUSH) {\n /*** CLEAR_HASH(s); ***/ /* forget history */\n zero$1(s.head); // Fill with NIL (= 0);\n\n if (s.lookahead === 0) {\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n }\n }\n flush_pending(strm);\n if (strm.avail_out === 0) {\n s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */\n return Z_OK;\n }\n }\n }\n //Assert(strm->avail_out > 0, \"bug2\");\n //if (strm.avail_out <= 0) { throw new Error(\"bug2\");}\n\n if (flush !== Z_FINISH) { return Z_OK; }\n if (s.wrap <= 0) { return Z_STREAM_END; }\n\n /* Write the trailer */\n if (s.wrap === 2) {\n put_byte(s, strm.adler & 0xff);\n put_byte(s, (strm.adler >> 8) & 0xff);\n put_byte(s, (strm.adler >> 16) & 0xff);\n put_byte(s, (strm.adler >> 24) & 0xff);\n put_byte(s, strm.total_in & 0xff);\n put_byte(s, (strm.total_in >> 8) & 0xff);\n put_byte(s, (strm.total_in >> 16) & 0xff);\n put_byte(s, (strm.total_in >> 24) & 0xff);\n }\n else\n {\n putShortMSB(s, strm.adler >>> 16);\n putShortMSB(s, strm.adler & 0xffff);\n }\n\n flush_pending(strm);\n /* If avail_out is zero, the application will call deflate again\n * to flush the rest.\n */\n if (s.wrap > 0) { s.wrap = -s.wrap; }\n /* write the trailer only once! */\n return s.pending !== 0 ? Z_OK : Z_STREAM_END;\n};\n\n\nconst deflateEnd = (strm) => {\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n const status = strm.state.status;\n if (status !== INIT_STATE &&\n status !== EXTRA_STATE &&\n status !== NAME_STATE &&\n status !== COMMENT_STATE &&\n status !== HCRC_STATE &&\n status !== BUSY_STATE &&\n status !== FINISH_STATE\n ) {\n return err(strm, Z_STREAM_ERROR);\n }\n\n strm.state = null;\n\n return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;\n};\n\n\n/* =========================================================================\n * Initializes the compression dictionary from the given byte\n * sequence without producing any compressed output.\n */\nconst deflateSetDictionary = (strm, dictionary) => {\n\n let dictLength = dictionary.length;\n\n if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {\n return Z_STREAM_ERROR;\n }\n\n const s = strm.state;\n const wrap = s.wrap;\n\n if (wrap === 2 || (wrap === 1 && s.status !== INIT_STATE) || s.lookahead) {\n return Z_STREAM_ERROR;\n }\n\n /* when using zlib wrappers, compute Adler-32 for provided dictionary */\n if (wrap === 1) {\n /* adler32(strm->adler, dictionary, dictLength); */\n strm.adler = adler32_1(strm.adler, dictionary, dictLength, 0);\n }\n\n s.wrap = 0; /* avoid computing Adler-32 in read_buf */\n\n /* if dictionary would fill window, just replace the history */\n if (dictLength >= s.w_size) {\n if (wrap === 0) { /* already empty otherwise */\n /*** CLEAR_HASH(s); ***/\n zero$1(s.head); // Fill with NIL (= 0);\n s.strstart = 0;\n s.block_start = 0;\n s.insert = 0;\n }\n /* use the tail */\n // dictionary = dictionary.slice(dictLength - s.w_size);\n let tmpDict = new Uint8Array(s.w_size);\n tmpDict.set(dictionary.subarray(dictLength - s.w_size, dictLength), 0);\n dictionary = tmpDict;\n dictLength = s.w_size;\n }\n /* insert dictionary into window and hash */\n const avail = strm.avail_in;\n const next = strm.next_in;\n const input = strm.input;\n strm.avail_in = dictLength;\n strm.next_in = 0;\n strm.input = dictionary;\n fill_window(s);\n while (s.lookahead >= MIN_MATCH$1) {\n let str = s.strstart;\n let n = s.lookahead - (MIN_MATCH$1 - 1);\n do {\n /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */\n s.ins_h = HASH(s, s.ins_h, s.window[str + MIN_MATCH$1 - 1]);\n\n s.prev[str & s.w_mask] = s.head[s.ins_h];\n\n s.head[s.ins_h] = str;\n str++;\n } while (--n);\n s.strstart = str;\n s.lookahead = MIN_MATCH$1 - 1;\n fill_window(s);\n }\n s.strstart += s.lookahead;\n s.block_start = s.strstart;\n s.insert = s.lookahead;\n s.lookahead = 0;\n s.match_length = s.prev_length = MIN_MATCH$1 - 1;\n s.match_available = 0;\n strm.next_in = next;\n strm.input = input;\n strm.avail_in = avail;\n s.wrap = wrap;\n return Z_OK;\n};\n\n\nvar deflateInit_1 = deflateInit;\nvar deflateInit2_1 = deflateInit2;\nvar deflateReset_1 = deflateReset;\nvar deflateResetKeep_1 = deflateResetKeep;\nvar deflateSetHeader_1 = deflateSetHeader;\nvar deflate_2 = deflate;\nvar deflateEnd_1 = deflateEnd;\nvar deflateSetDictionary_1 = deflateSetDictionary;\nvar deflateInfo = 'pako deflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.deflateBound = deflateBound;\nmodule.exports.deflateCopy = deflateCopy;\nmodule.exports.deflateParams = deflateParams;\nmodule.exports.deflatePending = deflatePending;\nmodule.exports.deflatePrime = deflatePrime;\nmodule.exports.deflateTune = deflateTune;\n*/\n\nvar deflate_1 = {\n\tdeflateInit: deflateInit_1,\n\tdeflateInit2: deflateInit2_1,\n\tdeflateReset: deflateReset_1,\n\tdeflateResetKeep: deflateResetKeep_1,\n\tdeflateSetHeader: deflateSetHeader_1,\n\tdeflate: deflate_2,\n\tdeflateEnd: deflateEnd_1,\n\tdeflateSetDictionary: deflateSetDictionary_1,\n\tdeflateInfo: deflateInfo\n};\n\nconst _has = (obj, key) => {\n return Object.prototype.hasOwnProperty.call(obj, key);\n};\n\nvar assign = function (obj /*from1, from2, from3, ...*/) {\n const sources = Array.prototype.slice.call(arguments, 1);\n while (sources.length) {\n const source = sources.shift();\n if (!source) { continue; }\n\n if (typeof source !== 'object') {\n throw new TypeError(source + 'must be non-object');\n }\n\n for (const p in source) {\n if (_has(source, p)) {\n obj[p] = source[p];\n }\n }\n }\n\n return obj;\n};\n\n\n// Join array of chunks to single array.\nvar flattenChunks = (chunks) => {\n // calculate data length\n let len = 0;\n\n for (let i = 0, l = chunks.length; i < l; i++) {\n len += chunks[i].length;\n }\n\n // join chunks\n const result = new Uint8Array(len);\n\n for (let i = 0, pos = 0, l = chunks.length; i < l; i++) {\n let chunk = chunks[i];\n result.set(chunk, pos);\n pos += chunk.length;\n }\n\n return result;\n};\n\nvar common = {\n\tassign: assign,\n\tflattenChunks: flattenChunks\n};\n\n// String encode/decode helpers\n\n\n// Quick check if we can use fast array to bin string conversion\n//\n// - apply(Array) can fail on Android 2.2\n// - apply(Uint8Array) can fail on iOS 5.1 Safari\n//\nlet STR_APPLY_UIA_OK = true;\n\ntry { String.fromCharCode.apply(null, new Uint8Array(1)); } catch (__) { STR_APPLY_UIA_OK = false; }\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\nconst _utf8len = new Uint8Array(256);\nfor (let q = 0; q < 256; q++) {\n _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);\n}\n_utf8len[254] = _utf8len[254] = 1; // Invalid sequence start\n\n\n// convert string to array (typed, when possible)\nvar string2buf = (str) => {\n let 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 buf = new Uint8Array(buf_len);\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// Helper\nconst buf2binstring = (buf, len) => {\n // On Chrome, the arguments in a function call that are allowed is `65534`.\n // If the length of the buffer is smaller than that, we can use this optimization,\n // otherwise we will take a slower path.\n if (len < 65534) {\n if (buf.subarray && STR_APPLY_UIA_OK) {\n return String.fromCharCode.apply(null, buf.length === len ? buf : buf.subarray(0, len));\n }\n }\n\n let result = '';\n for (let i = 0; i < len; i++) {\n result += String.fromCharCode(buf[i]);\n }\n return result;\n};\n\n\n// convert array to string\nvar buf2string = (buf, max) => {\n let i, out;\n const len = max || 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 const utf16buf = new Array(len * 2);\n\n for (out = 0, i = 0; i < len;) {\n let c = buf[i++];\n // quick process ascii\n if (c < 0x80) { utf16buf[out++] = c; continue; }\n\n let c_len = _utf8len[c];\n // skip 5 & 6 byte codes\n if (c_len > 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 return buf2binstring(utf16buf, out);\n};\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 = (buf, max) => {\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 let pos = max - 1;\n while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }\n\n // 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 buffer 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\nvar strings = {\n\tstring2buf: string2buf,\n\tbuf2string: buf2string,\n\tutf8border: utf8border\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction ZStream() {\n /* next input byte */\n this.input = null; // JS specific, because we have no pointers\n this.next_in = 0;\n /* number of bytes available at input */\n this.avail_in = 0;\n /* total number of input bytes read so far */\n this.total_in = 0;\n /* next output byte should be put there */\n this.output = null; // JS specific, because we have no pointers\n this.next_out = 0;\n /* remaining free space at output */\n this.avail_out = 0;\n /* total number of bytes output so far */\n this.total_out = 0;\n /* last error message, NULL if no error */\n this.msg = ''/*Z_NULL*/;\n /* not visible by applications */\n this.state = null;\n /* best guess about the data type: binary or text */\n this.data_type = 2/*Z_UNKNOWN*/;\n /* adler32 value of the uncompressed data */\n this.adler = 0;\n}\n\nvar zstream = ZStream;\n\nconst toString = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$1, Z_SYNC_FLUSH, Z_FULL_FLUSH: Z_FULL_FLUSH$1, Z_FINISH: Z_FINISH$1,\n Z_OK: Z_OK$1, Z_STREAM_END: Z_STREAM_END$1,\n Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION$1,\n Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY$1,\n Z_DEFLATED: Z_DEFLATED$1\n} = constants;\n\n/* ===========================================================================*/\n\n\n/**\n * class Deflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[deflate]],\n * [[deflateRaw]] and [[gzip]].\n **/\n\n/* internal\n * Deflate.chunks -> Array\n *\n * Chunks of output data, if [[Deflate#onData]] not overridden.\n **/\n\n/**\n * Deflate.result -> Uint8Array\n *\n * Compressed result, generated by default [[Deflate#onData]]\n * and [[Deflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Deflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Deflate.err -> Number\n *\n * Error code after deflate finished. 0 (Z_OK) on success.\n * You will not need it in real life, because deflate errors\n * are possible only on wrong options or bad `onData` / `onEnd`\n * custom handlers.\n **/\n\n/**\n * Deflate.msg -> String\n *\n * Error message, if [[Deflate.err]] != 0\n **/\n\n\n/**\n * new Deflate(options)\n * - options (Object): zlib deflate options.\n *\n * Creates new deflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `level`\n * - `windowBits`\n * - `memLevel`\n * - `strategy`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw deflate\n * - `gzip` (Boolean) - create gzip wrapper\n * - `header` (Object) - custom header for gzip\n * - `text` (Boolean) - true if compressed data believed to be text\n * - `time` (Number) - modification time, unix timestamp\n * - `os` (Number) - operation system code\n * - `extra` (Array) - array of bytes with extra data (max 65536)\n * - `name` (String) - file name (binary string)\n * - `comment` (String) - comment (binary string)\n * - `hcrc` (Boolean) - true if header crc should be added\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * , chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * , chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const deflate = new pako.Deflate({ level: 3});\n *\n * deflate.push(chunk1, false);\n * deflate.push(chunk2, true); // true -> last chunk\n *\n * if (deflate.err) { throw new Error(deflate.err); }\n *\n * console.log(deflate.result);\n * ```\n **/\nfunction Deflate(options) {\n this.options = common.assign({\n level: Z_DEFAULT_COMPRESSION$1,\n method: Z_DEFLATED$1,\n chunkSize: 16384,\n windowBits: 15,\n memLevel: 8,\n strategy: Z_DEFAULT_STRATEGY$1\n }, options || {});\n\n let opt = this.options;\n\n if (opt.raw && (opt.windowBits > 0)) {\n opt.windowBits = -opt.windowBits;\n }\n\n else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {\n opt.windowBits += 16;\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = deflate_1.deflateInit2(\n this.strm,\n opt.level,\n opt.method,\n opt.windowBits,\n opt.memLevel,\n opt.strategy\n );\n\n if (status !== Z_OK$1) {\n throw new Error(messages[status]);\n }\n\n if (opt.header) {\n deflate_1.deflateSetHeader(this.strm, opt.header);\n }\n\n if (opt.dictionary) {\n let dict;\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n // If we need to compress text, change encoding to utf8.\n dict = strings.string2buf(opt.dictionary);\n } else if (toString.call(opt.dictionary) === '[object ArrayBuffer]') {\n dict = new Uint8Array(opt.dictionary);\n } else {\n dict = opt.dictionary;\n }\n\n status = deflate_1.deflateSetDictionary(this.strm, dict);\n\n if (status !== Z_OK$1) {\n throw new Error(messages[status]);\n }\n\n this._dict_set = true;\n }\n}\n\n/**\n * Deflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer|String): input data. Strings will be\n * converted to utf8 byte sequence.\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.\n * See constants. Skipped or `false` means Z_NO_FLUSH, `true` means Z_FINISH.\n *\n * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with\n * new compressed chunks. Returns `true` on success. The last data block must\n * have `flush_mode` Z_FINISH (or `true`). That will flush internal pending\n * buffers and call [[Deflate#onEnd]].\n *\n * On fail call [[Deflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nDeflate.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n let status, _flush_mode;\n\n if (this.ended) { return false; }\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$1 : Z_NO_FLUSH$1;\n\n // Convert data if needed\n if (typeof data === 'string') {\n // If we need to compress text, change encoding to utf8.\n strm.input = strings.string2buf(data);\n } else if (toString.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n // Make sure avail_out > 6 to avoid repeating markers\n if ((_flush_mode === Z_SYNC_FLUSH || _flush_mode === Z_FULL_FLUSH$1) && strm.avail_out <= 6) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n status = deflate_1.deflate(strm, _flush_mode);\n\n // Ended => flush and finish\n if (status === Z_STREAM_END$1) {\n if (strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n }\n status = deflate_1.deflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return status === Z_OK$1;\n }\n\n // Flush if out buffer full\n if (strm.avail_out === 0) {\n this.onData(strm.output);\n continue;\n }\n\n // Flush if requested and has data\n if (_flush_mode > 0 && strm.next_out > 0) {\n this.onData(strm.output.subarray(0, strm.next_out));\n strm.avail_out = 0;\n continue;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Deflate#onData(chunk) -> Void\n * - chunk (Uint8Array): output data.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nDeflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Deflate#onEnd(status) -> Void\n * - status (Number): deflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called once after you tell deflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nDeflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$1) {\n this.result = common.flattenChunks(this.chunks);\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * deflate(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * Compress `data` with deflate algorithm and `options`.\n *\n * Supported options are:\n *\n * - level\n * - windowBits\n * - memLevel\n * - strategy\n * - dictionary\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const data = new Uint8Array([1,2,3,4,5,6,7,8,9]);\n *\n * console.log(pako.deflate(data));\n * ```\n **/\nfunction deflate$1(input, options) {\n const deflator = new Deflate(options);\n\n deflator.push(input, true);\n\n // That will never happens, if you don't cheat with options :)\n if (deflator.err) { throw deflator.msg || messages[deflator.err]; }\n\n return deflator.result;\n}\n\n\n/**\n * deflateRaw(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction deflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return deflate$1(input, options);\n}\n\n\n/**\n * gzip(data[, options]) -> Uint8Array\n * - data (Uint8Array|String): input data to compress.\n * - options (Object): zlib deflate options.\n *\n * The same as [[deflate]], but create gzip wrapper instead of\n * deflate one.\n **/\nfunction gzip(input, options) {\n options = options || {};\n options.gzip = true;\n return deflate$1(input, options);\n}\n\n\nvar Deflate_1 = Deflate;\nvar deflate_2$1 = deflate$1;\nvar deflateRaw_1 = deflateRaw;\nvar gzip_1 = gzip;\nvar constants$1 = constants;\n\nvar deflate_1$1 = {\n\tDeflate: Deflate_1,\n\tdeflate: deflate_2$1,\n\tdeflateRaw: deflateRaw_1,\n\tgzip: gzip_1,\n\tconstants: constants$1\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n// See state defs from inflate.js\nconst BAD = 30; /* got a data error -- remain here until reset */\nconst TYPE = 12; /* i: waiting for type bits, including last-flag bit */\n\n/*\n Decode literal, length, and distance codes and write out the resulting\n literal and match bytes until either not enough input or output is\n available, an end-of-block is encountered, or a data error is encountered.\n When large enough input and output buffers are supplied to inflate(), for\n example, a 16K input buffer and a 64K output buffer, more than 95% of the\n inflate execution time is spent in this routine.\n\n Entry assumptions:\n\n state.mode === LEN\n strm.avail_in >= 6\n strm.avail_out >= 258\n start >= strm.avail_out\n state.bits < 8\n\n On return, state.mode is one of:\n\n LEN -- ran out of enough output space or enough available input\n TYPE -- reached end of block code, inflate() to interpret next block\n BAD -- error in block data\n\n Notes:\n\n - The maximum input bits used by a length/distance pair is 15 bits for the\n length code, 5 bits for the length extra, 15 bits for the distance code,\n and 13 bits for the distance extra. This totals 48 bits, or six bytes.\n Therefore if strm.avail_in >= 6, then there is enough input to avoid\n checking for available input while decoding.\n\n - The maximum bytes that a single length/distance pair can output is 258\n bytes, which is the maximum length that can be coded. inflate_fast()\n requires strm.avail_out >= 258 for each loop to avoid checking for\n output space.\n */\nvar inffast = function inflate_fast(strm, start) {\n let _in; /* local strm.input */\n let last; /* have enough input while in < last */\n let _out; /* local strm.output */\n let beg; /* inflate()'s initial strm.output */\n let end; /* while out < end, enough space available */\n//#ifdef INFLATE_STRICT\n let dmax; /* maximum distance from zlib header */\n//#endif\n let wsize; /* window size or zero if not using window */\n let whave; /* valid bytes in the window */\n let wnext; /* window write index */\n // Use `s_window` instead `window`, avoid conflict with instrumentation tools\n let s_window; /* allocated sliding window, if wsize != 0 */\n let hold; /* local strm.hold */\n let bits; /* local strm.bits */\n let lcode; /* local strm.lencode */\n let dcode; /* local strm.distcode */\n let lmask; /* mask for first level of length codes */\n let dmask; /* mask for first level of distance codes */\n let here; /* retrieved table entry */\n let op; /* code bits, operation, extra bits, or */\n /* window position, window bytes to copy */\n let len; /* match length, unused bytes */\n let dist; /* match distance */\n let from; /* where to copy match from */\n let from_source;\n\n\n let input, output; // JS specific, because we have no pointers\n\n /* copy state to local variables */\n const state = strm.state;\n //here = state.here;\n _in = strm.next_in;\n input = strm.input;\n last = _in + (strm.avail_in - 5);\n _out = strm.next_out;\n output = strm.output;\n beg = _out - (start - strm.avail_out);\n end = _out + (strm.avail_out - 257);\n//#ifdef INFLATE_STRICT\n dmax = state.dmax;\n//#endif\n wsize = state.wsize;\n whave = state.whave;\n wnext = state.wnext;\n s_window = state.window;\n hold = state.hold;\n bits = state.bits;\n lcode = state.lencode;\n dcode = state.distcode;\n lmask = (1 << state.lenbits) - 1;\n dmask = (1 << state.distbits) - 1;\n\n\n /* decode literals and length/distances until end-of-block or not enough\n input data or output space */\n\n top:\n do {\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n\n here = lcode[hold & lmask];\n\n dolen:\n for (;;) { // Goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n if (op === 0) { /* literal */\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n output[_out++] = here & 0xffff/*here.val*/;\n }\n else if (op & 16) { /* length base */\n len = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (op) {\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n len += hold & ((1 << op) - 1);\n hold >>>= op;\n bits -= op;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", len));\n if (bits < 15) {\n hold += input[_in++] << bits;\n bits += 8;\n hold += input[_in++] << bits;\n bits += 8;\n }\n here = dcode[hold & dmask];\n\n dodist:\n for (;;) { // goto emulation\n op = here >>> 24/*here.bits*/;\n hold >>>= op;\n bits -= op;\n op = (here >>> 16) & 0xff/*here.op*/;\n\n if (op & 16) { /* distance base */\n dist = here & 0xffff/*here.val*/;\n op &= 15; /* number of extra bits */\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n if (bits < op) {\n hold += input[_in++] << bits;\n bits += 8;\n }\n }\n dist += hold & ((1 << op) - 1);\n//#ifdef INFLATE_STRICT\n if (dist > dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n//#endif\n hold >>>= op;\n bits -= op;\n //Tracevv((stderr, \"inflate: distance %u\\n\", dist));\n op = _out - beg; /* max distance in output */\n if (dist > op) { /* see if copy from window */\n op = dist - op; /* distance back in window */\n if (op > whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD;\n break top;\n }\n\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// if (len <= op - whave) {\n// do {\n// output[_out++] = 0;\n// } while (--len);\n// continue top;\n// }\n// len -= op - whave;\n// do {\n// output[_out++] = 0;\n// } while (--op > whave);\n// if (op === 0) {\n// from = _out - dist;\n// do {\n// output[_out++] = output[from++];\n// } while (--len);\n// continue top;\n// }\n//#endif\n }\n from = 0; // window index\n from_source = s_window;\n if (wnext === 0) { /* very common case */\n from += wsize - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n else if (wnext < op) { /* wrap around window */\n from += wsize + wnext - op;\n op -= wnext;\n if (op < len) { /* some from end of window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = 0;\n if (wnext < len) { /* some from start of window */\n op = wnext;\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n }\n else { /* contiguous in window */\n from += wnext - op;\n if (op < len) { /* some from window */\n len -= op;\n do {\n output[_out++] = s_window[from++];\n } while (--op);\n from = _out - dist; /* rest from output */\n from_source = output;\n }\n }\n while (len > 2) {\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n output[_out++] = from_source[from++];\n len -= 3;\n }\n if (len) {\n output[_out++] = from_source[from++];\n if (len > 1) {\n output[_out++] = from_source[from++];\n }\n }\n }\n else {\n from = _out - dist; /* copy direct from output */\n do { /* minimum length is three */\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n output[_out++] = output[from++];\n len -= 3;\n } while (len > 2);\n if (len) {\n output[_out++] = output[from++];\n if (len > 1) {\n output[_out++] = output[from++];\n }\n }\n }\n }\n else if ((op & 64) === 0) { /* 2nd level distance code */\n here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dodist;\n }\n else {\n strm.msg = 'invalid distance code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n }\n else if ((op & 64) === 0) { /* 2nd level length code */\n here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];\n continue dolen;\n }\n else if (op & 32) { /* end-of-block */\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.mode = TYPE;\n break top;\n }\n else {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD;\n break top;\n }\n\n break; // need to emulate goto via \"continue\"\n }\n } while (_in < last && _out < end);\n\n /* return unused bytes (on entry, bits < 8, so in won't go too far back) */\n len = bits >> 3;\n _in -= len;\n bits -= len << 3;\n hold &= (1 << bits) - 1;\n\n /* update state and return */\n strm.next_in = _in;\n strm.next_out = _out;\n strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));\n strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));\n state.hold = hold;\n state.bits = bits;\n return;\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nconst MAXBITS = 15;\nconst ENOUGH_LENS = 852;\nconst ENOUGH_DISTS = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst CODES = 0;\nconst LENS = 1;\nconst DISTS = 2;\n\nconst lbase = new Uint16Array([ /* Length codes 257..285 base */\n 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,\n 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0\n]);\n\nconst lext = new Uint8Array([ /* Length codes 257..285 extra */\n 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,\n 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78\n]);\n\nconst dbase = new Uint16Array([ /* Distance codes 0..29 base */\n 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,\n 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,\n 8193, 12289, 16385, 24577, 0, 0\n]);\n\nconst dext = new Uint8Array([ /* Distance codes 0..29 extra */\n 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,\n 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,\n 28, 28, 29, 29, 64, 64\n]);\n\nconst inflate_table = (type, lens, lens_index, codes, table, table_index, work, opts) =>\n{\n const bits = opts.bits;\n //here = opts.here; /* table entry for duplication */\n\n let len = 0; /* a code's length in bits */\n let sym = 0; /* index of code symbols */\n let min = 0, max = 0; /* minimum and maximum code lengths */\n let root = 0; /* number of index bits for root table */\n let curr = 0; /* number of index bits for current table */\n let drop = 0; /* code bits to drop for sub-table */\n let left = 0; /* number of prefix codes available */\n let used = 0; /* code entries in table used */\n let huff = 0; /* Huffman code */\n let incr; /* for incrementing code, index */\n let fill; /* index for replicating entries */\n let low; /* low bits for current root entry */\n let mask; /* mask for low root bits */\n let next; /* next available space in table */\n let base = null; /* base value table to use */\n let base_index = 0;\n// let shoextra; /* extra bits table to use */\n let end; /* use base and extra for symbol > end */\n const count = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */\n const offs = new Uint16Array(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */\n let extra = null;\n let extra_index = 0;\n\n let here_bits, here_op, here_val;\n\n /*\n Process a set of code lengths to create a canonical Huffman code. The\n code lengths are lens[0..codes-1]. Each length corresponds to the\n symbols 0..codes-1. The Huffman code is generated by first sorting the\n symbols by length from short to long, and retaining the symbol order\n for codes with equal lengths. Then the code starts with all zero bits\n for the first code of the shortest length, and the codes are integer\n increments for the same length, and zeros are appended as the length\n increases. For the deflate format, these bits are stored backwards\n from their more natural integer increment ordering, and so when the\n decoding tables are built in the large loop below, the integer codes\n are incremented backwards.\n\n This routine assumes, but does not check, that all of the entries in\n lens[] are in the range 0..MAXBITS. The caller must assure this.\n 1..MAXBITS is interpreted as that code length. zero means that that\n symbol does not occur in this code.\n\n The codes are sorted by computing a count of codes for each length,\n creating from that a table of starting indices for each length in the\n sorted table, and then entering the symbols in order in the sorted\n table. The sorted table is work[], with that space being provided by\n the caller.\n\n The length counts are used for other purposes as well, i.e. finding\n the minimum and maximum length codes, determining if there are any\n codes at all, checking for a valid set of lengths, and looking ahead\n at length counts to determine sub-table sizes when building the\n decoding tables.\n */\n\n /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */\n for (len = 0; len <= MAXBITS; len++) {\n count[len] = 0;\n }\n for (sym = 0; sym < codes; sym++) {\n count[lens[lens_index + sym]]++;\n }\n\n /* bound code lengths, force root to be within code lengths */\n root = bits;\n for (max = MAXBITS; max >= 1; max--) {\n if (count[max] !== 0) { break; }\n }\n if (root > max) {\n root = max;\n }\n if (max === 0) { /* no symbols to code at all */\n //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */\n //table.bits[opts.table_index] = 1; //here.bits = (var char)1;\n //table.val[opts.table_index++] = 0; //here.val = (var short)0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n\n //table.op[opts.table_index] = 64;\n //table.bits[opts.table_index] = 1;\n //table.val[opts.table_index++] = 0;\n table[table_index++] = (1 << 24) | (64 << 16) | 0;\n\n opts.bits = 1;\n return 0; /* no symbols, but wait for decoding to report error */\n }\n for (min = 1; min < max; min++) {\n if (count[min] !== 0) { break; }\n }\n if (root < min) {\n root = min;\n }\n\n /* check for an over-subscribed or incomplete set of lengths */\n left = 1;\n for (len = 1; len <= MAXBITS; len++) {\n left <<= 1;\n left -= count[len];\n if (left < 0) {\n return -1;\n } /* over-subscribed */\n }\n if (left > 0 && (type === CODES || max !== 1)) {\n return -1; /* incomplete set */\n }\n\n /* generate offsets into symbol table for each length for sorting */\n offs[1] = 0;\n for (len = 1; len < MAXBITS; len++) {\n offs[len + 1] = offs[len] + count[len];\n }\n\n /* sort symbols by length, by symbol order within each length */\n for (sym = 0; sym < codes; sym++) {\n if (lens[lens_index + sym] !== 0) {\n work[offs[lens[lens_index + sym]]++] = sym;\n }\n }\n\n /*\n Create and fill in decoding tables. In this loop, the table being\n filled is at next and has curr index bits. The code being used is huff\n with length len. That code is converted to an index by dropping drop\n bits off of the bottom. For codes where len is less than drop + curr,\n those top drop + curr - len bits are incremented through all values to\n fill the table with replicated entries.\n\n root is the number of index bits for the root table. When len exceeds\n root, sub-tables are created pointed to by the root entry with an index\n of the low root bits of huff. This is saved in low to check for when a\n new sub-table should be started. drop is zero when the root table is\n being filled, and drop is root when sub-tables are being filled.\n\n When a new sub-table is needed, it is necessary to look ahead in the\n code lengths to determine what size sub-table is needed. The length\n counts are used for this, and so count[] is decremented as codes are\n entered in the tables.\n\n used keeps track of how many table entries have been allocated from the\n provided *table space. It is checked for LENS and DIST tables against\n the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in\n the initial root table size constants. See the comments in inftrees.h\n for more information.\n\n sym increments through all symbols, and the loop terminates when\n all codes of length max, i.e. all codes, have been processed. This\n routine permits incomplete codes, so another loop after this one fills\n in the rest of the decoding tables with invalid code markers.\n */\n\n /* set up for code type */\n // poor man optimization - use if-else instead of switch,\n // to avoid deopts in old v8\n if (type === CODES) {\n base = extra = work; /* dummy value--not used */\n end = 19;\n\n } else if (type === LENS) {\n base = lbase;\n base_index -= 257;\n extra = lext;\n extra_index -= 257;\n end = 256;\n\n } else { /* DISTS */\n base = dbase;\n extra = dext;\n end = -1;\n }\n\n /* initialize opts for loop */\n huff = 0; /* starting code */\n sym = 0; /* starting code symbol */\n len = min; /* starting code length */\n next = table_index; /* current table to fill in */\n curr = root; /* current table index bits */\n drop = 0; /* current bits to drop from code for index */\n low = -1; /* trigger new sub-table when len > root */\n used = 1 << root; /* use root table entries */\n mask = used - 1; /* mask for comparing low */\n\n /* check available table space */\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* process all codes and make table entries */\n for (;;) {\n /* create table entry */\n here_bits = len - drop;\n if (work[sym] < end) {\n here_op = 0;\n here_val = work[sym];\n }\n else if (work[sym] > end) {\n here_op = extra[extra_index + work[sym]];\n here_val = base[base_index + work[sym]];\n }\n else {\n here_op = 32 + 64; /* end of block */\n here_val = 0;\n }\n\n /* replicate for those indices with low len bits equal to huff */\n incr = 1 << (len - drop);\n fill = 1 << curr;\n min = fill; /* save offset to next table */\n do {\n fill -= incr;\n table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;\n } while (fill !== 0);\n\n /* backwards increment the len-bit code huff */\n incr = 1 << (len - 1);\n while (huff & incr) {\n incr >>= 1;\n }\n if (incr !== 0) {\n huff &= incr - 1;\n huff += incr;\n } else {\n huff = 0;\n }\n\n /* go to next symbol, update count, len */\n sym++;\n if (--count[len] === 0) {\n if (len === max) { break; }\n len = lens[lens_index + work[sym]];\n }\n\n /* create new sub-table if needed */\n if (len > root && (huff & mask) !== low) {\n /* if first time, transition to sub-tables */\n if (drop === 0) {\n drop = root;\n }\n\n /* increment past last table */\n next += min; /* here min is 1 << curr */\n\n /* determine length of next table */\n curr = len - drop;\n left = 1 << curr;\n while (curr + drop < max) {\n left -= count[curr + drop];\n if (left <= 0) { break; }\n curr++;\n left <<= 1;\n }\n\n /* check for enough space */\n used += 1 << curr;\n if ((type === LENS && used > ENOUGH_LENS) ||\n (type === DISTS && used > ENOUGH_DISTS)) {\n return 1;\n }\n\n /* point entry in root table to sub-table */\n low = huff & mask;\n /*table.op[low] = curr;\n table.bits[low] = root;\n table.val[low] = next - opts.table_index;*/\n table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;\n }\n }\n\n /* fill in remaining table entry if code is incomplete (guaranteed to have\n at most one remaining entry, since if the code is incomplete, the\n maximum code length that was allowed to get this far is one bit) */\n if (huff !== 0) {\n //table.op[next + huff] = 64; /* invalid code marker */\n //table.bits[next + huff] = len - drop;\n //table.val[next + huff] = 0;\n table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;\n }\n\n /* set return parameters */\n //opts.table_index += used;\n opts.bits = root;\n return 0;\n};\n\n\nvar inftrees = inflate_table;\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\n\n\n\n\n\nconst CODES$1 = 0;\nconst LENS$1 = 1;\nconst DISTS$1 = 2;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_FINISH: Z_FINISH$2, Z_BLOCK: Z_BLOCK$1, Z_TREES,\n Z_OK: Z_OK$2, Z_STREAM_END: Z_STREAM_END$2, Z_NEED_DICT, Z_STREAM_ERROR: Z_STREAM_ERROR$1, Z_DATA_ERROR: Z_DATA_ERROR$1, Z_MEM_ERROR, Z_BUF_ERROR: Z_BUF_ERROR$1,\n Z_DEFLATED: Z_DEFLATED$2\n} = constants;\n\n\n/* STATES ====================================================================*/\n/* ===========================================================================*/\n\n\nconst HEAD = 1; /* i: waiting for magic header */\nconst FLAGS = 2; /* i: waiting for method and flags (gzip) */\nconst TIME = 3; /* i: waiting for modification time (gzip) */\nconst OS = 4; /* i: waiting for extra flags and operating system (gzip) */\nconst EXLEN = 5; /* i: waiting for extra length (gzip) */\nconst EXTRA = 6; /* i: waiting for extra bytes (gzip) */\nconst NAME = 7; /* i: waiting for end of file name (gzip) */\nconst COMMENT = 8; /* i: waiting for end of comment (gzip) */\nconst HCRC = 9; /* i: waiting for header crc (gzip) */\nconst DICTID = 10; /* i: waiting for dictionary check value */\nconst DICT = 11; /* waiting for inflateSetDictionary() call */\nconst TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */\nconst TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */\nconst STORED = 14; /* i: waiting for stored size (length and complement) */\nconst COPY_ = 15; /* i/o: same as COPY below, but only first time in */\nconst COPY = 16; /* i/o: waiting for input or output to copy stored block */\nconst TABLE = 17; /* i: waiting for dynamic block table lengths */\nconst LENLENS = 18; /* i: waiting for code length code lengths */\nconst CODELENS = 19; /* i: waiting for length/lit and distance code lengths */\nconst LEN_ = 20; /* i: same as LEN below, but only first time in */\nconst LEN = 21; /* i: waiting for length/lit/eob code */\nconst LENEXT = 22; /* i: waiting for length extra bits */\nconst DIST = 23; /* i: waiting for distance code */\nconst DISTEXT = 24; /* i: waiting for distance extra bits */\nconst MATCH = 25; /* o: waiting for output space to copy string */\nconst LIT = 26; /* o: waiting for output space to write literal */\nconst CHECK = 27; /* i: waiting for 32-bit check value */\nconst LENGTH = 28; /* i: waiting for 32-bit length (gzip) */\nconst DONE = 29; /* finished check, done -- remain here until reset */\nconst BAD$1 = 30; /* got a data error -- remain here until reset */\nconst MEM = 31; /* got an inflate() memory error -- remain here until reset */\nconst SYNC = 32; /* looking for synchronization bytes to restart inflate() */\n\n/* ===========================================================================*/\n\n\n\nconst ENOUGH_LENS$1 = 852;\nconst ENOUGH_DISTS$1 = 592;\n//const ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);\n\nconst MAX_WBITS$1 = 15;\n/* 32K LZ77 window */\nconst DEF_WBITS = MAX_WBITS$1;\n\n\nconst zswap32 = (q) => {\n\n return (((q >>> 24) & 0xff) +\n ((q >>> 8) & 0xff00) +\n ((q & 0xff00) << 8) +\n ((q & 0xff) << 24));\n};\n\n\nfunction InflateState() {\n this.mode = 0; /* current inflate mode */\n this.last = false; /* true if processing last block */\n this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */\n this.havedict = false; /* true if dictionary provided */\n this.flags = 0; /* gzip header method and flags (0 if zlib) */\n this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */\n this.check = 0; /* protected copy of check value */\n this.total = 0; /* protected copy of output count */\n // TODO: may be {}\n this.head = null; /* where to save gzip header information */\n\n /* sliding window */\n this.wbits = 0; /* log base 2 of requested window size */\n this.wsize = 0; /* window size or zero if not using window */\n this.whave = 0; /* valid bytes in the window */\n this.wnext = 0; /* window write index */\n this.window = null; /* allocated sliding window, if needed */\n\n /* bit accumulator */\n this.hold = 0; /* input bit accumulator */\n this.bits = 0; /* number of bits in \"in\" */\n\n /* for string and stored block copying */\n this.length = 0; /* literal or length of data to copy */\n this.offset = 0; /* distance back to copy string from */\n\n /* for table and code decoding */\n this.extra = 0; /* extra bits needed */\n\n /* fixed and dynamic code tables */\n this.lencode = null; /* starting table for length/literal codes */\n this.distcode = null; /* starting table for distance codes */\n this.lenbits = 0; /* index bits for lencode */\n this.distbits = 0; /* index bits for distcode */\n\n /* dynamic table building */\n this.ncode = 0; /* number of code length code lengths */\n this.nlen = 0; /* number of length code lengths */\n this.ndist = 0; /* number of distance code lengths */\n this.have = 0; /* number of code lengths in lens[] */\n this.next = null; /* next available space in codes[] */\n\n this.lens = new Uint16Array(320); /* temporary storage for code lengths */\n this.work = new Uint16Array(288); /* work area for code table building */\n\n /*\n because we don't have pointers in js, we use lencode and distcode directly\n as buffers so we don't need codes\n */\n //this.codes = new Int32Array(ENOUGH); /* space for code tables */\n this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */\n this.distdyn = null; /* dynamic table for distance codes (JS specific) */\n this.sane = 0; /* if false, allow invalid distance too far */\n this.back = 0; /* bits back of last unprocessed length/lit */\n this.was = 0; /* initial length of match */\n}\n\n\nconst inflateResetKeep = (strm) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n strm.total_in = strm.total_out = state.total = 0;\n strm.msg = ''; /*Z_NULL*/\n if (state.wrap) { /* to support ill-conceived Java test suite */\n strm.adler = state.wrap & 1;\n }\n state.mode = HEAD;\n state.last = 0;\n state.havedict = 0;\n state.dmax = 32768;\n state.head = null/*Z_NULL*/;\n state.hold = 0;\n state.bits = 0;\n //state.lencode = state.distcode = state.next = state.codes;\n state.lencode = state.lendyn = new Int32Array(ENOUGH_LENS$1);\n state.distcode = state.distdyn = new Int32Array(ENOUGH_DISTS$1);\n\n state.sane = 1;\n state.back = -1;\n //Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK$2;\n};\n\n\nconst inflateReset = (strm) => {\n\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n state.wsize = 0;\n state.whave = 0;\n state.wnext = 0;\n return inflateResetKeep(strm);\n\n};\n\n\nconst inflateReset2 = (strm, windowBits) => {\n let wrap;\n\n /* get the state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 1;\n if (windowBits < 48) {\n windowBits &= 15;\n }\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15)) {\n return Z_STREAM_ERROR$1;\n }\n if (state.window !== null && state.wbits !== windowBits) {\n state.window = null;\n }\n\n /* update state and reset the rest of it */\n state.wrap = wrap;\n state.wbits = windowBits;\n return inflateReset(strm);\n};\n\n\nconst inflateInit2 = (strm, windowBits) => {\n\n if (!strm) { return Z_STREAM_ERROR$1; }\n //strm.msg = Z_NULL; /* in case we return an error */\n\n const state = new InflateState();\n\n //if (state === Z_NULL) return Z_MEM_ERROR;\n //Tracev((stderr, \"inflate: allocated\\n\"));\n strm.state = state;\n state.window = null/*Z_NULL*/;\n const ret = inflateReset2(strm, windowBits);\n if (ret !== Z_OK$2) {\n strm.state = null/*Z_NULL*/;\n }\n return ret;\n};\n\n\nconst inflateInit = (strm) => {\n\n return inflateInit2(strm, DEF_WBITS);\n};\n\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlet virgin = true;\n\nlet lenfix, distfix; // We have no pointers in JS, so keep tables separate\n\n\nconst fixedtables = (state) => {\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n lenfix = new Int32Array(512);\n distfix = new Int32Array(32);\n\n /* literal/length table */\n let sym = 0;\n while (sym < 144) { state.lens[sym++] = 8; }\n while (sym < 256) { state.lens[sym++] = 9; }\n while (sym < 280) { state.lens[sym++] = 7; }\n while (sym < 288) { state.lens[sym++] = 8; }\n\n inftrees(LENS$1, state.lens, 0, 288, lenfix, 0, state.work, { bits: 9 });\n\n /* distance table */\n sym = 0;\n while (sym < 32) { state.lens[sym++] = 5; }\n\n inftrees(DISTS$1, state.lens, 0, 32, distfix, 0, state.work, { bits: 5 });\n\n /* do this just once */\n virgin = false;\n }\n\n state.lencode = lenfix;\n state.lenbits = 9;\n state.distcode = distfix;\n state.distbits = 5;\n};\n\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nconst updatewindow = (strm, src, end, copy) => {\n\n let dist;\n const state = strm.state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state.window === null) {\n state.wsize = 1 << state.wbits;\n state.wnext = 0;\n state.whave = 0;\n\n state.window = new Uint8Array(state.wsize);\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state.wsize) {\n state.window.set(src.subarray(end - state.wsize, end), 0);\n state.wnext = 0;\n state.whave = state.wsize;\n }\n else {\n dist = state.wsize - state.wnext;\n if (dist > copy) {\n dist = copy;\n }\n //zmemcpy(state->window + state->wnext, end - copy, dist);\n state.window.set(src.subarray(end - copy, end - copy + dist), state.wnext);\n copy -= dist;\n if (copy) {\n //zmemcpy(state->window, end - copy, copy);\n state.window.set(src.subarray(end - copy, end), 0);\n state.wnext = copy;\n state.whave = state.wsize;\n }\n else {\n state.wnext += dist;\n if (state.wnext === state.wsize) { state.wnext = 0; }\n if (state.whave < state.wsize) { state.whave += dist; }\n }\n }\n return 0;\n};\n\n\nconst inflate = (strm, flush) => {\n\n let state;\n let input, output; // input/output buffers\n let next; /* next input INDEX */\n let put; /* next output INDEX */\n let have, left; /* available input and output */\n let hold; /* bit buffer */\n let bits; /* bits in bit buffer */\n let _in, _out; /* save starting available input and output */\n let copy; /* number of stored or match bytes to copy */\n let from; /* where to copy match bytes from */\n let from_source;\n let here = 0; /* current decoding table entry */\n let here_bits, here_op, here_val; // paked \"here\" denormalized (JS specific)\n //let last; /* parent table entry */\n let last_bits, last_op, last_val; // paked \"last\" denormalized (JS specific)\n let len; /* length to copy for repeats, bits to drop */\n let ret; /* return code */\n const hbuf = new Uint8Array(4); /* buffer for gzip header crc calculation */\n let opts;\n\n let n; // temporary variable for NEED_BITS\n\n const order = /* permutation of code lengths */\n new Uint8Array([ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 ]);\n\n\n if (!strm || !strm.state || !strm.output ||\n (!strm.input && strm.avail_in !== 0)) {\n return Z_STREAM_ERROR$1;\n }\n\n state = strm.state;\n if (state.mode === TYPE$1) { state.mode = TYPEDO; } /* skip check */\n\n\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n _in = have;\n _out = left;\n ret = Z_OK$2;\n\n inf_leave: // goto emulation\n for (;;) {\n switch (state.mode) {\n case HEAD:\n if (state.wrap === 0) {\n state.mode = TYPEDO;\n break;\n }\n //=== NEEDBITS(16);\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */\n state.check = 0/*crc32(0L, Z_NULL, 0)*/;\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = FLAGS;\n break;\n }\n state.flags = 0; /* expect zlib header */\n if (state.head) {\n state.head.done = false;\n }\n if (!(state.wrap & 1) || /* check if zlib header allowed */\n (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {\n strm.msg = 'incorrect header check';\n state.mode = BAD$1;\n break;\n }\n if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED$2) {\n strm.msg = 'unknown compression method';\n state.mode = BAD$1;\n break;\n }\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n len = (hold & 0x0f)/*BITS(4)*/ + 8;\n if (state.wbits === 0) {\n state.wbits = len;\n }\n else if (len > state.wbits) {\n strm.msg = 'invalid window size';\n state.mode = BAD$1;\n break;\n }\n\n // !!! pako patch. Force use `options.windowBits` if passed.\n // Required to always use max window size by default.\n state.dmax = 1 << state.wbits;\n //state.dmax = 1 << len;\n\n //Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = hold & 0x200 ? DICTID : TYPE$1;\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n break;\n case FLAGS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.flags = hold;\n if ((state.flags & 0xff) !== Z_DEFLATED$2) {\n strm.msg = 'unknown compression method';\n state.mode = BAD$1;\n break;\n }\n if (state.flags & 0xe000) {\n strm.msg = 'unknown header flags set';\n state.mode = BAD$1;\n break;\n }\n if (state.head) {\n state.head.text = ((hold >> 8) & 1);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = TIME;\n /* falls through */\n case TIME:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.time = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC4(state.check, hold)\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n hbuf[2] = (hold >>> 16) & 0xff;\n hbuf[3] = (hold >>> 24) & 0xff;\n state.check = crc32_1(state.check, hbuf, 4, 0);\n //===\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = OS;\n /* falls through */\n case OS:\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (state.head) {\n state.head.xflags = (hold & 0xff);\n state.head.os = (hold >> 8);\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = EXLEN;\n /* falls through */\n case EXLEN:\n if (state.flags & 0x0400) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length = hold;\n if (state.head) {\n state.head.extra_len = hold;\n }\n if (state.flags & 0x0200) {\n //=== CRC2(state.check, hold);\n hbuf[0] = hold & 0xff;\n hbuf[1] = (hold >>> 8) & 0xff;\n state.check = crc32_1(state.check, hbuf, 2, 0);\n //===//\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n else if (state.head) {\n state.head.extra = null/*Z_NULL*/;\n }\n state.mode = EXTRA;\n /* falls through */\n case EXTRA:\n if (state.flags & 0x0400) {\n copy = state.length;\n if (copy > have) { copy = have; }\n if (copy) {\n if (state.head) {\n len = state.head.extra_len - state.length;\n if (!state.head.extra) {\n // Use untyped array for more convenient processing later\n state.head.extra = new Uint8Array(state.head.extra_len);\n }\n state.head.extra.set(\n input.subarray(\n next,\n // extra field is limited to 65536 bytes\n // - no need for additional size check\n next + copy\n ),\n /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/\n len\n );\n //zmemcpy(state.head.extra + len, next,\n // len + copy > state.head.extra_max ?\n // state.head.extra_max - len : copy);\n }\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n state.length -= copy;\n }\n if (state.length) { break inf_leave; }\n }\n state.length = 0;\n state.mode = NAME;\n /* falls through */\n case NAME:\n if (state.flags & 0x0800) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n // TODO: 2 or 1 bytes?\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.name_max*/)) {\n state.head.name += String.fromCharCode(len);\n }\n } while (len && copy < have);\n\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.name = null;\n }\n state.length = 0;\n state.mode = COMMENT;\n /* falls through */\n case COMMENT:\n if (state.flags & 0x1000) {\n if (have === 0) { break inf_leave; }\n copy = 0;\n do {\n len = input[next + copy++];\n /* use constant limit because in js we should not preallocate memory */\n if (state.head && len &&\n (state.length < 65536 /*state.head.comm_max*/)) {\n state.head.comment += String.fromCharCode(len);\n }\n } while (len && copy < have);\n if (state.flags & 0x0200) {\n state.check = crc32_1(state.check, input, copy, next);\n }\n have -= copy;\n next += copy;\n if (len) { break inf_leave; }\n }\n else if (state.head) {\n state.head.comment = null;\n }\n state.mode = HCRC;\n /* falls through */\n case HCRC:\n if (state.flags & 0x0200) {\n //=== NEEDBITS(16); */\n while (bits < 16) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.check & 0xffff)) {\n strm.msg = 'header crc mismatch';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n }\n if (state.head) {\n state.head.hcrc = ((state.flags >> 9) & 1);\n state.head.done = true;\n }\n strm.adler = state.check = 0;\n state.mode = TYPE$1;\n break;\n case DICTID:\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n strm.adler = state.check = zswap32(hold);\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = DICT;\n /* falls through */\n case DICT:\n if (state.havedict === 0) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n return Z_NEED_DICT;\n }\n strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;\n state.mode = TYPE$1;\n /* falls through */\n case TYPE$1:\n if (flush === Z_BLOCK$1 || flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case TYPEDO:\n if (state.last) {\n //--- BYTEBITS() ---//\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n state.mode = CHECK;\n break;\n }\n //=== NEEDBITS(3); */\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.last = (hold & 0x01)/*BITS(1)*/;\n //--- DROPBITS(1) ---//\n hold >>>= 1;\n bits -= 1;\n //---//\n\n switch ((hold & 0x03)/*BITS(2)*/) {\n case 0: /* stored block */\n //Tracev((stderr, \"inflate: stored block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n //Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = LEN_; /* decode codes */\n if (flush === Z_TREES) {\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break inf_leave;\n }\n break;\n case 2: /* dynamic block */\n //Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n // state.last ? \" (last)\" : \"\"));\n state.mode = TABLE;\n break;\n case 3:\n strm.msg = 'invalid block type';\n state.mode = BAD$1;\n }\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n break;\n case STORED:\n //--- BYTEBITS() ---// /* go to byte boundary */\n hold >>>= bits & 7;\n bits -= bits & 7;\n //---//\n //=== NEEDBITS(32); */\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {\n strm.msg = 'invalid stored block lengths';\n state.mode = BAD$1;\n break;\n }\n state.length = hold & 0xffff;\n //Tracev((stderr, \"inflate: stored length %u\\n\",\n // state.length));\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n state.mode = COPY_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case COPY_:\n state.mode = COPY;\n /* falls through */\n case COPY:\n copy = state.length;\n if (copy) {\n if (copy > have) { copy = have; }\n if (copy > left) { copy = left; }\n if (copy === 0) { break inf_leave; }\n //--- zmemcpy(put, next, copy); ---\n output.set(input.subarray(next, next + copy), put);\n //---//\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state.length -= copy;\n break;\n }\n //Tracev((stderr, \"inflate: stored end\\n\"));\n state.mode = TYPE$1;\n break;\n case TABLE:\n //=== NEEDBITS(14); */\n while (bits < 14) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;\n //--- DROPBITS(5) ---//\n hold >>>= 5;\n bits -= 5;\n //---//\n state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;\n //--- DROPBITS(4) ---//\n hold >>>= 4;\n bits -= 4;\n //---//\n//#ifndef PKZIP_BUG_WORKAROUND\n if (state.nlen > 286 || state.ndist > 30) {\n strm.msg = 'too many length or distance symbols';\n state.mode = BAD$1;\n break;\n }\n//#endif\n //Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state.have = 0;\n state.mode = LENLENS;\n /* falls through */\n case LENLENS:\n while (state.have < state.ncode) {\n //=== NEEDBITS(3);\n while (bits < 3) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n while (state.have < 19) {\n state.lens[order[state.have++]] = 0;\n }\n // We have separate tables & no pointers. 2 commented lines below not needed.\n //state.next = state.codes;\n //state.lencode = state.next;\n // Switch to use dynamic table\n state.lencode = state.lendyn;\n state.lenbits = 7;\n\n opts = { bits: state.lenbits };\n ret = inftrees(CODES$1, state.lens, 0, 19, state.lencode, 0, state.work, opts);\n state.lenbits = opts.bits;\n\n if (ret) {\n strm.msg = 'invalid code lengths set';\n state.mode = BAD$1;\n break;\n }\n //Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state.have = 0;\n state.mode = CODELENS;\n /* falls through */\n case CODELENS:\n while (state.have < state.nlen + state.ndist) {\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_val < 16) {\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.lens[state.have++] = here_val;\n }\n else {\n if (here_val === 16) {\n //=== NEEDBITS(here.bits + 2);\n n = here_bits + 2;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n if (state.have === 0) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD$1;\n break;\n }\n len = state.lens[state.have - 1];\n copy = 3 + (hold & 0x03);//BITS(2);\n //--- DROPBITS(2) ---//\n hold >>>= 2;\n bits -= 2;\n //---//\n }\n else if (here_val === 17) {\n //=== NEEDBITS(here.bits + 3);\n n = here_bits + 3;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 3 + (hold & 0x07);//BITS(3);\n //--- DROPBITS(3) ---//\n hold >>>= 3;\n bits -= 3;\n //---//\n }\n else {\n //=== NEEDBITS(here.bits + 7);\n n = here_bits + 7;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n len = 0;\n copy = 11 + (hold & 0x7f);//BITS(7);\n //--- DROPBITS(7) ---//\n hold >>>= 7;\n bits -= 7;\n //---//\n }\n if (state.have + copy > state.nlen + state.ndist) {\n strm.msg = 'invalid bit length repeat';\n state.mode = BAD$1;\n break;\n }\n while (copy--) {\n state.lens[state.have++] = len;\n }\n }\n }\n\n /* handle error breaks in while */\n if (state.mode === BAD$1) { break; }\n\n /* check for end-of-block code (better have one) */\n if (state.lens[256] === 0) {\n strm.msg = 'invalid code -- missing end-of-block';\n state.mode = BAD$1;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state.lenbits = 9;\n\n opts = { bits: state.lenbits };\n ret = inftrees(LENS$1, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.lenbits = opts.bits;\n // state.lencode = state.next;\n\n if (ret) {\n strm.msg = 'invalid literal/lengths set';\n state.mode = BAD$1;\n break;\n }\n\n state.distbits = 6;\n //state.distcode.copy(state.codes);\n // Switch to use dynamic table\n state.distcode = state.distdyn;\n opts = { bits: state.distbits };\n ret = inftrees(DISTS$1, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);\n // We have separate tables & no pointers. 2 commented lines below not needed.\n // state.next_index = opts.table_index;\n state.distbits = opts.bits;\n // state.distcode = state.next;\n\n if (ret) {\n strm.msg = 'invalid distances set';\n state.mode = BAD$1;\n break;\n }\n //Tracev((stderr, 'inflate: codes ok\\n'));\n state.mode = LEN_;\n if (flush === Z_TREES) { break inf_leave; }\n /* falls through */\n case LEN_:\n state.mode = LEN;\n /* falls through */\n case LEN:\n if (have >= 6 && left >= 258) {\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n inffast(strm, _out);\n //--- LOAD() ---\n put = strm.next_out;\n output = strm.output;\n left = strm.avail_out;\n next = strm.next_in;\n input = strm.input;\n have = strm.avail_in;\n hold = state.hold;\n bits = state.bits;\n //---\n\n if (state.mode === TYPE$1) {\n state.back = -1;\n }\n break;\n }\n state.back = 0;\n for (;;) {\n here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if (here_bits <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if (here_op && (here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.lencode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n state.length = here_val;\n if (here_op === 0) {\n //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n // \"inflate: literal '%c'\\n\" :\n // \"inflate: literal 0x%02x\\n\", here.val));\n state.mode = LIT;\n break;\n }\n if (here_op & 32) {\n //Tracevv((stderr, \"inflate: end of block\\n\"));\n state.back = -1;\n state.mode = TYPE$1;\n break;\n }\n if (here_op & 64) {\n strm.msg = 'invalid literal/length code';\n state.mode = BAD$1;\n break;\n }\n state.extra = here_op & 15;\n state.mode = LENEXT;\n /* falls through */\n case LENEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.length += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n //Tracevv((stderr, \"inflate: length %u\\n\", state.length));\n state.was = state.length;\n state.mode = DIST;\n /* falls through */\n case DIST:\n for (;;) {\n here = state.distcode[hold & ((1 << state.distbits) - 1)];/*BITS(state.distbits)*/\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n if ((here_op & 0xf0) === 0) {\n last_bits = here_bits;\n last_op = here_op;\n last_val = here_val;\n for (;;) {\n here = state.distcode[last_val +\n ((hold & ((1 << (last_bits + last_op)) - 1))/*BITS(last.bits + last.op)*/ >> last_bits)];\n here_bits = here >>> 24;\n here_op = (here >>> 16) & 0xff;\n here_val = here & 0xffff;\n\n if ((last_bits + here_bits) <= bits) { break; }\n //--- PULLBYTE() ---//\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n //---//\n }\n //--- DROPBITS(last.bits) ---//\n hold >>>= last_bits;\n bits -= last_bits;\n //---//\n state.back += last_bits;\n }\n //--- DROPBITS(here.bits) ---//\n hold >>>= here_bits;\n bits -= here_bits;\n //---//\n state.back += here_bits;\n if (here_op & 64) {\n strm.msg = 'invalid distance code';\n state.mode = BAD$1;\n break;\n }\n state.offset = here_val;\n state.extra = (here_op) & 15;\n state.mode = DISTEXT;\n /* falls through */\n case DISTEXT:\n if (state.extra) {\n //=== NEEDBITS(state.extra);\n n = state.extra;\n while (bits < n) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n state.offset += hold & ((1 << state.extra) - 1)/*BITS(state.extra)*/;\n //--- DROPBITS(state.extra) ---//\n hold >>>= state.extra;\n bits -= state.extra;\n //---//\n state.back += state.extra;\n }\n//#ifdef INFLATE_STRICT\n if (state.offset > state.dmax) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break;\n }\n//#endif\n //Tracevv((stderr, \"inflate: distance %u\\n\", state.offset));\n state.mode = MATCH;\n /* falls through */\n case MATCH:\n if (left === 0) { break inf_leave; }\n copy = _out - left;\n if (state.offset > copy) { /* copy from window */\n copy = state.offset - copy;\n if (copy > state.whave) {\n if (state.sane) {\n strm.msg = 'invalid distance too far back';\n state.mode = BAD$1;\n break;\n }\n// (!) This block is disabled in zlib defaults,\n// don't enable it for binary compatibility\n//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n// Trace((stderr, \"inflate.c too far\\n\"));\n// copy -= state.whave;\n// if (copy > state.length) { copy = state.length; }\n// if (copy > left) { copy = left; }\n// left -= copy;\n// state.length -= copy;\n// do {\n// output[put++] = 0;\n// } while (--copy);\n// if (state.length === 0) { state.mode = LEN; }\n// break;\n//#endif\n }\n if (copy > state.wnext) {\n copy -= state.wnext;\n from = state.wsize - copy;\n }\n else {\n from = state.wnext - copy;\n }\n if (copy > state.length) { copy = state.length; }\n from_source = state.window;\n }\n else { /* copy from output */\n from_source = output;\n from = put - state.offset;\n copy = state.length;\n }\n if (copy > left) { copy = left; }\n left -= copy;\n state.length -= copy;\n do {\n output[put++] = from_source[from++];\n } while (--copy);\n if (state.length === 0) { state.mode = LEN; }\n break;\n case LIT:\n if (left === 0) { break inf_leave; }\n output[put++] = state.length;\n left--;\n state.mode = LEN;\n break;\n case CHECK:\n if (state.wrap) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n // Use '|' instead of '+' to make sure that result is signed\n hold |= input[next++] << bits;\n bits += 8;\n }\n //===//\n _out -= left;\n strm.total_out += _out;\n state.total += _out;\n if (_out) {\n strm.adler = state.check =\n /*UPDATE(state.check, put - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, put - _out) : adler32_1(state.check, output, _out, put - _out));\n\n }\n _out = left;\n // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too\n if ((state.flags ? hold : zswap32(hold)) !== state.check) {\n strm.msg = 'incorrect data check';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n state.mode = LENGTH;\n /* falls through */\n case LENGTH:\n if (state.wrap && state.flags) {\n //=== NEEDBITS(32);\n while (bits < 32) {\n if (have === 0) { break inf_leave; }\n have--;\n hold += input[next++] << bits;\n bits += 8;\n }\n //===//\n if (hold !== (state.total & 0xffffffff)) {\n strm.msg = 'incorrect length check';\n state.mode = BAD$1;\n break;\n }\n //=== INITBITS();\n hold = 0;\n bits = 0;\n //===//\n //Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n state.mode = DONE;\n /* falls through */\n case DONE:\n ret = Z_STREAM_END$2;\n break inf_leave;\n case BAD$1:\n ret = Z_DATA_ERROR$1;\n break inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* falls through */\n default:\n return Z_STREAM_ERROR$1;\n }\n }\n\n // inf_leave <- here is real place for \"goto inf_leave\", emulated via \"break inf_leave\"\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n\n //--- RESTORE() ---\n strm.next_out = put;\n strm.avail_out = left;\n strm.next_in = next;\n strm.avail_in = have;\n state.hold = hold;\n state.bits = bits;\n //---\n\n if (state.wsize || (_out !== strm.avail_out && state.mode < BAD$1 &&\n (state.mode < CHECK || flush !== Z_FINISH$2))) {\n if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ;\n }\n _in -= strm.avail_in;\n _out -= strm.avail_out;\n strm.total_in += _in;\n strm.total_out += _out;\n state.total += _out;\n if (state.wrap && _out) {\n strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/\n (state.flags ? crc32_1(state.check, output, _out, strm.next_out - _out) : adler32_1(state.check, output, _out, strm.next_out - _out));\n }\n strm.data_type = state.bits + (state.last ? 64 : 0) +\n (state.mode === TYPE$1 ? 128 : 0) +\n (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);\n if (((_in === 0 && _out === 0) || flush === Z_FINISH$2) && ret === Z_OK$2) {\n ret = Z_BUF_ERROR$1;\n }\n return ret;\n};\n\n\nconst inflateEnd = (strm) => {\n\n if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {\n return Z_STREAM_ERROR$1;\n }\n\n let state = strm.state;\n if (state.window) {\n state.window = null;\n }\n strm.state = null;\n return Z_OK$2;\n};\n\n\nconst inflateGetHeader = (strm, head) => {\n\n /* check state */\n if (!strm || !strm.state) { return Z_STREAM_ERROR$1; }\n const state = strm.state;\n if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR$1; }\n\n /* save header structure */\n state.head = head;\n head.done = false;\n return Z_OK$2;\n};\n\n\nconst inflateSetDictionary = (strm, dictionary) => {\n const dictLength = dictionary.length;\n\n let state;\n let dictid;\n let ret;\n\n /* check state */\n if (!strm /* == Z_NULL */ || !strm.state /* == Z_NULL */) { return Z_STREAM_ERROR$1; }\n state = strm.state;\n\n if (state.wrap !== 0 && state.mode !== DICT) {\n return Z_STREAM_ERROR$1;\n }\n\n /* check for correct dictionary identifier */\n if (state.mode === DICT) {\n dictid = 1; /* adler32(0, null, 0)*/\n /* dictid = adler32(dictid, dictionary, dictLength); */\n dictid = adler32_1(dictid, dictionary, dictLength, 0);\n if (dictid !== state.check) {\n return Z_DATA_ERROR$1;\n }\n }\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary, dictLength, dictLength);\n if (ret) {\n state.mode = MEM;\n return Z_MEM_ERROR;\n }\n state.havedict = 1;\n // Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK$2;\n};\n\n\nvar inflateReset_1 = inflateReset;\nvar inflateReset2_1 = inflateReset2;\nvar inflateResetKeep_1 = inflateResetKeep;\nvar inflateInit_1 = inflateInit;\nvar inflateInit2_1 = inflateInit2;\nvar inflate_2 = inflate;\nvar inflateEnd_1 = inflateEnd;\nvar inflateGetHeader_1 = inflateGetHeader;\nvar inflateSetDictionary_1 = inflateSetDictionary;\nvar inflateInfo = 'pako inflate (from Nodeca project)';\n\n/* Not implemented\nmodule.exports.inflateCopy = inflateCopy;\nmodule.exports.inflateGetDictionary = inflateGetDictionary;\nmodule.exports.inflateMark = inflateMark;\nmodule.exports.inflatePrime = inflatePrime;\nmodule.exports.inflateSync = inflateSync;\nmodule.exports.inflateSyncPoint = inflateSyncPoint;\nmodule.exports.inflateUndermine = inflateUndermine;\n*/\n\nvar inflate_1 = {\n\tinflateReset: inflateReset_1,\n\tinflateReset2: inflateReset2_1,\n\tinflateResetKeep: inflateResetKeep_1,\n\tinflateInit: inflateInit_1,\n\tinflateInit2: inflateInit2_1,\n\tinflate: inflate_2,\n\tinflateEnd: inflateEnd_1,\n\tinflateGetHeader: inflateGetHeader_1,\n\tinflateSetDictionary: inflateSetDictionary_1,\n\tinflateInfo: inflateInfo\n};\n\n// (C) 1995-2013 Jean-loup Gailly and Mark Adler\n// (C) 2014-2017 Vitaly Puzrin and Andrey Tupitsin\n//\n// This software is provided 'as-is', without any express or implied\n// warranty. In no event will the authors be held liable for any damages\n// arising from the use of this software.\n//\n// Permission is granted to anyone to use this software for any purpose,\n// including commercial applications, and to alter it and redistribute it\n// freely, subject to the following restrictions:\n//\n// 1. The origin of this software must not be misrepresented; you must not\n// claim that you wrote the original software. If you use this software\n// in a product, an acknowledgment in the product documentation would be\n// appreciated but is not required.\n// 2. Altered source versions must be plainly marked as such, and must not be\n// misrepresented as being the original software.\n// 3. This notice may not be removed or altered from any source distribution.\n\nfunction GZheader() {\n /* true if compressed data believed to be text */\n this.text = 0;\n /* modification time */\n this.time = 0;\n /* extra flags (not used when writing a gzip file) */\n this.xflags = 0;\n /* operating system */\n this.os = 0;\n /* pointer to extra field or Z_NULL if none */\n this.extra = null;\n /* extra field length (valid if extra != Z_NULL) */\n this.extra_len = 0; // Actually, we don't need it in JS,\n // but leave for few code modifications\n\n //\n // Setup limits is not necessary because in js we should not preallocate memory\n // for inflate use constant limit in 65536 bytes\n //\n\n /* space at extra (only when reading header) */\n // this.extra_max = 0;\n /* pointer to zero-terminated file name or Z_NULL */\n this.name = '';\n /* space at name (only when reading header) */\n // this.name_max = 0;\n /* pointer to zero-terminated comment or Z_NULL */\n this.comment = '';\n /* space at comment (only when reading header) */\n // this.comm_max = 0;\n /* true if there was or will be a header crc */\n this.hcrc = 0;\n /* true when done reading gzip header (not used when writing a gzip file) */\n this.done = false;\n}\n\nvar gzheader = GZheader;\n\nconst toString$1 = Object.prototype.toString;\n\n/* Public constants ==========================================================*/\n/* ===========================================================================*/\n\nconst {\n Z_NO_FLUSH: Z_NO_FLUSH$2, Z_FINISH: Z_FINISH$3,\n Z_OK: Z_OK$3, Z_STREAM_END: Z_STREAM_END$3, Z_NEED_DICT: Z_NEED_DICT$1, Z_STREAM_ERROR: Z_STREAM_ERROR$2, Z_DATA_ERROR: Z_DATA_ERROR$2, Z_MEM_ERROR: Z_MEM_ERROR$1\n} = constants;\n\n/* ===========================================================================*/\n\n\n/**\n * class Inflate\n *\n * Generic JS-style wrapper for zlib calls. If you don't need\n * streaming behaviour - use more simple functions: [[inflate]]\n * and [[inflateRaw]].\n **/\n\n/* internal\n * inflate.chunks -> Array\n *\n * Chunks of output data, if [[Inflate#onData]] not overridden.\n **/\n\n/**\n * Inflate.result -> Uint8Array|String\n *\n * Uncompressed result, generated by default [[Inflate#onData]]\n * and [[Inflate#onEnd]] handlers. Filled after you push last chunk\n * (call [[Inflate#push]] with `Z_FINISH` / `true` param).\n **/\n\n/**\n * Inflate.err -> Number\n *\n * Error code after inflate finished. 0 (Z_OK) on success.\n * Should be checked if broken data possible.\n **/\n\n/**\n * Inflate.msg -> String\n *\n * Error message, if [[Inflate.err]] != 0\n **/\n\n\n/**\n * new Inflate(options)\n * - options (Object): zlib inflate options.\n *\n * Creates new inflator instance with specified params. Throws exception\n * on bad params. Supported options:\n *\n * - `windowBits`\n * - `dictionary`\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information on these.\n *\n * Additional options, for internal needs:\n *\n * - `chunkSize` - size of generated data chunks (16K by default)\n * - `raw` (Boolean) - do raw inflate\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n * By default, when no options set, autodetect deflate/gzip data format via\n * wrapper header.\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako')\n * const chunk1 = new Uint8Array([1,2,3,4,5,6,7,8,9])\n * const chunk2 = new Uint8Array([10,11,12,13,14,15,16,17,18,19]);\n *\n * const inflate = new pako.Inflate({ level: 3});\n *\n * inflate.push(chunk1, false);\n * inflate.push(chunk2, true); // true -> last chunk\n *\n * if (inflate.err) { throw new Error(inflate.err); }\n *\n * console.log(inflate.result);\n * ```\n **/\nfunction Inflate(options) {\n this.options = common.assign({\n chunkSize: 1024 * 64,\n windowBits: 15,\n to: ''\n }, options || {});\n\n const opt = this.options;\n\n // Force window size for `raw` data, if not set directly,\n // because we have no header for autodetect.\n if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {\n opt.windowBits = -opt.windowBits;\n if (opt.windowBits === 0) { opt.windowBits = -15; }\n }\n\n // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate\n if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&\n !(options && options.windowBits)) {\n opt.windowBits += 32;\n }\n\n // Gzip header has no info about windows size, we can do autodetect only\n // for deflate. So, if window size not set, force it to max when gzip possible\n if ((opt.windowBits > 15) && (opt.windowBits < 48)) {\n // bit 3 (16) -> gzipped data\n // bit 4 (32) -> autodetect gzip/deflate\n if ((opt.windowBits & 15) === 0) {\n opt.windowBits |= 15;\n }\n }\n\n this.err = 0; // error code, if happens (0 = Z_OK)\n this.msg = ''; // error message\n this.ended = false; // used to avoid multiple onEnd() calls\n this.chunks = []; // chunks of compressed data\n\n this.strm = new zstream();\n this.strm.avail_out = 0;\n\n let status = inflate_1.inflateInit2(\n this.strm,\n opt.windowBits\n );\n\n if (status !== Z_OK$3) {\n throw new Error(messages[status]);\n }\n\n this.header = new gzheader();\n\n inflate_1.inflateGetHeader(this.strm, this.header);\n\n // Setup dictionary\n if (opt.dictionary) {\n // Convert data if needed\n if (typeof opt.dictionary === 'string') {\n opt.dictionary = strings.string2buf(opt.dictionary);\n } else if (toString$1.call(opt.dictionary) === '[object ArrayBuffer]') {\n opt.dictionary = new Uint8Array(opt.dictionary);\n }\n if (opt.raw) { //In raw mode we need to set the dictionary early\n status = inflate_1.inflateSetDictionary(this.strm, opt.dictionary);\n if (status !== Z_OK$3) {\n throw new Error(messages[status]);\n }\n }\n }\n}\n\n/**\n * Inflate#push(data[, flush_mode]) -> Boolean\n * - data (Uint8Array|ArrayBuffer): input data\n * - flush_mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE\n * flush modes. See constants. Skipped or `false` means Z_NO_FLUSH,\n * `true` means Z_FINISH.\n *\n * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with\n * new output chunks. Returns `true` on success. If end of stream detected,\n * [[Inflate#onEnd]] will be called.\n *\n * `flush_mode` is not needed for normal operation, because end of stream\n * detected automatically. You may try to use it for advanced things, but\n * this functionality was not tested.\n *\n * On fail call [[Inflate#onEnd]] with error code and return false.\n *\n * ##### Example\n *\n * ```javascript\n * push(chunk, false); // push one of data chunks\n * ...\n * push(chunk, true); // push last chunk\n * ```\n **/\nInflate.prototype.push = function (data, flush_mode) {\n const strm = this.strm;\n const chunkSize = this.options.chunkSize;\n const dictionary = this.options.dictionary;\n let status, _flush_mode, last_avail_out;\n\n if (this.ended) return false;\n\n if (flush_mode === ~~flush_mode) _flush_mode = flush_mode;\n else _flush_mode = flush_mode === true ? Z_FINISH$3 : Z_NO_FLUSH$2;\n\n // Convert data if needed\n if (toString$1.call(data) === '[object ArrayBuffer]') {\n strm.input = new Uint8Array(data);\n } else {\n strm.input = data;\n }\n\n strm.next_in = 0;\n strm.avail_in = strm.input.length;\n\n for (;;) {\n if (strm.avail_out === 0) {\n strm.output = new Uint8Array(chunkSize);\n strm.next_out = 0;\n strm.avail_out = chunkSize;\n }\n\n status = inflate_1.inflate(strm, _flush_mode);\n\n if (status === Z_NEED_DICT$1 && dictionary) {\n status = inflate_1.inflateSetDictionary(strm, dictionary);\n\n if (status === Z_OK$3) {\n status = inflate_1.inflate(strm, _flush_mode);\n } else if (status === Z_DATA_ERROR$2) {\n // Replace code with more verbose\n status = Z_NEED_DICT$1;\n }\n }\n\n // Skip snyc markers if more data follows and not raw mode\n while (strm.avail_in > 0 &&\n status === Z_STREAM_END$3 &&\n strm.state.wrap > 0 &&\n data[strm.next_in] !== 0)\n {\n inflate_1.inflateReset(strm);\n status = inflate_1.inflate(strm, _flush_mode);\n }\n\n switch (status) {\n case Z_STREAM_ERROR$2:\n case Z_DATA_ERROR$2:\n case Z_NEED_DICT$1:\n case Z_MEM_ERROR$1:\n this.onEnd(status);\n this.ended = true;\n return false;\n }\n\n // Remember real `avail_out` value, because we may patch out buffer content\n // to align utf8 strings boundaries.\n last_avail_out = strm.avail_out;\n\n if (strm.next_out) {\n if (strm.avail_out === 0 || status === Z_STREAM_END$3) {\n\n if (this.options.to === 'string') {\n\n let next_out_utf8 = strings.utf8border(strm.output, strm.next_out);\n\n let tail = strm.next_out - next_out_utf8;\n let utf8str = strings.buf2string(strm.output, next_out_utf8);\n\n // move tail & realign counters\n strm.next_out = tail;\n strm.avail_out = chunkSize - tail;\n if (tail) strm.output.set(strm.output.subarray(next_out_utf8, next_out_utf8 + tail), 0);\n\n this.onData(utf8str);\n\n } else {\n this.onData(strm.output.length === strm.next_out ? strm.output : strm.output.subarray(0, strm.next_out));\n }\n }\n }\n\n // Must repeat iteration if out buffer is full\n if (status === Z_OK$3 && last_avail_out === 0) continue;\n\n // Finalize if end of stream reached.\n if (status === Z_STREAM_END$3) {\n status = inflate_1.inflateEnd(this.strm);\n this.onEnd(status);\n this.ended = true;\n return true;\n }\n\n if (strm.avail_in === 0) break;\n }\n\n return true;\n};\n\n\n/**\n * Inflate#onData(chunk) -> Void\n * - chunk (Uint8Array|String): output data. When string output requested,\n * each chunk will be string.\n *\n * By default, stores data blocks in `chunks[]` property and glue\n * those in `onEnd`. Override this handler, if you need another behaviour.\n **/\nInflate.prototype.onData = function (chunk) {\n this.chunks.push(chunk);\n};\n\n\n/**\n * Inflate#onEnd(status) -> Void\n * - status (Number): inflate status. 0 (Z_OK) on success,\n * other if not.\n *\n * Called either after you tell inflate that the input stream is\n * complete (Z_FINISH). By default - join collected chunks,\n * free memory and fill `results` / `err` properties.\n **/\nInflate.prototype.onEnd = function (status) {\n // On success - join\n if (status === Z_OK$3) {\n if (this.options.to === 'string') {\n this.result = this.chunks.join('');\n } else {\n this.result = common.flattenChunks(this.chunks);\n }\n }\n this.chunks = [];\n this.err = status;\n this.msg = this.strm.msg;\n};\n\n\n/**\n * inflate(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Decompress `data` with inflate/ungzip and `options`. Autodetect\n * format via wrapper header by default. That's why we don't provide\n * separate `ungzip` method.\n *\n * Supported options are:\n *\n * - windowBits\n *\n * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)\n * for more information.\n *\n * Sugar (options):\n *\n * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify\n * negative windowBits implicitly.\n * - `to` (String) - if equal to 'string', then result will be converted\n * from utf8 to utf16 (javascript) string. When string output requested,\n * chunk length can differ from `chunkSize`, depending on content.\n *\n *\n * ##### Example:\n *\n * ```javascript\n * const pako = require('pako');\n * const input = pako.deflate(new Uint8Array([1,2,3,4,5,6,7,8,9]));\n * let output;\n *\n * try {\n * output = pako.inflate(input);\n * } catch (err)\n * console.log(err);\n * }\n * ```\n **/\nfunction inflate$1(input, options) {\n const inflator = new Inflate(options);\n\n inflator.push(input);\n\n // That will never happens, if you don't cheat with options :)\n if (inflator.err) throw inflator.msg || messages[inflator.err];\n\n return inflator.result;\n}\n\n\n/**\n * inflateRaw(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * The same as [[inflate]], but creates raw data, without wrapper\n * (header and adler32 crc).\n **/\nfunction inflateRaw(input, options) {\n options = options || {};\n options.raw = true;\n return inflate$1(input, options);\n}\n\n\n/**\n * ungzip(data[, options]) -> Uint8Array|String\n * - data (Uint8Array): input data to decompress.\n * - options (Object): zlib inflate options.\n *\n * Just shortcut to [[inflate]], because it autodetects format\n * by header.content. Done for convenience.\n **/\n\n\nvar Inflate_1 = Inflate;\nvar inflate_2$1 = inflate$1;\nvar inflateRaw_1 = inflateRaw;\nvar ungzip = inflate$1;\nvar constants$2 = constants;\n\nvar inflate_1$1 = {\n\tInflate: Inflate_1,\n\tinflate: inflate_2$1,\n\tinflateRaw: inflateRaw_1,\n\tungzip: ungzip,\n\tconstants: constants$2\n};\n\nconst { Deflate: Deflate$1, deflate: deflate$2, deflateRaw: deflateRaw$1, gzip: gzip$1 } = deflate_1$1;\n\nconst { Inflate: Inflate$1, inflate: inflate$2, inflateRaw: inflateRaw$1, ungzip: ungzip$1 } = inflate_1$1;\n\n\n\nvar Deflate_1$1 = Deflate$1;\nvar deflate_1$2 = deflate$2;\nvar deflateRaw_1$1 = deflateRaw$1;\nvar gzip_1$1 = gzip$1;\nvar Inflate_1$1 = Inflate$1;\nvar inflate_1$2 = inflate$2;\nvar inflateRaw_1$1 = inflateRaw$1;\nvar ungzip_1 = ungzip$1;\nvar constants_1 = constants;\n\nvar pako = {\n\tDeflate: Deflate_1$1,\n\tdeflate: deflate_1$2,\n\tdeflateRaw: deflateRaw_1$1,\n\tgzip: gzip_1$1,\n\tInflate: Inflate_1$1,\n\tinflate: inflate_1$2,\n\tinflateRaw: inflateRaw_1$1,\n\tungzip: ungzip_1,\n\tconstants: constants_1\n};\n\nexport default pako;\nexport { Deflate_1$1 as Deflate, Inflate_1$1 as Inflate, constants_1 as constants, deflate_1$2 as deflate, deflateRaw_1$1 as deflateRaw, gzip_1$1 as gzip, inflate_1$2 as inflate, inflateRaw_1$1 as inflateRaw, ungzip_1 as ungzip };\n","export const pngSignature = [137, 80, 78, 71, 13, 10, 26, 10];\nconst crcTable = [];\nfor (let n = 0; n < 256; n++) {\n let c = n;\n for (let k = 0; k < 8; k++) {\n if (c & 1) {\n c = 0xedb88320 ^ (c >>> 1);\n }\n else {\n c = c >>> 1;\n }\n }\n crcTable[n] = c;\n}\nconst initialCrc = 0xffffffff;\nfunction updateCrc(currentCrc, data, length) {\n let c = currentCrc;\n for (let n = 0; n < length; n++) {\n c = crcTable[(c ^ data[n]) & 0xff] ^ (c >>> 8);\n }\n return c;\n}\nexport function crc(data, length) {\n return (updateCrc(initialCrc, data, length) ^ initialCrc) >>> 0;\n}\n//# sourceMappingURL=common.js.map","export var ColorType;\n(function (ColorType) {\n ColorType[ColorType[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n ColorType[ColorType[\"GREYSCALE\"] = 0] = \"GREYSCALE\";\n ColorType[ColorType[\"TRUECOLOUR\"] = 2] = \"TRUECOLOUR\";\n ColorType[ColorType[\"INDEXED_COLOUR\"] = 3] = \"INDEXED_COLOUR\";\n ColorType[ColorType[\"GREYSCALE_ALPHA\"] = 4] = \"GREYSCALE_ALPHA\";\n ColorType[ColorType[\"TRUECOLOUR_ALPHA\"] = 6] = \"TRUECOLOUR_ALPHA\";\n})(ColorType || (ColorType = {}));\nexport var CompressionMethod;\n(function (CompressionMethod) {\n CompressionMethod[CompressionMethod[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n CompressionMethod[CompressionMethod[\"DEFLATE\"] = 0] = \"DEFLATE\";\n})(CompressionMethod || (CompressionMethod = {}));\nexport var FilterMethod;\n(function (FilterMethod) {\n FilterMethod[FilterMethod[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n FilterMethod[FilterMethod[\"ADAPTIVE\"] = 0] = \"ADAPTIVE\";\n})(FilterMethod || (FilterMethod = {}));\nexport var InterlaceMethod;\n(function (InterlaceMethod) {\n InterlaceMethod[InterlaceMethod[\"UNKNOWN\"] = -1] = \"UNKNOWN\";\n InterlaceMethod[InterlaceMethod[\"NO_INTERLACE\"] = 0] = \"NO_INTERLACE\";\n InterlaceMethod[InterlaceMethod[\"ADAM7\"] = 1] = \"ADAM7\";\n})(InterlaceMethod || (InterlaceMethod = {}));\n//# sourceMappingURL=internalTypes.js.map","import { IOBuffer } from 'iobuffer';\nimport { Inflate as Inflator } from 'pako';\nimport { pngSignature, crc } from './common';\nimport { ColorType, CompressionMethod, FilterMethod, InterlaceMethod, } from './internalTypes';\nconst empty = new Uint8Array(0);\nconst NULL = '\\0';\nconst uint16 = new Uint16Array([0x00ff]);\nconst uint8 = new Uint8Array(uint16.buffer);\nconst osIsLittleEndian = uint8[0] === 0xff;\nexport default class PNGDecoder extends IOBuffer {\n constructor(data, options = {}) {\n super(data);\n const { checkCrc = false } = options;\n this._checkCrc = checkCrc;\n this._inflator = new Inflator();\n this._png = {\n width: -1,\n height: -1,\n channels: -1,\n data: new Uint8Array(0),\n depth: 1,\n text: {},\n };\n this._end = false;\n this._hasPalette = false;\n this._palette = [];\n this._compressionMethod = CompressionMethod.UNKNOWN;\n this._filterMethod = FilterMethod.UNKNOWN;\n this._interlaceMethod = InterlaceMethod.UNKNOWN;\n this._colorType = -1;\n // PNG is always big endian\n // https://www.w3.org/TR/PNG/#7Integers-and-byte-order\n this.setBigEndian();\n }\n decode() {\n this.decodeSignature();\n while (!this._end) {\n this.decodeChunk();\n }\n this.decodeImage();\n return this._png;\n }\n // https://www.w3.org/TR/PNG/#5PNG-file-signature\n decodeSignature() {\n for (let i = 0; i < pngSignature.length; i++) {\n if (this.readUint8() !== pngSignature[i]) {\n throw new Error(`wrong PNG signature. Byte at ${i} should be ${pngSignature[i]}.`);\n }\n }\n }\n // https://www.w3.org/TR/PNG/#5Chunk-layout\n decodeChunk() {\n const length = this.readUint32();\n const type = this.readChars(4);\n const offset = this.offset;\n switch (type) {\n // 11.2 Critical chunks\n case 'IHDR': // 11.2.2 IHDR Image header\n this.decodeIHDR();\n break;\n case 'PLTE': // 11.2.3 PLTE Palette\n this.decodePLTE(length);\n break;\n case 'IDAT': // 11.2.4 IDAT Image data\n this.decodeIDAT(length);\n break;\n case 'IEND': // 11.2.5 IEND Image trailer\n this._end = true;\n break;\n // 11.3 Ancillary chunks\n case 'tRNS': // 11.3.2.1 tRNS Transparency\n this.decodetRNS(length);\n break;\n case 'tEXt': // 11.3.4.3 tEXt Textual data\n this.decodetEXt(length);\n break;\n case 'pHYs': // 11.3.5.3 pHYs Physical pixel dimensions\n this.decodepHYs();\n break;\n default:\n this.skip(length);\n break;\n }\n if (this.offset - offset !== length) {\n throw new Error(`Length mismatch while decoding chunk ${type}`);\n }\n if (this._checkCrc) {\n const expectedCrc = this.readUint32();\n const crcLength = length + 4; // includes type\n const actualCrc = crc(new Uint8Array(this.buffer, this.byteOffset + this.offset - crcLength - 4, crcLength), crcLength); // \"- 4\" because we already advanced by reading the CRC\n if (actualCrc !== expectedCrc) {\n throw new Error(`CRC mismatch for chunk ${type}. Expected ${expectedCrc}, found ${actualCrc}`);\n }\n }\n else {\n this.skip(4);\n }\n }\n // https://www.w3.org/TR/PNG/#11IHDR\n decodeIHDR() {\n const image = this._png;\n image.width = this.readUint32();\n image.height = this.readUint32();\n image.depth = checkBitDepth(this.readUint8());\n const colorType = this.readUint8();\n this._colorType = colorType;\n let channels;\n switch (colorType) {\n case ColorType.GREYSCALE:\n channels = 1;\n break;\n case ColorType.TRUECOLOUR:\n channels = 3;\n break;\n case ColorType.INDEXED_COLOUR:\n channels = 1;\n break;\n case ColorType.GREYSCALE_ALPHA:\n channels = 2;\n break;\n case ColorType.TRUECOLOUR_ALPHA:\n channels = 4;\n break;\n default:\n throw new Error(`Unknown color type: ${colorType}`);\n }\n this._png.channels = channels;\n this._compressionMethod = this.readUint8();\n if (this._compressionMethod !== CompressionMethod.DEFLATE) {\n throw new Error(`Unsupported compression method: ${this._compressionMethod}`);\n }\n this._filterMethod = this.readUint8();\n this._interlaceMethod = this.readUint8();\n }\n // https://www.w3.org/TR/PNG/#11PLTE\n decodePLTE(length) {\n if (length % 3 !== 0) {\n throw new RangeError(`PLTE field length must be a multiple of 3. Got ${length}`);\n }\n const l = length / 3;\n this._hasPalette = true;\n const palette = [];\n this._palette = palette;\n for (let i = 0; i < l; i++) {\n palette.push([this.readUint8(), this.readUint8(), this.readUint8()]);\n }\n }\n // https://www.w3.org/TR/PNG/#11IDAT\n decodeIDAT(length) {\n this._inflator.push(new Uint8Array(this.buffer, this.offset + this.byteOffset, length));\n this.skip(length);\n }\n // https://www.w3.org/TR/PNG/#11tRNS\n decodetRNS(length) {\n // TODO: support other color types.\n if (this._colorType === 3) {\n if (length > this._palette.length) {\n throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${length} vs ${this._palette.length})`);\n }\n let i = 0;\n for (; i < length; i++) {\n const alpha = this.readByte();\n this._palette[i].push(alpha);\n }\n for (; i < this._palette.length; i++) {\n this._palette[i].push(255);\n }\n }\n }\n // https://www.w3.org/TR/PNG/#11tEXt\n decodetEXt(length) {\n let keyword = '';\n let char;\n while ((char = this.readChar()) !== NULL) {\n keyword += char;\n }\n this._png.text[keyword] = this.readChars(length - keyword.length - 1);\n }\n // https://www.w3.org/TR/PNG/#11pHYs\n decodepHYs() {\n const ppuX = this.readUint32();\n const ppuY = this.readUint32();\n const unitSpecifier = this.readByte();\n this._png.resolution = { x: ppuX, y: ppuY, unit: unitSpecifier };\n }\n decodeImage() {\n if (this._inflator.err) {\n throw new Error(`Error while decompressing the data: ${this._inflator.err}`);\n }\n const data = this._inflator.result;\n if (this._filterMethod !== FilterMethod.ADAPTIVE) {\n throw new Error(`Filter method ${this._filterMethod} not supported`);\n }\n if (this._interlaceMethod === InterlaceMethod.NO_INTERLACE) {\n this.decodeInterlaceNull(data);\n }\n else {\n throw new Error(`Interlace method ${this._interlaceMethod} not supported`);\n }\n }\n decodeInterlaceNull(data) {\n const height = this._png.height;\n const bytesPerPixel = (this._png.channels * this._png.depth) / 8;\n const bytesPerLine = this._png.width * bytesPerPixel;\n const newData = new Uint8Array(this._png.height * bytesPerLine);\n let prevLine = empty;\n let offset = 0;\n let currentLine;\n let newLine;\n for (let i = 0; i < height; i++) {\n currentLine = data.subarray(offset + 1, offset + 1 + bytesPerLine);\n newLine = newData.subarray(i * bytesPerLine, (i + 1) * bytesPerLine);\n switch (data[offset]) {\n case 0:\n unfilterNone(currentLine, newLine, bytesPerLine);\n break;\n case 1:\n unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel);\n break;\n case 2:\n unfilterUp(currentLine, newLine, prevLine, bytesPerLine);\n break;\n case 3:\n unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);\n break;\n case 4:\n unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel);\n break;\n default:\n throw new Error(`Unsupported filter: ${data[offset]}`);\n }\n prevLine = newLine;\n offset += bytesPerLine + 1;\n }\n if (this._hasPalette) {\n this._png.palette = this._palette;\n }\n if (this._png.depth === 16) {\n const uint16Data = new Uint16Array(newData.buffer);\n if (osIsLittleEndian) {\n for (let k = 0; k < uint16Data.length; k++) {\n // PNG is always big endian. Swap the bytes.\n uint16Data[k] = swap16(uint16Data[k]);\n }\n }\n this._png.data = uint16Data;\n }\n else {\n this._png.data = newData;\n }\n }\n}\nfunction unfilterNone(currentLine, newLine, bytesPerLine) {\n for (let i = 0; i < bytesPerLine; i++) {\n newLine[i] = currentLine[i];\n }\n}\nfunction unfilterSub(currentLine, newLine, bytesPerLine, bytesPerPixel) {\n let i = 0;\n for (; i < bytesPerPixel; i++) {\n // just copy first bytes\n newLine[i] = currentLine[i];\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] = (currentLine[i] + newLine[i - bytesPerPixel]) & 0xff;\n }\n}\nfunction unfilterUp(currentLine, newLine, prevLine, bytesPerLine) {\n let i = 0;\n if (prevLine.length === 0) {\n // just copy bytes for first line\n for (; i < bytesPerLine; i++) {\n newLine[i] = currentLine[i];\n }\n }\n else {\n for (; i < bytesPerLine; i++) {\n newLine[i] = (currentLine[i] + prevLine[i]) & 0xff;\n }\n }\n}\nfunction unfilterAverage(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {\n let i = 0;\n if (prevLine.length === 0) {\n for (; i < bytesPerPixel; i++) {\n newLine[i] = currentLine[i];\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] = (currentLine[i] + (newLine[i - bytesPerPixel] >> 1)) & 0xff;\n }\n }\n else {\n for (; i < bytesPerPixel; i++) {\n newLine[i] = (currentLine[i] + (prevLine[i] >> 1)) & 0xff;\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] =\n (currentLine[i] + ((newLine[i - bytesPerPixel] + prevLine[i]) >> 1)) &\n 0xff;\n }\n }\n}\nfunction unfilterPaeth(currentLine, newLine, prevLine, bytesPerLine, bytesPerPixel) {\n let i = 0;\n if (prevLine.length === 0) {\n for (; i < bytesPerPixel; i++) {\n newLine[i] = currentLine[i];\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] = (currentLine[i] + newLine[i - bytesPerPixel]) & 0xff;\n }\n }\n else {\n for (; i < bytesPerPixel; i++) {\n newLine[i] = (currentLine[i] + prevLine[i]) & 0xff;\n }\n for (; i < bytesPerLine; i++) {\n newLine[i] =\n (currentLine[i] +\n paethPredictor(newLine[i - bytesPerPixel], prevLine[i], prevLine[i - bytesPerPixel])) &\n 0xff;\n }\n }\n}\nfunction paethPredictor(a, b, c) {\n const p = a + b - c;\n const pa = Math.abs(p - a);\n const pb = Math.abs(p - b);\n const pc = Math.abs(p - c);\n if (pa <= pb && pa <= pc)\n return a;\n else if (pb <= pc)\n return b;\n else\n return c;\n}\nfunction swap16(val) {\n return ((val & 0xff) << 8) | ((val >> 8) & 0xff);\n}\nfunction checkBitDepth(value) {\n if (value !== 1 &&\n value !== 2 &&\n value !== 4 &&\n value !== 8 &&\n value !== 16) {\n throw new Error(`invalid bit depth: ${value}`);\n }\n return value;\n}\n//# sourceMappingURL=PNGDecoder.js.map","import { IOBuffer } from 'iobuffer';\nimport { deflate } from 'pako';\nimport { pngSignature, crc } from './common';\nimport { ColorType, CompressionMethod, FilterMethod, InterlaceMethod, } from './internalTypes';\nconst defaultZlibOptions = {\n level: 3,\n};\nexport default class PNGEncoder extends IOBuffer {\n constructor(data, options = {}) {\n super();\n this._colorType = ColorType.UNKNOWN;\n this._zlibOptions = Object.assign({}, defaultZlibOptions, options.zlib);\n this._png = this._checkData(data);\n this.setBigEndian();\n }\n encode() {\n this.encodeSignature();\n this.encodeIHDR();\n this.encodeData();\n this.encodeIEND();\n return this.toArray();\n }\n // https://www.w3.org/TR/PNG/#5PNG-file-signature\n encodeSignature() {\n this.writeBytes(pngSignature);\n }\n // https://www.w3.org/TR/PNG/#11IHDR\n encodeIHDR() {\n this.writeUint32(13);\n this.writeChars('IHDR');\n this.writeUint32(this._png.width);\n this.writeUint32(this._png.height);\n this.writeByte(this._png.depth);\n this.writeByte(this._colorType);\n this.writeByte(CompressionMethod.DEFLATE);\n this.writeByte(FilterMethod.ADAPTIVE);\n this.writeByte(InterlaceMethod.NO_INTERLACE);\n this.writeCrc(17);\n }\n // https://www.w3.org/TR/PNG/#11IEND\n encodeIEND() {\n this.writeUint32(0);\n this.writeChars('IEND');\n this.writeCrc(4);\n }\n // https://www.w3.org/TR/PNG/#11IDAT\n encodeIDAT(data) {\n this.writeUint32(data.length);\n this.writeChars('IDAT');\n this.writeBytes(data);\n this.writeCrc(data.length + 4);\n }\n encodeData() {\n const { width, height, channels, depth, data } = this._png;\n const slotsPerLine = channels * width;\n const newData = new IOBuffer().setBigEndian();\n let offset = 0;\n for (let i = 0; i < height; i++) {\n newData.writeByte(0); // no filter\n /* istanbul ignore else */\n if (depth === 8) {\n offset = writeDataBytes(data, newData, slotsPerLine, offset);\n }\n else if (depth === 16) {\n offset = writeDataUint16(data, newData, slotsPerLine, offset);\n }\n else {\n throw new Error('unreachable');\n }\n }\n const buffer = newData.toArray();\n const compressed = deflate(buffer, this._zlibOptions);\n this.encodeIDAT(compressed);\n }\n _checkData(data) {\n const { colorType, channels, depth } = getColorType(data);\n const png = {\n width: checkInteger(data.width, 'width'),\n height: checkInteger(data.height, 'height'),\n channels: channels,\n data: data.data,\n depth: depth,\n text: {},\n };\n this._colorType = colorType;\n const expectedSize = png.width * png.height * channels;\n if (png.data.length !== expectedSize) {\n throw new RangeError(`wrong data size. Found ${png.data.length}, expected ${expectedSize}`);\n }\n return png;\n }\n writeCrc(length) {\n this.writeUint32(crc(new Uint8Array(this.buffer, this.byteOffset + this.offset - length, length), length));\n }\n}\nfunction checkInteger(value, name) {\n if (Number.isInteger(value) && value > 0) {\n return value;\n }\n throw new TypeError(`${name} must be a positive integer`);\n}\nfunction getColorType(data) {\n const { channels = 4, depth = 8 } = data;\n if (channels !== 4 && channels !== 3 && channels !== 2 && channels !== 1) {\n throw new RangeError(`unsupported number of channels: ${channels}`);\n }\n if (depth !== 8 && depth !== 16) {\n throw new RangeError(`unsupported bit depth: ${depth}`);\n }\n const returnValue = { channels, depth, colorType: ColorType.UNKNOWN };\n switch (channels) {\n case 4:\n returnValue.colorType = ColorType.TRUECOLOUR_ALPHA;\n break;\n case 3:\n returnValue.colorType = ColorType.TRUECOLOUR;\n break;\n case 1:\n returnValue.colorType = ColorType.GREYSCALE;\n break;\n case 2:\n returnValue.colorType = ColorType.GREYSCALE_ALPHA;\n break;\n default:\n throw new Error('unsupported number of channels');\n }\n return returnValue;\n}\nfunction writeDataBytes(data, newData, slotsPerLine, offset) {\n for (let j = 0; j < slotsPerLine; j++) {\n newData.writeByte(data[offset++]);\n }\n return offset;\n}\nfunction writeDataUint16(data, newData, slotsPerLine, offset) {\n for (let j = 0; j < slotsPerLine; j++) {\n newData.writeUint16(data[offset++]);\n }\n return offset;\n}\n//# sourceMappingURL=PNGEncoder.js.map","import PNGDecoder from './PNGDecoder';\nimport PNGEncoder from './PNGEncoder';\nexport * from './types';\nfunction decodePNG(data, options) {\n const decoder = new PNGDecoder(data, options);\n return decoder.decode();\n}\nfunction encodePNG(png, options) {\n const encoder = new PNGEncoder(png, options);\n return encoder.encode();\n}\nexport { decodePNG as decode, encodePNG as encode };\n//# sourceMappingURL=index.js.map","/*\n Copyright (c) 2008, Adobe Systems Incorporated\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without \n modification, are permitted provided that the following conditions are\n met:\n\n * Redistributions of source code must retain the above copyright notice, \n this list of conditions and the following disclaimer.\n \n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the \n documentation and/or other materials provided with the distribution.\n \n * Neither the name of Adobe Systems Incorporated nor the names of its \n contributors may be used to endorse or promote products derived from \n this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR \n CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*/\n/*\nJPEG encoder ported to JavaScript and optimized by Andreas Ritter, www.bytestrom.eu, 11/2009\n\nBasic GUI blocking jpeg encoder\n*/\n\nvar btoa = btoa || function(buf) {\n return Buffer.from(buf).toString('base64');\n};\n\nfunction JPEGEncoder(quality) {\n var self = this;\n\tvar fround = Math.round;\n\tvar ffloor = Math.floor;\n\tvar YTable = new Array(64);\n\tvar UVTable = new Array(64);\n\tvar fdtbl_Y = new Array(64);\n\tvar fdtbl_UV = new Array(64);\n\tvar YDC_HT;\n\tvar UVDC_HT;\n\tvar YAC_HT;\n\tvar UVAC_HT;\n\t\n\tvar bitcode = new Array(65535);\n\tvar category = new Array(65535);\n\tvar outputfDCTQuant = new Array(64);\n\tvar DU = new Array(64);\n\tvar byteout = [];\n\tvar bytenew = 0;\n\tvar bytepos = 7;\n\t\n\tvar YDU = new Array(64);\n\tvar UDU = new Array(64);\n\tvar VDU = new Array(64);\n\tvar clt = new Array(256);\n\tvar RGB_YUV_TABLE = new Array(2048);\n\tvar currentQuality;\n\t\n\tvar ZigZag = [\n\t\t\t 0, 1, 5, 6,14,15,27,28,\n\t\t\t 2, 4, 7,13,16,26,29,42,\n\t\t\t 3, 8,12,17,25,30,41,43,\n\t\t\t 9,11,18,24,31,40,44,53,\n\t\t\t10,19,23,32,39,45,52,54,\n\t\t\t20,22,33,38,46,51,55,60,\n\t\t\t21,34,37,47,50,56,59,61,\n\t\t\t35,36,48,49,57,58,62,63\n\t\t];\n\t\n\tvar std_dc_luminance_nrcodes = [0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0];\n\tvar std_dc_luminance_values = [0,1,2,3,4,5,6,7,8,9,10,11];\n\tvar std_ac_luminance_nrcodes = [0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d];\n\tvar std_ac_luminance_values = [\n\t\t\t0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,\n\t\t\t0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,\n\t\t\t0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,\n\t\t\t0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,\n\t\t\t0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,\n\t\t\t0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,\n\t\t\t0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,\n\t\t\t0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,\n\t\t\t0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,\n\t\t\t0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,\n\t\t\t0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,\n\t\t\t0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,\n\t\t\t0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,\n\t\t\t0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,\n\t\t\t0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,\n\t\t\t0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,\n\t\t\t0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,\n\t\t\t0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,\n\t\t\t0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,\n\t\t\t0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,\n\t\t\t0xf9,0xfa\n\t\t];\n\t\n\tvar std_dc_chrominance_nrcodes = [0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0];\n\tvar std_dc_chrominance_values = [0,1,2,3,4,5,6,7,8,9,10,11];\n\tvar std_ac_chrominance_nrcodes = [0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77];\n\tvar std_ac_chrominance_values = [\n\t\t\t0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,\n\t\t\t0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,\n\t\t\t0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,\n\t\t\t0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,\n\t\t\t0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,\n\t\t\t0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,\n\t\t\t0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,\n\t\t\t0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,\n\t\t\t0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,\n\t\t\t0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,\n\t\t\t0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,\n\t\t\t0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,\n\t\t\t0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,\n\t\t\t0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,\n\t\t\t0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,\n\t\t\t0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,\n\t\t\t0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,\n\t\t\t0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,\n\t\t\t0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,\n\t\t\t0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,\n\t\t\t0xf9,0xfa\n\t\t];\n\t\n\tfunction initQuantTables(sf){\n\t\t\tvar YQT = [\n\t\t\t\t16, 11, 10, 16, 24, 40, 51, 61,\n\t\t\t\t12, 12, 14, 19, 26, 58, 60, 55,\n\t\t\t\t14, 13, 16, 24, 40, 57, 69, 56,\n\t\t\t\t14, 17, 22, 29, 51, 87, 80, 62,\n\t\t\t\t18, 22, 37, 56, 68,109,103, 77,\n\t\t\t\t24, 35, 55, 64, 81,104,113, 92,\n\t\t\t\t49, 64, 78, 87,103,121,120,101,\n\t\t\t\t72, 92, 95, 98,112,100,103, 99\n\t\t\t];\n\t\t\t\n\t\t\tfor (var i = 0; i < 64; i++) {\n\t\t\t\tvar t = ffloor((YQT[i]*sf+50)/100);\n\t\t\t\tif (t < 1) {\n\t\t\t\t\tt = 1;\n\t\t\t\t} else if (t > 255) {\n\t\t\t\t\tt = 255;\n\t\t\t\t}\n\t\t\t\tYTable[ZigZag[i]] = t;\n\t\t\t}\n\t\t\tvar UVQT = [\n\t\t\t\t17, 18, 24, 47, 99, 99, 99, 99,\n\t\t\t\t18, 21, 26, 66, 99, 99, 99, 99,\n\t\t\t\t24, 26, 56, 99, 99, 99, 99, 99,\n\t\t\t\t47, 66, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99,\n\t\t\t\t99, 99, 99, 99, 99, 99, 99, 99\n\t\t\t];\n\t\t\tfor (var j = 0; j < 64; j++) {\n\t\t\t\tvar u = ffloor((UVQT[j]*sf+50)/100);\n\t\t\t\tif (u < 1) {\n\t\t\t\t\tu = 1;\n\t\t\t\t} else if (u > 255) {\n\t\t\t\t\tu = 255;\n\t\t\t\t}\n\t\t\t\tUVTable[ZigZag[j]] = u;\n\t\t\t}\n\t\t\tvar aasf = [\n\t\t\t\t1.0, 1.387039845, 1.306562965, 1.175875602,\n\t\t\t\t1.0, 0.785694958, 0.541196100, 0.275899379\n\t\t\t];\n\t\t\tvar k = 0;\n\t\t\tfor (var row = 0; row < 8; row++)\n\t\t\t{\n\t\t\t\tfor (var col = 0; col < 8; col++)\n\t\t\t\t{\n\t\t\t\t\tfdtbl_Y[k] = (1.0 / (YTable [ZigZag[k]] * aasf[row] * aasf[col] * 8.0));\n\t\t\t\t\tfdtbl_UV[k] = (1.0 / (UVTable[ZigZag[k]] * aasf[row] * aasf[col] * 8.0));\n\t\t\t\t\tk++;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\t\n\t\tfunction computeHuffmanTbl(nrcodes, std_table){\n\t\t\tvar codevalue = 0;\n\t\t\tvar pos_in_table = 0;\n\t\t\tvar HT = new Array();\n\t\t\tfor (var k = 1; k <= 16; k++) {\n\t\t\t\tfor (var j = 1; j <= nrcodes[k]; j++) {\n\t\t\t\t\tHT[std_table[pos_in_table]] = [];\n\t\t\t\t\tHT[std_table[pos_in_table]][0] = codevalue;\n\t\t\t\t\tHT[std_table[pos_in_table]][1] = k;\n\t\t\t\t\tpos_in_table++;\n\t\t\t\t\tcodevalue++;\n\t\t\t\t}\n\t\t\t\tcodevalue*=2;\n\t\t\t}\n\t\t\treturn HT;\n\t\t}\n\t\t\n\t\tfunction initHuffmanTbl()\n\t\t{\n\t\t\tYDC_HT = computeHuffmanTbl(std_dc_luminance_nrcodes,std_dc_luminance_values);\n\t\t\tUVDC_HT = computeHuffmanTbl(std_dc_chrominance_nrcodes,std_dc_chrominance_values);\n\t\t\tYAC_HT = computeHuffmanTbl(std_ac_luminance_nrcodes,std_ac_luminance_values);\n\t\t\tUVAC_HT = computeHuffmanTbl(std_ac_chrominance_nrcodes,std_ac_chrominance_values);\n\t\t}\n\t\n\t\tfunction initCategoryNumber()\n\t\t{\n\t\t\tvar nrlower = 1;\n\t\t\tvar nrupper = 2;\n\t\t\tfor (var cat = 1; cat <= 15; cat++) {\n\t\t\t\t//Positive numbers\n\t\t\t\tfor (var nr = nrlower; nr>0] \t= 38470 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+ 512)>>0] \t= 7471 * i + 0x8000;\n\t\t\t\tRGB_YUV_TABLE[(i+ 768)>>0] \t= -11059 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1024)>>0] \t= -21709 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1280)>>0] \t= 32768 * i + 0x807FFF;\n\t\t\t\tRGB_YUV_TABLE[(i+1536)>>0] \t= -27439 * i;\n\t\t\t\tRGB_YUV_TABLE[(i+1792)>>0] \t= - 5329 * i;\n\t\t\t}\n\t\t}\n\t\t\n\t\t// IO functions\n\t\tfunction writeBits(bs)\n\t\t{\n\t\t\tvar value = bs[0];\n\t\t\tvar posval = bs[1]-1;\n\t\t\twhile ( posval >= 0 ) {\n\t\t\t\tif (value & (1 << posval) ) {\n\t\t\t\t\tbytenew |= (1 << bytepos);\n\t\t\t\t}\n\t\t\t\tposval--;\n\t\t\t\tbytepos--;\n\t\t\t\tif (bytepos < 0) {\n\t\t\t\t\tif (bytenew == 0xFF) {\n\t\t\t\t\t\twriteByte(0xFF);\n\t\t\t\t\t\twriteByte(0);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\twriteByte(bytenew);\n\t\t\t\t\t}\n\t\t\t\t\tbytepos=7;\n\t\t\t\t\tbytenew=0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeByte(value)\n\t\t{\n\t\t\t//byteout.push(clt[value]); // write char directly instead of converting later\n byteout.push(value);\n\t\t}\n\t\n\t\tfunction writeWord(value)\n\t\t{\n\t\t\twriteByte((value>>8)&0xFF);\n\t\t\twriteByte((value )&0xFF);\n\t\t}\n\t\t\n\t\t// DCT & quantization core\n\t\tfunction fDCTQuant(data, fdtbl)\n\t\t{\n\t\t\tvar d0, d1, d2, d3, d4, d5, d6, d7;\n\t\t\t/* Pass 1: process rows. */\n\t\t\tvar dataOff=0;\n\t\t\tvar i;\n\t\t\tvar I8 = 8;\n\t\t\tvar I64 = 64;\n\t\t\tfor (i=0; i 0.0) ? ((fDCTQuant + 0.5)|0) : ((fDCTQuant - 0.5)|0);\n\t\t\t\t//outputfDCTQuant[i] = fround(fDCTQuant);\n\n\t\t\t}\n\t\t\treturn outputfDCTQuant;\n\t\t}\n\t\t\n\t\tfunction writeAPP0()\n\t\t{\n\t\t\twriteWord(0xFFE0); // marker\n\t\t\twriteWord(16); // length\n\t\t\twriteByte(0x4A); // J\n\t\t\twriteByte(0x46); // F\n\t\t\twriteByte(0x49); // I\n\t\t\twriteByte(0x46); // F\n\t\t\twriteByte(0); // = \"JFIF\",'\\0'\n\t\t\twriteByte(1); // versionhi\n\t\t\twriteByte(1); // versionlo\n\t\t\twriteByte(0); // xyunits\n\t\t\twriteWord(1); // xdensity\n\t\t\twriteWord(1); // ydensity\n\t\t\twriteByte(0); // thumbnwidth\n\t\t\twriteByte(0); // thumbnheight\n\t\t}\n\n\t\tfunction writeAPP1(exifBuffer) {\n\t\t\tif (!exifBuffer) return;\n\n\t\t\twriteWord(0xFFE1); // APP1 marker\n\n\t\t\tif (exifBuffer[0] === 0x45 &&\n\t\t\t\t\texifBuffer[1] === 0x78 &&\n\t\t\t\t\texifBuffer[2] === 0x69 &&\n\t\t\t\t\texifBuffer[3] === 0x66) {\n\t\t\t\t// Buffer already starts with EXIF, just use it directly\n\t\t\t\twriteWord(exifBuffer.length + 2); // length is buffer + length itself!\n\t\t\t} else {\n\t\t\t\t// Buffer doesn't start with EXIF, write it for them\n\t\t\t\twriteWord(exifBuffer.length + 5 + 2); // length is buffer + EXIF\\0 + length itself!\n\t\t\t\twriteByte(0x45); // E\n\t\t\t\twriteByte(0x78); // X\n\t\t\t\twriteByte(0x69); // I\n\t\t\t\twriteByte(0x66); // F\n\t\t\t\twriteByte(0); // = \"EXIF\",'\\0'\n\t\t\t}\n\n\t\t\tfor (var i = 0; i < exifBuffer.length; i++) {\n\t\t\t\twriteByte(exifBuffer[i]);\n\t\t\t}\n\t\t}\n\n\t\tfunction writeSOF0(width, height)\n\t\t{\n\t\t\twriteWord(0xFFC0); // marker\n\t\t\twriteWord(17); // length, truecolor YUV JPG\n\t\t\twriteByte(8); // precision\n\t\t\twriteWord(height);\n\t\t\twriteWord(width);\n\t\t\twriteByte(3); // nrofcomponents\n\t\t\twriteByte(1); // IdY\n\t\t\twriteByte(0x11); // HVY\n\t\t\twriteByte(0); // QTY\n\t\t\twriteByte(2); // IdU\n\t\t\twriteByte(0x11); // HVU\n\t\t\twriteByte(1); // QTU\n\t\t\twriteByte(3); // IdV\n\t\t\twriteByte(0x11); // HVV\n\t\t\twriteByte(1); // QTV\n\t\t}\n\t\n\t\tfunction writeDQT()\n\t\t{\n\t\t\twriteWord(0xFFDB); // marker\n\t\t\twriteWord(132);\t // length\n\t\t\twriteByte(0);\n\t\t\tfor (var i=0; i<64; i++) {\n\t\t\t\twriteByte(YTable[i]);\n\t\t\t}\n\t\t\twriteByte(1);\n\t\t\tfor (var j=0; j<64; j++) {\n\t\t\t\twriteByte(UVTable[j]);\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeDHT()\n\t\t{\n\t\t\twriteWord(0xFFC4); // marker\n\t\t\twriteWord(0x01A2); // length\n\t\n\t\t\twriteByte(0); // HTYDCinfo\n\t\t\tfor (var i=0; i<16; i++) {\n\t\t\t\twriteByte(std_dc_luminance_nrcodes[i+1]);\n\t\t\t}\n\t\t\tfor (var j=0; j<=11; j++) {\n\t\t\t\twriteByte(std_dc_luminance_values[j]);\n\t\t\t}\n\t\n\t\t\twriteByte(0x10); // HTYACinfo\n\t\t\tfor (var k=0; k<16; k++) {\n\t\t\t\twriteByte(std_ac_luminance_nrcodes[k+1]);\n\t\t\t}\n\t\t\tfor (var l=0; l<=161; l++) {\n\t\t\t\twriteByte(std_ac_luminance_values[l]);\n\t\t\t}\n\t\n\t\t\twriteByte(1); // HTUDCinfo\n\t\t\tfor (var m=0; m<16; m++) {\n\t\t\t\twriteByte(std_dc_chrominance_nrcodes[m+1]);\n\t\t\t}\n\t\t\tfor (var n=0; n<=11; n++) {\n\t\t\t\twriteByte(std_dc_chrominance_values[n]);\n\t\t\t}\n\t\n\t\t\twriteByte(0x11); // HTUACinfo\n\t\t\tfor (var o=0; o<16; o++) {\n\t\t\t\twriteByte(std_ac_chrominance_nrcodes[o+1]);\n\t\t\t}\n\t\t\tfor (var p=0; p<=161; p++) {\n\t\t\t\twriteByte(std_ac_chrominance_values[p]);\n\t\t\t}\n\t\t}\n\t\n\t\tfunction writeSOS()\n\t\t{\n\t\t\twriteWord(0xFFDA); // marker\n\t\t\twriteWord(12); // length\n\t\t\twriteByte(3); // nrofcomponents\n\t\t\twriteByte(1); // IdY\n\t\t\twriteByte(0); // HTY\n\t\t\twriteByte(2); // IdU\n\t\t\twriteByte(0x11); // HTU\n\t\t\twriteByte(3); // IdV\n\t\t\twriteByte(0x11); // HTV\n\t\t\twriteByte(0); // Ss\n\t\t\twriteByte(0x3f); // Se\n\t\t\twriteByte(0); // Bf\n\t\t}\n\t\t\n\t\tfunction processDU(CDU, fdtbl, DC, HTDC, HTAC){\n\t\t\tvar EOB = HTAC[0x00];\n\t\t\tvar M16zeroes = HTAC[0xF0];\n\t\t\tvar pos;\n\t\t\tvar I16 = 16;\n\t\t\tvar I63 = 63;\n\t\t\tvar I64 = 64;\n\t\t\tvar DU_DCT = fDCTQuant(CDU, fdtbl);\n\t\t\t//ZigZag reorder\n\t\t\tfor (var j=0;j0)&&(DU[end0pos]==0); end0pos--) {};\n\t\t\t//end0pos = first element in reverse order !=0\n\t\t\tif ( end0pos == 0) {\n\t\t\t\twriteBits(EOB);\n\t\t\t\treturn DC;\n\t\t\t}\n\t\t\tvar i = 1;\n\t\t\tvar lng;\n\t\t\twhile ( i <= end0pos ) {\n\t\t\t\tvar startpos = i;\n\t\t\t\tfor (; (DU[i]==0) && (i<=end0pos); ++i) {}\n\t\t\t\tvar nrzeroes = i-startpos;\n\t\t\t\tif ( nrzeroes >= I16 ) {\n\t\t\t\t\tlng = nrzeroes>>4;\n\t\t\t\t\tfor (var nrmarker=1; nrmarker <= lng; ++nrmarker)\n\t\t\t\t\t\twriteBits(M16zeroes);\n\t\t\t\t\tnrzeroes = nrzeroes&0xF;\n\t\t\t\t}\n\t\t\t\tpos = 32767+DU[i];\n\t\t\t\twriteBits(HTAC[(nrzeroes<<4)+category[pos]]);\n\t\t\t\twriteBits(bitcode[pos]);\n\t\t\t\ti++;\n\t\t\t}\n\t\t\tif ( end0pos != I63 ) {\n\t\t\t\twriteBits(EOB);\n\t\t\t}\n\t\t\treturn DC;\n\t\t}\n\n\t\tfunction initCharLookupTable(){\n\t\t\tvar sfcc = String.fromCharCode;\n\t\t\tfor(var i=0; i < 256; i++){ ///// ACHTUNG // 255\n\t\t\t\tclt[i] = sfcc(i);\n\t\t\t}\n\t\t}\n\t\t\n\t\tthis.encode = function(image,quality) // image data object\n\t\t{\n\t\t\tvar time_start = new Date().getTime();\n\t\t\t\n\t\t\tif(quality) setQuality(quality);\n\t\t\t\n\t\t\t// Initialize bit writer\n\t\t\tbyteout = new Array();\n\t\t\tbytenew=0;\n\t\t\tbytepos=7;\n\t\n\t\t\t// Add JPEG headers\n\t\t\twriteWord(0xFFD8); // SOI\n\t\t\twriteAPP0();\n\t\t\twriteAPP1(image.exifBuffer);\n\t\t\twriteDQT();\n\t\t\twriteSOF0(image.width,image.height);\n\t\t\twriteDHT();\n\t\t\twriteSOS();\n\n\t\n\t\t\t// Encode 8x8 macroblocks\n\t\t\tvar DCY=0;\n\t\t\tvar DCU=0;\n\t\t\tvar DCV=0;\n\t\t\t\n\t\t\tbytenew=0;\n\t\t\tbytepos=7;\n\t\t\t\n\t\t\t\n\t\t\tthis.encode.displayName = \"_encode_\";\n\n\t\t\tvar imageData = image.data;\n\t\t\tvar width = image.width;\n\t\t\tvar height = image.height;\n\n\t\t\tvar quadWidth = width*4;\n\t\t\tvar tripleWidth = width*3;\n\t\t\t\n\t\t\tvar x, y = 0;\n\t\t\tvar r, g, b;\n\t\t\tvar start,p, col,row,pos;\n\t\t\twhile(y < height){\n\t\t\t\tx = 0;\n\t\t\t\twhile(x < quadWidth){\n\t\t\t\tstart = quadWidth * y + x;\n\t\t\t\tp = start;\n\t\t\t\tcol = -1;\n\t\t\t\trow = 0;\n\t\t\t\t\n\t\t\t\tfor(pos=0; pos < 64; pos++){\n\t\t\t\t\trow = pos >> 3;// /8\n\t\t\t\t\tcol = ( pos & 7 ) * 4; // %8\n\t\t\t\t\tp = start + ( row * quadWidth ) + col;\t\t\n\t\t\t\t\t\n\t\t\t\t\tif(y+row >= height){ // padding bottom\n\t\t\t\t\t\tp-= (quadWidth*(y+1+row-height));\n\t\t\t\t\t}\n\n\t\t\t\t\tif(x+col >= quadWidth){ // padding right\t\n\t\t\t\t\t\tp-= ((x+col) - quadWidth +4)\n\t\t\t\t\t}\n\t\t\t\t\t\n\t\t\t\t\tr = imageData[ p++ ];\n\t\t\t\t\tg = imageData[ p++ ];\n\t\t\t\t\tb = imageData[ p++ ];\n\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t/* // calculate YUV values dynamically\n\t\t\t\t\tYDU[pos]=((( 0.29900)*r+( 0.58700)*g+( 0.11400)*b))-128; //-0x80\n\t\t\t\t\tUDU[pos]=(((-0.16874)*r+(-0.33126)*g+( 0.50000)*b));\n\t\t\t\t\tVDU[pos]=((( 0.50000)*r+(-0.41869)*g+(-0.08131)*b));\n\t\t\t\t\t*/\n\t\t\t\t\t\n\t\t\t\t\t// use lookup table (slightly faster)\n\t\t\t\t\tYDU[pos] = ((RGB_YUV_TABLE[r] + RGB_YUV_TABLE[(g + 256)>>0] + RGB_YUV_TABLE[(b + 512)>>0]) >> 16)-128;\n\t\t\t\t\tUDU[pos] = ((RGB_YUV_TABLE[(r + 768)>>0] + RGB_YUV_TABLE[(g + 1024)>>0] + RGB_YUV_TABLE[(b + 1280)>>0]) >> 16)-128;\n\t\t\t\t\tVDU[pos] = ((RGB_YUV_TABLE[(r + 1280)>>0] + RGB_YUV_TABLE[(g + 1536)>>0] + RGB_YUV_TABLE[(b + 1792)>>0]) >> 16)-128;\n\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tDCY = processDU(YDU, fdtbl_Y, DCY, YDC_HT, YAC_HT);\n\t\t\t\tDCU = processDU(UDU, fdtbl_UV, DCU, UVDC_HT, UVAC_HT);\n\t\t\t\tDCV = processDU(VDU, fdtbl_UV, DCV, UVDC_HT, UVAC_HT);\n\t\t\t\tx+=32;\n\t\t\t\t}\n\t\t\t\ty+=8;\n\t\t\t}\n\t\t\t\n\t\t\t\n\t\t\t////////////////////////////////////////////////////////////////\n\t\n\t\t\t// Do the bit alignment of the EOI marker\n\t\t\tif ( bytepos >= 0 ) {\n\t\t\t\tvar fillbits = [];\n\t\t\t\tfillbits[1] = bytepos+1;\n\t\t\t\tfillbits[0] = (1<<(bytepos+1))-1;\n\t\t\t\twriteBits(fillbits);\n\t\t\t}\n\t\n\t\t\twriteWord(0xFFD9); //EOI\n\n\t\t\tif (typeof module === 'undefined') return new Uint8Array(byteout);\n return Buffer.from(byteout);\n\n\t\t\tvar jpegDataUri = 'data:image/jpeg;base64,' + btoa(byteout.join(''));\n\t\t\t\n\t\t\tbyteout = [];\n\t\t\t\n\t\t\t// benchmarking\n\t\t\tvar duration = new Date().getTime() - time_start;\n \t\t//console.log('Encoding time: '+ duration + 'ms');\n \t\t//\n\t\t\t\n\t\t\treturn jpegDataUri\t\t\t\n\t}\n\t\n\tfunction setQuality(quality){\n\t\tif (quality <= 0) {\n\t\t\tquality = 1;\n\t\t}\n\t\tif (quality > 100) {\n\t\t\tquality = 100;\n\t\t}\n\t\t\n\t\tif(currentQuality == quality) return // don't recalc if unchanged\n\t\t\n\t\tvar sf = 0;\n\t\tif (quality < 50) {\n\t\t\tsf = Math.floor(5000 / quality);\n\t\t} else {\n\t\t\tsf = Math.floor(200 - quality*2);\n\t\t}\n\t\t\n\t\tinitQuantTables(sf);\n\t\tcurrentQuality = quality;\n\t\t//console.log('Quality set to: '+quality +'%');\n\t}\n\t\n\tfunction init(){\n\t\tvar time_start = new Date().getTime();\n\t\tif(!quality) quality = 50;\n\t\t// Create tables\n\t\tinitCharLookupTable()\n\t\tinitHuffmanTbl();\n\t\tinitCategoryNumber();\n\t\tinitRGBYUVTable();\n\t\t\n\t\tsetQuality(quality);\n\t\tvar duration = new Date().getTime() - time_start;\n \t//console.log('Initialization '+ duration + 'ms');\n\t}\n\t\n\tinit();\n\t\n};\n\nif (typeof module !== 'undefined') {\n\tmodule.exports = encode;\n} else if (typeof window !== 'undefined') {\n\twindow['jpeg-js'] = window['jpeg-js'] || {};\n\twindow['jpeg-js'].encode = encode;\n}\n\nfunction encode(imgData, qu) {\n if (typeof qu === 'undefined') qu = 50;\n var encoder = new JPEGEncoder(qu);\n\tvar data = encoder.encode(imgData, qu);\n return {\n data: data,\n width: imgData.width,\n height: imgData.height\n };\n}\n\n// helper function to get the imageData of an existing image on the current page.\nfunction getImageDataFromImage(idOrElement){\n\tvar theImg = (typeof(idOrElement)=='string')? document.getElementById(idOrElement):idOrElement;\n\tvar cvs = document.createElement('canvas');\n\tcvs.width = theImg.width;\n\tcvs.height = theImg.height;\n\tvar ctx = cvs.getContext(\"2d\");\n\tctx.drawImage(theImg,0,0);\n\t\n\treturn (ctx.getImageData(0, 0, cvs.width, cvs.height));\n}\n","/* -*- tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- /\n/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */\n/*\n Copyright 2011 notmasteryet\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n*/\n\n// - The JPEG specification can be found in the ITU CCITT Recommendation T.81\n// (www.w3.org/Graphics/JPEG/itu-t81.pdf)\n// - The JFIF specification can be found in the JPEG File Interchange Format\n// (www.w3.org/Graphics/JPEG/jfif3.pdf)\n// - The Adobe Application-Specific JPEG markers in the Supporting the DCT Filters\n// in PostScript Level 2, Technical Note #5116\n// (partners.adobe.com/public/developer/en/ps/sdk/5116.DCT_Filter.pdf)\n\nvar JpegImage = (function jpegImage() {\n \"use strict\";\n var dctZigZag = new Int32Array([\n 0,\n 1, 8,\n 16, 9, 2,\n 3, 10, 17, 24,\n 32, 25, 18, 11, 4,\n 5, 12, 19, 26, 33, 40,\n 48, 41, 34, 27, 20, 13, 6,\n 7, 14, 21, 28, 35, 42, 49, 56,\n 57, 50, 43, 36, 29, 22, 15,\n 23, 30, 37, 44, 51, 58,\n 59, 52, 45, 38, 31,\n 39, 46, 53, 60,\n 61, 54, 47,\n 55, 62,\n 63\n ]);\n\n var dctCos1 = 4017 // cos(pi/16)\n var dctSin1 = 799 // sin(pi/16)\n var dctCos3 = 3406 // cos(3*pi/16)\n var dctSin3 = 2276 // sin(3*pi/16)\n var dctCos6 = 1567 // cos(6*pi/16)\n var dctSin6 = 3784 // sin(6*pi/16)\n var dctSqrt2 = 5793 // sqrt(2)\n var dctSqrt1d2 = 2896 // sqrt(2) / 2\n\n function constructor() {\n }\n\n function buildHuffmanTable(codeLengths, values) {\n var k = 0, code = [], i, j, length = 16;\n while (length > 0 && !codeLengths[length - 1])\n length--;\n code.push({children: [], index: 0});\n var p = code[0], q;\n for (i = 0; i < length; i++) {\n for (j = 0; j < codeLengths[i]; j++) {\n p = code.pop();\n p.children[p.index] = values[k];\n while (p.index > 0) {\n if (code.length === 0)\n throw new Error('Could not recreate Huffman Table');\n p = code.pop();\n }\n p.index++;\n code.push(p);\n while (code.length <= i) {\n code.push(q = {children: [], index: 0});\n p.children[p.index] = q.children;\n p = q;\n }\n k++;\n }\n if (i + 1 < length) {\n // p here points to last code\n code.push(q = {children: [], index: 0});\n p.children[p.index] = q.children;\n p = q;\n }\n }\n return code[0].children;\n }\n\n function decodeScan(data, offset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successivePrev, successive, opts) {\n var precision = frame.precision;\n var samplesPerLine = frame.samplesPerLine;\n var scanLines = frame.scanLines;\n var mcusPerLine = frame.mcusPerLine;\n var progressive = frame.progressive;\n var maxH = frame.maxH, maxV = frame.maxV;\n\n var startOffset = offset, bitsData = 0, bitsCount = 0;\n function readBit() {\n if (bitsCount > 0) {\n bitsCount--;\n return (bitsData >> bitsCount) & 1;\n }\n bitsData = data[offset++];\n if (bitsData == 0xFF) {\n var nextByte = data[offset++];\n if (nextByte) {\n throw new Error(\"unexpected marker: \" + ((bitsData << 8) | nextByte).toString(16));\n }\n // unstuff 0\n }\n bitsCount = 7;\n return bitsData >>> 7;\n }\n function decodeHuffman(tree) {\n var node = tree, bit;\n while ((bit = readBit()) !== null) {\n node = node[bit];\n if (typeof node === 'number')\n return node;\n if (typeof node !== 'object')\n throw new Error(\"invalid huffman sequence\");\n }\n return null;\n }\n function receive(length) {\n var n = 0;\n while (length > 0) {\n var bit = readBit();\n if (bit === null) return;\n n = (n << 1) | bit;\n length--;\n }\n return n;\n }\n function receiveAndExtend(length) {\n var n = receive(length);\n if (n >= 1 << (length - 1))\n return n;\n return n + (-1 << length) + 1;\n }\n function decodeBaseline(component, zz) {\n var t = decodeHuffman(component.huffmanTableDC);\n var diff = t === 0 ? 0 : receiveAndExtend(t);\n zz[0]= (component.pred += diff);\n var k = 1;\n while (k < 64) {\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15)\n break;\n k += 16;\n continue;\n }\n k += r;\n var z = dctZigZag[k];\n zz[z] = receiveAndExtend(s);\n k++;\n }\n }\n function decodeDCFirst(component, zz) {\n var t = decodeHuffman(component.huffmanTableDC);\n var diff = t === 0 ? 0 : (receiveAndExtend(t) << successive);\n zz[0] = (component.pred += diff);\n }\n function decodeDCSuccessive(component, zz) {\n zz[0] |= readBit() << successive;\n }\n var eobrun = 0;\n function decodeACFirst(component, zz) {\n if (eobrun > 0) {\n eobrun--;\n return;\n }\n var k = spectralStart, e = spectralEnd;\n while (k <= e) {\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r) - 1;\n break;\n }\n k += 16;\n continue;\n }\n k += r;\n var z = dctZigZag[k];\n zz[z] = receiveAndExtend(s) * (1 << successive);\n k++;\n }\n }\n var successiveACState = 0, successiveACNextValue;\n function decodeACSuccessive(component, zz) {\n var k = spectralStart, e = spectralEnd, r = 0;\n while (k <= e) {\n var z = dctZigZag[k];\n var direction = zz[z] < 0 ? -1 : 1;\n switch (successiveACState) {\n case 0: // initial state\n var rs = decodeHuffman(component.huffmanTableAC);\n var s = rs & 15, r = rs >> 4;\n if (s === 0) {\n if (r < 15) {\n eobrun = receive(r) + (1 << r);\n successiveACState = 4;\n } else {\n r = 16;\n successiveACState = 1;\n }\n } else {\n if (s !== 1)\n throw new Error(\"invalid ACn encoding\");\n successiveACNextValue = receiveAndExtend(s);\n successiveACState = r ? 2 : 3;\n }\n continue;\n case 1: // skipping r zero items\n case 2:\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n else {\n r--;\n if (r === 0)\n successiveACState = successiveACState == 2 ? 3 : 0;\n }\n break;\n case 3: // set value for a zero item\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n else {\n zz[z] = successiveACNextValue << successive;\n successiveACState = 0;\n }\n break;\n case 4: // eob\n if (zz[z])\n zz[z] += (readBit() << successive) * direction;\n break;\n }\n k++;\n }\n if (successiveACState === 4) {\n eobrun--;\n if (eobrun === 0)\n successiveACState = 0;\n }\n }\n function decodeMcu(component, decode, mcu, row, col) {\n var mcuRow = (mcu / mcusPerLine) | 0;\n var mcuCol = mcu % mcusPerLine;\n var blockRow = mcuRow * component.v + row;\n var blockCol = mcuCol * component.h + col;\n // If the block is missing and we're in tolerant mode, just skip it.\n if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)\n return;\n decode(component, component.blocks[blockRow][blockCol]);\n }\n function decodeBlock(component, decode, mcu) {\n var blockRow = (mcu / component.blocksPerLine) | 0;\n var blockCol = mcu % component.blocksPerLine;\n // If the block is missing and we're in tolerant mode, just skip it.\n if (component.blocks[blockRow] === undefined && opts.tolerantDecoding)\n return;\n decode(component, component.blocks[blockRow][blockCol]);\n }\n\n var componentsLength = components.length;\n var component, i, j, k, n;\n var decodeFn;\n if (progressive) {\n if (spectralStart === 0)\n decodeFn = successivePrev === 0 ? decodeDCFirst : decodeDCSuccessive;\n else\n decodeFn = successivePrev === 0 ? decodeACFirst : decodeACSuccessive;\n } else {\n decodeFn = decodeBaseline;\n }\n\n var mcu = 0, marker;\n var mcuExpected;\n if (componentsLength == 1) {\n mcuExpected = components[0].blocksPerLine * components[0].blocksPerColumn;\n } else {\n mcuExpected = mcusPerLine * frame.mcusPerColumn;\n }\n if (!resetInterval) resetInterval = mcuExpected;\n\n var h, v;\n while (mcu < mcuExpected) {\n // reset interval stuff\n for (i = 0; i < componentsLength; i++)\n components[i].pred = 0;\n eobrun = 0;\n\n if (componentsLength == 1) {\n component = components[0];\n for (n = 0; n < resetInterval; n++) {\n decodeBlock(component, decodeFn, mcu);\n mcu++;\n }\n } else {\n for (n = 0; n < resetInterval; n++) {\n for (i = 0; i < componentsLength; i++) {\n component = components[i];\n h = component.h;\n v = component.v;\n for (j = 0; j < v; j++) {\n for (k = 0; k < h; k++) {\n decodeMcu(component, decodeFn, mcu, j, k);\n }\n }\n }\n mcu++;\n\n // If we've reached our expected MCU's, stop decoding\n if (mcu === mcuExpected) break;\n }\n }\n\n if (mcu === mcuExpected) {\n // Skip trailing bytes at the end of the scan - until we reach the next marker\n do {\n if (data[offset] === 0xFF) {\n if (data[offset + 1] !== 0x00) {\n break;\n }\n }\n offset += 1;\n } while (offset < data.length - 2);\n }\n\n // find marker\n bitsCount = 0;\n marker = (data[offset] << 8) | data[offset + 1];\n if (marker < 0xFF00) {\n throw new Error(\"marker was not found\");\n }\n\n if (marker >= 0xFFD0 && marker <= 0xFFD7) { // RSTx\n offset += 2;\n }\n else\n break;\n }\n\n return offset - startOffset;\n }\n\n function buildComponentData(frame, component) {\n var lines = [];\n var blocksPerLine = component.blocksPerLine;\n var blocksPerColumn = component.blocksPerColumn;\n var samplesPerLine = blocksPerLine << 3;\n // Only 1 used per invocation of this function and garbage collected after invocation, so no need to account for its memory footprint.\n var R = new Int32Array(64), r = new Uint8Array(64);\n\n // A port of poppler's IDCT method which in turn is taken from:\n // Christoph Loeffler, Adriaan Ligtenberg, George S. Moschytz,\n // \"Practical Fast 1-D DCT Algorithms with 11 Multiplications\",\n // IEEE Intl. Conf. on Acoustics, Speech & Signal Processing, 1989,\n // 988-991.\n function quantizeAndInverse(zz, dataOut, dataIn) {\n var qt = component.quantizationTable;\n var v0, v1, v2, v3, v4, v5, v6, v7, t;\n var p = dataIn;\n var i;\n\n // dequant\n for (i = 0; i < 64; i++)\n p[i] = zz[i] * qt[i];\n\n // inverse DCT on rows\n for (i = 0; i < 8; ++i) {\n var row = 8 * i;\n\n // check for all-zero AC coefficients\n if (p[1 + row] == 0 && p[2 + row] == 0 && p[3 + row] == 0 &&\n p[4 + row] == 0 && p[5 + row] == 0 && p[6 + row] == 0 &&\n p[7 + row] == 0) {\n t = (dctSqrt2 * p[0 + row] + 512) >> 10;\n p[0 + row] = t;\n p[1 + row] = t;\n p[2 + row] = t;\n p[3 + row] = t;\n p[4 + row] = t;\n p[5 + row] = t;\n p[6 + row] = t;\n p[7 + row] = t;\n continue;\n }\n\n // stage 4\n v0 = (dctSqrt2 * p[0 + row] + 128) >> 8;\n v1 = (dctSqrt2 * p[4 + row] + 128) >> 8;\n v2 = p[2 + row];\n v3 = p[6 + row];\n v4 = (dctSqrt1d2 * (p[1 + row] - p[7 + row]) + 128) >> 8;\n v7 = (dctSqrt1d2 * (p[1 + row] + p[7 + row]) + 128) >> 8;\n v5 = p[3 + row] << 4;\n v6 = p[5 + row] << 4;\n\n // stage 3\n t = (v0 - v1+ 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = (v2 * dctSin6 + v3 * dctCos6 + 128) >> 8;\n v2 = (v2 * dctCos6 - v3 * dctSin6 + 128) >> 8;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;\n v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;\n v7 = t;\n t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;\n v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0 + row] = v0 + v7;\n p[7 + row] = v0 - v7;\n p[1 + row] = v1 + v6;\n p[6 + row] = v1 - v6;\n p[2 + row] = v2 + v5;\n p[5 + row] = v2 - v5;\n p[3 + row] = v3 + v4;\n p[4 + row] = v3 - v4;\n }\n\n // inverse DCT on columns\n for (i = 0; i < 8; ++i) {\n var col = i;\n\n // check for all-zero AC coefficients\n if (p[1*8 + col] == 0 && p[2*8 + col] == 0 && p[3*8 + col] == 0 &&\n p[4*8 + col] == 0 && p[5*8 + col] == 0 && p[6*8 + col] == 0 &&\n p[7*8 + col] == 0) {\n t = (dctSqrt2 * dataIn[i+0] + 8192) >> 14;\n p[0*8 + col] = t;\n p[1*8 + col] = t;\n p[2*8 + col] = t;\n p[3*8 + col] = t;\n p[4*8 + col] = t;\n p[5*8 + col] = t;\n p[6*8 + col] = t;\n p[7*8 + col] = t;\n continue;\n }\n\n // stage 4\n v0 = (dctSqrt2 * p[0*8 + col] + 2048) >> 12;\n v1 = (dctSqrt2 * p[4*8 + col] + 2048) >> 12;\n v2 = p[2*8 + col];\n v3 = p[6*8 + col];\n v4 = (dctSqrt1d2 * (p[1*8 + col] - p[7*8 + col]) + 2048) >> 12;\n v7 = (dctSqrt1d2 * (p[1*8 + col] + p[7*8 + col]) + 2048) >> 12;\n v5 = p[3*8 + col];\n v6 = p[5*8 + col];\n\n // stage 3\n t = (v0 - v1 + 1) >> 1;\n v0 = (v0 + v1 + 1) >> 1;\n v1 = t;\n t = (v2 * dctSin6 + v3 * dctCos6 + 2048) >> 12;\n v2 = (v2 * dctCos6 - v3 * dctSin6 + 2048) >> 12;\n v3 = t;\n t = (v4 - v6 + 1) >> 1;\n v4 = (v4 + v6 + 1) >> 1;\n v6 = t;\n t = (v7 + v5 + 1) >> 1;\n v5 = (v7 - v5 + 1) >> 1;\n v7 = t;\n\n // stage 2\n t = (v0 - v3 + 1) >> 1;\n v0 = (v0 + v3 + 1) >> 1;\n v3 = t;\n t = (v1 - v2 + 1) >> 1;\n v1 = (v1 + v2 + 1) >> 1;\n v2 = t;\n t = (v4 * dctSin3 + v7 * dctCos3 + 2048) >> 12;\n v4 = (v4 * dctCos3 - v7 * dctSin3 + 2048) >> 12;\n v7 = t;\n t = (v5 * dctSin1 + v6 * dctCos1 + 2048) >> 12;\n v5 = (v5 * dctCos1 - v6 * dctSin1 + 2048) >> 12;\n v6 = t;\n\n // stage 1\n p[0*8 + col] = v0 + v7;\n p[7*8 + col] = v0 - v7;\n p[1*8 + col] = v1 + v6;\n p[6*8 + col] = v1 - v6;\n p[2*8 + col] = v2 + v5;\n p[5*8 + col] = v2 - v5;\n p[3*8 + col] = v3 + v4;\n p[4*8 + col] = v3 - v4;\n }\n\n // convert to 8-bit integers\n for (i = 0; i < 64; ++i) {\n var sample = 128 + ((p[i] + 8) >> 4);\n dataOut[i] = sample < 0 ? 0 : sample > 0xFF ? 0xFF : sample;\n }\n }\n\n requestMemoryAllocation(samplesPerLine * blocksPerColumn * 8);\n\n var i, j;\n for (var blockRow = 0; blockRow < blocksPerColumn; blockRow++) {\n var scanLine = blockRow << 3;\n for (i = 0; i < 8; i++)\n lines.push(new Uint8Array(samplesPerLine));\n for (var blockCol = 0; blockCol < blocksPerLine; blockCol++) {\n quantizeAndInverse(component.blocks[blockRow][blockCol], r, R);\n\n var offset = 0, sample = blockCol << 3;\n for (j = 0; j < 8; j++) {\n var line = lines[scanLine + j];\n for (i = 0; i < 8; i++)\n line[sample + i] = r[offset++];\n }\n }\n }\n return lines;\n }\n\n function clampTo8bit(a) {\n return a < 0 ? 0 : a > 255 ? 255 : a;\n }\n\n constructor.prototype = {\n load: function load(path) {\n var xhr = new XMLHttpRequest();\n xhr.open(\"GET\", path, true);\n xhr.responseType = \"arraybuffer\";\n xhr.onload = (function() {\n // TODO catch parse error\n var data = new Uint8Array(xhr.response || xhr.mozResponseArrayBuffer);\n this.parse(data);\n if (this.onload)\n this.onload();\n }).bind(this);\n xhr.send(null);\n },\n parse: function parse(data) {\n var maxResolutionInPixels = this.opts.maxResolutionInMP * 1000 * 1000;\n var offset = 0, length = data.length;\n function readUint16() {\n var value = (data[offset] << 8) | data[offset + 1];\n offset += 2;\n return value;\n }\n function readDataBlock() {\n var length = readUint16();\n var array = data.subarray(offset, offset + length - 2);\n offset += array.length;\n return array;\n }\n function prepareComponents(frame) {\n var maxH = 0, maxV = 0;\n var component, componentId;\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n if (maxH < component.h) maxH = component.h;\n if (maxV < component.v) maxV = component.v;\n }\n }\n var mcusPerLine = Math.ceil(frame.samplesPerLine / 8 / maxH);\n var mcusPerColumn = Math.ceil(frame.scanLines / 8 / maxV);\n for (componentId in frame.components) {\n if (frame.components.hasOwnProperty(componentId)) {\n component = frame.components[componentId];\n var blocksPerLine = Math.ceil(Math.ceil(frame.samplesPerLine / 8) * component.h / maxH);\n var blocksPerColumn = Math.ceil(Math.ceil(frame.scanLines / 8) * component.v / maxV);\n var blocksPerLineForMcu = mcusPerLine * component.h;\n var blocksPerColumnForMcu = mcusPerColumn * component.v;\n var blocksToAllocate = blocksPerColumnForMcu * blocksPerLineForMcu;\n var blocks = [];\n\n // Each block is a Int32Array of length 64 (4 x 64 = 256 bytes)\n requestMemoryAllocation(blocksToAllocate * 256);\n\n for (var i = 0; i < blocksPerColumnForMcu; i++) {\n var row = [];\n for (var j = 0; j < blocksPerLineForMcu; j++)\n row.push(new Int32Array(64));\n blocks.push(row);\n }\n component.blocksPerLine = blocksPerLine;\n component.blocksPerColumn = blocksPerColumn;\n component.blocks = blocks;\n }\n }\n frame.maxH = maxH;\n frame.maxV = maxV;\n frame.mcusPerLine = mcusPerLine;\n frame.mcusPerColumn = mcusPerColumn;\n }\n var jfif = null;\n var adobe = null;\n var pixels = null;\n var frame, resetInterval;\n var quantizationTables = [], frames = [];\n var huffmanTablesAC = [], huffmanTablesDC = [];\n var fileMarker = readUint16();\n var malformedDataOffset = -1;\n this.comments = [];\n if (fileMarker != 0xFFD8) { // SOI (Start of Image)\n throw new Error(\"SOI not found\");\n }\n\n fileMarker = readUint16();\n while (fileMarker != 0xFFD9) { // EOI (End of image)\n var i, j, l;\n switch(fileMarker) {\n case 0xFF00: break;\n case 0xFFE0: // APP0 (Application Specific)\n case 0xFFE1: // APP1\n case 0xFFE2: // APP2\n case 0xFFE3: // APP3\n case 0xFFE4: // APP4\n case 0xFFE5: // APP5\n case 0xFFE6: // APP6\n case 0xFFE7: // APP7\n case 0xFFE8: // APP8\n case 0xFFE9: // APP9\n case 0xFFEA: // APP10\n case 0xFFEB: // APP11\n case 0xFFEC: // APP12\n case 0xFFED: // APP13\n case 0xFFEE: // APP14\n case 0xFFEF: // APP15\n case 0xFFFE: // COM (Comment)\n var appData = readDataBlock();\n\n if (fileMarker === 0xFFFE) {\n var comment = String.fromCharCode.apply(null, appData);\n this.comments.push(comment);\n }\n\n if (fileMarker === 0xFFE0) {\n if (appData[0] === 0x4A && appData[1] === 0x46 && appData[2] === 0x49 &&\n appData[3] === 0x46 && appData[4] === 0) { // 'JFIF\\x00'\n jfif = {\n version: { major: appData[5], minor: appData[6] },\n densityUnits: appData[7],\n xDensity: (appData[8] << 8) | appData[9],\n yDensity: (appData[10] << 8) | appData[11],\n thumbWidth: appData[12],\n thumbHeight: appData[13],\n thumbData: appData.subarray(14, 14 + 3 * appData[12] * appData[13])\n };\n }\n }\n // TODO APP1 - Exif\n if (fileMarker === 0xFFE1) {\n if (appData[0] === 0x45 &&\n appData[1] === 0x78 &&\n appData[2] === 0x69 &&\n appData[3] === 0x66 &&\n appData[4] === 0) { // 'EXIF\\x00'\n this.exifBuffer = appData.subarray(5, appData.length);\n }\n }\n\n if (fileMarker === 0xFFEE) {\n if (appData[0] === 0x41 && appData[1] === 0x64 && appData[2] === 0x6F &&\n appData[3] === 0x62 && appData[4] === 0x65 && appData[5] === 0) { // 'Adobe\\x00'\n adobe = {\n version: appData[6],\n flags0: (appData[7] << 8) | appData[8],\n flags1: (appData[9] << 8) | appData[10],\n transformCode: appData[11]\n };\n }\n }\n break;\n\n case 0xFFDB: // DQT (Define Quantization Tables)\n var quantizationTablesLength = readUint16();\n var quantizationTablesEnd = quantizationTablesLength + offset - 2;\n while (offset < quantizationTablesEnd) {\n var quantizationTableSpec = data[offset++];\n requestMemoryAllocation(64 * 4);\n var tableData = new Int32Array(64);\n if ((quantizationTableSpec >> 4) === 0) { // 8 bit values\n for (j = 0; j < 64; j++) {\n var z = dctZigZag[j];\n tableData[z] = data[offset++];\n }\n } else if ((quantizationTableSpec >> 4) === 1) { //16 bit\n for (j = 0; j < 64; j++) {\n var z = dctZigZag[j];\n tableData[z] = readUint16();\n }\n } else\n throw new Error(\"DQT: invalid table spec\");\n quantizationTables[quantizationTableSpec & 15] = tableData;\n }\n break;\n\n case 0xFFC0: // SOF0 (Start of Frame, Baseline DCT)\n case 0xFFC1: // SOF1 (Start of Frame, Extended DCT)\n case 0xFFC2: // SOF2 (Start of Frame, Progressive DCT)\n readUint16(); // skip data length\n frame = {};\n frame.extended = (fileMarker === 0xFFC1);\n frame.progressive = (fileMarker === 0xFFC2);\n frame.precision = data[offset++];\n frame.scanLines = readUint16();\n frame.samplesPerLine = readUint16();\n frame.components = {};\n frame.componentsOrder = [];\n\n var pixelsInFrame = frame.scanLines * frame.samplesPerLine;\n if (pixelsInFrame > maxResolutionInPixels) {\n var exceededAmount = Math.ceil((pixelsInFrame - maxResolutionInPixels) / 1e6);\n throw new Error(`maxResolutionInMP limit exceeded by ${exceededAmount}MP`);\n }\n\n var componentsCount = data[offset++], componentId;\n var maxH = 0, maxV = 0;\n for (i = 0; i < componentsCount; i++) {\n componentId = data[offset];\n var h = data[offset + 1] >> 4;\n var v = data[offset + 1] & 15;\n var qId = data[offset + 2];\n frame.componentsOrder.push(componentId);\n frame.components[componentId] = {\n h: h,\n v: v,\n quantizationIdx: qId\n };\n offset += 3;\n }\n prepareComponents(frame);\n frames.push(frame);\n break;\n\n case 0xFFC4: // DHT (Define Huffman Tables)\n var huffmanLength = readUint16();\n for (i = 2; i < huffmanLength;) {\n var huffmanTableSpec = data[offset++];\n var codeLengths = new Uint8Array(16);\n var codeLengthSum = 0;\n for (j = 0; j < 16; j++, offset++) {\n codeLengthSum += (codeLengths[j] = data[offset]);\n }\n requestMemoryAllocation(16 + codeLengthSum);\n var huffmanValues = new Uint8Array(codeLengthSum);\n for (j = 0; j < codeLengthSum; j++, offset++)\n huffmanValues[j] = data[offset];\n i += 17 + codeLengthSum;\n\n ((huffmanTableSpec >> 4) === 0 ?\n huffmanTablesDC : huffmanTablesAC)[huffmanTableSpec & 15] =\n buildHuffmanTable(codeLengths, huffmanValues);\n }\n break;\n\n case 0xFFDD: // DRI (Define Restart Interval)\n readUint16(); // skip data length\n resetInterval = readUint16();\n break;\n\n case 0xFFDC: // Number of Lines marker\n readUint16() // skip data length\n readUint16() // Ignore this data since it represents the image height\n break;\n \n case 0xFFDA: // SOS (Start of Scan)\n var scanLength = readUint16();\n var selectorsCount = data[offset++];\n var components = [], component;\n for (i = 0; i < selectorsCount; i++) {\n component = frame.components[data[offset++]];\n var tableSpec = data[offset++];\n component.huffmanTableDC = huffmanTablesDC[tableSpec >> 4];\n component.huffmanTableAC = huffmanTablesAC[tableSpec & 15];\n components.push(component);\n }\n var spectralStart = data[offset++];\n var spectralEnd = data[offset++];\n var successiveApproximation = data[offset++];\n var processed = decodeScan(data, offset,\n frame, components, resetInterval,\n spectralStart, spectralEnd,\n successiveApproximation >> 4, successiveApproximation & 15, this.opts);\n offset += processed;\n break;\n\n case 0xFFFF: // Fill bytes\n if (data[offset] !== 0xFF) { // Avoid skipping a valid marker.\n offset--;\n }\n break;\n default:\n if (data[offset - 3] == 0xFF &&\n data[offset - 2] >= 0xC0 && data[offset - 2] <= 0xFE) {\n // could be incorrect encoding -- last 0xFF byte of the previous\n // block was eaten by the encoder\n offset -= 3;\n break;\n }\n else if (fileMarker === 0xE0 || fileMarker == 0xE1) {\n // Recover from malformed APP1 markers popular in some phone models.\n // See https://github.com/eugeneware/jpeg-js/issues/82\n if (malformedDataOffset !== -1) {\n throw new Error(`first unknown JPEG marker at offset ${malformedDataOffset.toString(16)}, second unknown JPEG marker ${fileMarker.toString(16)} at offset ${(offset - 1).toString(16)}`);\n }\n malformedDataOffset = offset - 1;\n const nextOffset = readUint16();\n if (data[offset + nextOffset - 2] === 0xFF) {\n offset += nextOffset - 2;\n break;\n }\n }\n throw new Error(\"unknown JPEG marker \" + fileMarker.toString(16));\n }\n fileMarker = readUint16();\n }\n if (frames.length != 1)\n throw new Error(\"only single frame JPEGs supported\");\n\n // set each frame's components quantization table\n for (var i = 0; i < frames.length; i++) {\n var cp = frames[i].components;\n for (var j in cp) {\n cp[j].quantizationTable = quantizationTables[cp[j].quantizationIdx];\n delete cp[j].quantizationIdx;\n }\n }\n\n this.width = frame.samplesPerLine;\n this.height = frame.scanLines;\n this.jfif = jfif;\n this.adobe = adobe;\n this.components = [];\n for (var i = 0; i < frame.componentsOrder.length; i++) {\n var component = frame.components[frame.componentsOrder[i]];\n this.components.push({\n lines: buildComponentData(frame, component),\n scaleX: component.h / frame.maxH,\n scaleY: component.v / frame.maxV\n });\n }\n },\n getData: function getData(width, height) {\n var scaleX = this.width / width, scaleY = this.height / height;\n\n var component1, component2, component3, component4;\n var component1Line, component2Line, component3Line, component4Line;\n var x, y;\n var offset = 0;\n var Y, Cb, Cr, K, C, M, Ye, R, G, B;\n var colorTransform;\n var dataLength = width * height * this.components.length;\n requestMemoryAllocation(dataLength);\n var data = new Uint8Array(dataLength);\n switch (this.components.length) {\n case 1:\n component1 = this.components[0];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n\n data[offset++] = Y;\n }\n }\n break;\n case 2:\n // PDF might compress two component data in custom colorspace\n component1 = this.components[0];\n component2 = this.components[1];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n data[offset++] = Y;\n Y = component2Line[0 | (x * component2.scaleX * scaleX)];\n data[offset++] = Y;\n }\n }\n break;\n case 3:\n // The default transform for three components is true\n colorTransform = true;\n // The adobe transform marker overrides any previous setting\n if (this.adobe && this.adobe.transformCode)\n colorTransform = true;\n else if (typeof this.opts.colorTransform !== 'undefined')\n colorTransform = !!this.opts.colorTransform;\n\n component1 = this.components[0];\n component2 = this.components[1];\n component3 = this.components[2];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n if (!colorTransform) {\n R = component1Line[0 | (x * component1.scaleX * scaleX)];\n G = component2Line[0 | (x * component2.scaleX * scaleX)];\n B = component3Line[0 | (x * component3.scaleX * scaleX)];\n } else {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n Cb = component2Line[0 | (x * component2.scaleX * scaleX)];\n Cr = component3Line[0 | (x * component3.scaleX * scaleX)];\n\n R = clampTo8bit(Y + 1.402 * (Cr - 128));\n G = clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));\n B = clampTo8bit(Y + 1.772 * (Cb - 128));\n }\n\n data[offset++] = R;\n data[offset++] = G;\n data[offset++] = B;\n }\n }\n break;\n case 4:\n if (!this.adobe)\n throw new Error('Unsupported color mode (4 components)');\n // The default transform for four components is false\n colorTransform = false;\n // The adobe transform marker overrides any previous setting\n if (this.adobe && this.adobe.transformCode)\n colorTransform = true;\n else if (typeof this.opts.colorTransform !== 'undefined')\n colorTransform = !!this.opts.colorTransform;\n\n component1 = this.components[0];\n component2 = this.components[1];\n component3 = this.components[2];\n component4 = this.components[3];\n for (y = 0; y < height; y++) {\n component1Line = component1.lines[0 | (y * component1.scaleY * scaleY)];\n component2Line = component2.lines[0 | (y * component2.scaleY * scaleY)];\n component3Line = component3.lines[0 | (y * component3.scaleY * scaleY)];\n component4Line = component4.lines[0 | (y * component4.scaleY * scaleY)];\n for (x = 0; x < width; x++) {\n if (!colorTransform) {\n C = component1Line[0 | (x * component1.scaleX * scaleX)];\n M = component2Line[0 | (x * component2.scaleX * scaleX)];\n Ye = component3Line[0 | (x * component3.scaleX * scaleX)];\n K = component4Line[0 | (x * component4.scaleX * scaleX)];\n } else {\n Y = component1Line[0 | (x * component1.scaleX * scaleX)];\n Cb = component2Line[0 | (x * component2.scaleX * scaleX)];\n Cr = component3Line[0 | (x * component3.scaleX * scaleX)];\n K = component4Line[0 | (x * component4.scaleX * scaleX)];\n\n C = 255 - clampTo8bit(Y + 1.402 * (Cr - 128));\n M = 255 - clampTo8bit(Y - 0.3441363 * (Cb - 128) - 0.71413636 * (Cr - 128));\n Ye = 255 - clampTo8bit(Y + 1.772 * (Cb - 128));\n }\n data[offset++] = 255-C;\n data[offset++] = 255-M;\n data[offset++] = 255-Ye;\n data[offset++] = 255-K;\n }\n }\n break;\n default:\n throw new Error('Unsupported color mode');\n }\n return data;\n },\n copyToImageData: function copyToImageData(imageData, formatAsRGBA) {\n var width = imageData.width, height = imageData.height;\n var imageDataArray = imageData.data;\n var data = this.getData(width, height);\n var i = 0, j = 0, x, y;\n var Y, K, C, M, R, G, B;\n switch (this.components.length) {\n case 1:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n Y = data[i++];\n\n imageDataArray[j++] = Y;\n imageDataArray[j++] = Y;\n imageDataArray[j++] = Y;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n case 3:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n R = data[i++];\n G = data[i++];\n B = data[i++];\n\n imageDataArray[j++] = R;\n imageDataArray[j++] = G;\n imageDataArray[j++] = B;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n case 4:\n for (y = 0; y < height; y++) {\n for (x = 0; x < width; x++) {\n C = data[i++];\n M = data[i++];\n Y = data[i++];\n K = data[i++];\n\n R = 255 - clampTo8bit(C * (1 - K / 255) + K);\n G = 255 - clampTo8bit(M * (1 - K / 255) + K);\n B = 255 - clampTo8bit(Y * (1 - K / 255) + K);\n\n imageDataArray[j++] = R;\n imageDataArray[j++] = G;\n imageDataArray[j++] = B;\n if (formatAsRGBA) {\n imageDataArray[j++] = 255;\n }\n }\n }\n break;\n default:\n throw new Error('Unsupported color mode');\n }\n }\n };\n\n\n // We cap the amount of memory used by jpeg-js to avoid unexpected OOMs from untrusted content.\n var totalBytesAllocated = 0;\n var maxMemoryUsageBytes = 0;\n function requestMemoryAllocation(increaseAmount = 0) {\n var totalMemoryImpactBytes = totalBytesAllocated + increaseAmount;\n if (totalMemoryImpactBytes > maxMemoryUsageBytes) {\n var exceededAmount = Math.ceil((totalMemoryImpactBytes - maxMemoryUsageBytes) / 1024 / 1024);\n throw new Error(`maxMemoryUsageInMB limit exceeded by at least ${exceededAmount}MB`);\n }\n\n totalBytesAllocated = totalMemoryImpactBytes;\n }\n\n constructor.resetMaxMemoryUsage = function (maxMemoryUsageBytes_) {\n totalBytesAllocated = 0;\n maxMemoryUsageBytes = maxMemoryUsageBytes_;\n };\n\n constructor.getBytesAllocated = function () {\n return totalBytesAllocated;\n };\n\n constructor.requestMemoryAllocation = requestMemoryAllocation;\n\n return constructor;\n})();\n\nif (typeof module !== 'undefined') {\n\tmodule.exports = decode;\n} else if (typeof window !== 'undefined') {\n\twindow['jpeg-js'] = window['jpeg-js'] || {};\n\twindow['jpeg-js'].decode = decode;\n}\n\nfunction decode(jpegData, userOpts = {}) {\n var defaultOpts = {\n // \"undefined\" means \"Choose whether to transform colors based on the image’s color model.\"\n colorTransform: undefined,\n useTArray: false,\n formatAsRGBA: true,\n tolerantDecoding: true,\n maxResolutionInMP: 100, // Don't decode more than 100 megapixels\n maxMemoryUsageInMB: 512, // Don't decode if memory footprint is more than 512MB\n };\n\n var opts = {...defaultOpts, ...userOpts};\n var arr = new Uint8Array(jpegData);\n var decoder = new JpegImage();\n decoder.opts = opts;\n // If this constructor ever supports async decoding this will need to be done differently.\n // Until then, treating as singleton limit is fine.\n JpegImage.resetMaxMemoryUsage(opts.maxMemoryUsageInMB * 1024 * 1024);\n decoder.parse(arr);\n\n var channels = (opts.formatAsRGBA) ? 4 : 3;\n var bytesNeeded = decoder.width * decoder.height * channels;\n try {\n JpegImage.requestMemoryAllocation(bytesNeeded);\n var image = {\n width: decoder.width,\n height: decoder.height,\n exifBuffer: decoder.exifBuffer,\n data: opts.useTArray ?\n new Uint8Array(bytesNeeded) :\n Buffer.alloc(bytesNeeded)\n };\n if(decoder.comments.length > 0) {\n image[\"comments\"] = decoder.comments;\n }\n } catch (err){\n if (err instanceof RangeError){\n throw new Error(\"Could not allocate enough memory for the image. \" +\n \"Required: \" + bytesNeeded);\n } else {\n throw err;\n }\n }\n\n decoder.copyToImageData(image, opts.formatAsRGBA);\n\n return image;\n}\n","var encode = require('./lib/encoder'),\n decode = require('./lib/decoder');\n\nmodule.exports = {\n encode: encode,\n decode: decode\n};\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n\nlet chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n// Use a lookup table to find the index.\nlet lookup = new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\n\nexport function encode(bytes) {\n let i;\n let len = bytes.length;\n let base64 = '';\n\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n\n if (len % 3 === 2) {\n base64 = `${base64.substring(0, base64.length - 1)}=`;\n } else if (len % 3 === 1) {\n base64 = `${base64.substring(0, base64.length - 2)}==`;\n }\n\n return base64;\n}\n\nexport function decode(base64) {\n let bufferLength = base64.length * 0.75;\n let len = base64.length;\n let p = 0;\n let encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n const bytes = new Uint8Array(bufferLength);\n\n for (let i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n\n return bytes;\n}\n\nexport function toBase64URL(u8, type) {\n const base64 = encode(u8);\n return `data:${type};base64,${base64}`;\n}\n","const env = 'browser';\nconst ImageData = self.ImageData;\nconst DOMImage = self.Image;\n\nexport function createCanvas(width, height) {\n let canvas = self.document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n return canvas;\n}\n\nexport function fetchBinary(url, { withCredentials = false } = {}) {\n return new Promise(function (resolve, reject) {\n let xhr = new self.XMLHttpRequest();\n xhr.open('GET', url, true);\n xhr.responseType = 'arraybuffer';\n xhr.withCredentials = withCredentials;\n\n xhr.onload = function (e) {\n if (this.status !== 200) reject(e);\n else resolve(this.response);\n };\n xhr.onerror = reject;\n xhr.send();\n });\n}\n\nexport function createWriteStream() {\n throw new Error('createWriteStream does not exist in the browser');\n}\n\nexport function writeFile() {\n throw new Error('writeFile does not exist in the browser');\n}\n\nexport { env, ImageData, DOMImage };\n","export function getType(type) {\n if (!type.includes('/')) {\n type = `image/${type}`;\n }\n return type;\n}\n","import { canvasToBlob } from 'blob-util';\nimport { encode as encodeBmp } from 'fast-bmp';\nimport { encode as realEncodePng } from 'fast-png';\nimport { encode as realEncodeJpeg } from 'jpeg-js';\n\nimport { toBase64URL } from '../../util/base64';\n\nimport {\n ImageData,\n createCanvas,\n createWriteStream,\n writeFile,\n} from './environment';\nimport { getType } from './mediaTypes';\n\nfunction encodeJpeg(image, options = {}) {\n const data = {\n width: image.width,\n height: image.height,\n data: image.getRGBAData(),\n };\n return realEncodeJpeg(data, options.quality).data;\n}\n\nfunction encodePng(image, options) {\n const data = {\n width: image.width,\n height: image.height,\n channels: image.channels,\n depth: image.bitDepth,\n data: image.data,\n };\n\n if (data.depth === 1 || data.depth === 32) {\n data.depth = 8;\n data.channels = 4;\n data.data = image.getRGBAData();\n }\n\n return realEncodePng(data, options);\n}\n\nconst exportMethods = {\n /**\n * Save the image to disk (Node.js only)\n * @memberof Image\n * @instance\n * @param {string} path\n * @param {object} [options]\n * @param {string} [options.format] - One of: png, jpg, bmp (limited support for bmp). If not specified will try to infer from filename\n * @param {boolean} [options.useCanvas=false] - Force use of the canvas API to save the image instead of a JavaScript implementation\n * @param {object} [options.encoder] - Specify options for the encoder if applicable.\n * @return {Promise} - Resolves when the file is fully written\n */\n save(path, options = {}) {\n const { useCanvas = false, encoder: encoderOptions = undefined } = options;\n\n let { format } = options;\n if (!format) {\n // try to infer format from filename\n const m = /\\.(?[a-zA-Z]+)$/.exec(path);\n if (m) {\n format = m.groups.format.toLowerCase();\n }\n }\n if (!format) {\n throw new Error('file format not provided');\n }\n return new Promise((resolve, reject) => {\n let stream, buffer;\n switch (format.toLowerCase()) {\n case 'png': {\n if (useCanvas) {\n stream = this.getCanvas().pngStream();\n } else {\n buffer = encodePng(this, encoderOptions);\n }\n break;\n }\n case 'jpg':\n case 'jpeg':\n if (useCanvas) {\n stream = this.getCanvas().jpegStream();\n } else {\n buffer = encodeJpeg(this, encoderOptions);\n }\n break;\n case 'bmp':\n buffer = encodeBmp(this, encoderOptions);\n break;\n default:\n throw new RangeError(`invalid output format: ${format}`);\n }\n if (stream) {\n let out = createWriteStream(path);\n out.on('finish', resolve);\n out.on('error', reject);\n stream.pipe(out);\n } else if (buffer) {\n writeFile(path, buffer, (err) => {\n if (err) {\n reject(err);\n return;\n }\n resolve();\n });\n }\n });\n },\n\n /**\n * Creates a dataURL string from the image.\n * @memberof Image\n * @instance\n * @param {string} [type='image/png']\n * @param {object} [options]\n * @param {boolean} [options.useCanvas=false] - Force use of the canvas API to save the image instead of JavaScript implementation.\n * @param {object} [options.encoder] - Specify options for the encoder if applicable.\n * @return {string|Promise}\n */\n toDataURL(type = 'image/png', options = {}) {\n if (typeof type === 'object') {\n options = type;\n type = 'image/png';\n }\n const { useCanvas = false, encoder: encoderOptions = undefined } = options;\n type = getType(type);\n function dataUrl(encoder, ctx) {\n const u8 = encoder(ctx, encoderOptions);\n return toBase64URL(u8, type);\n }\n if (type === 'image/bmp') {\n return dataUrl(encodeBmp, this);\n } else if (type === 'image/png' && !useCanvas) {\n return dataUrl(encodePng, this);\n } else if (type === 'image/jpeg' && !useCanvas) {\n return dataUrl(encodeJpeg, this);\n } else {\n return this.getCanvas().toDataURL(type);\n }\n },\n\n /**\n * Encodes the image and returns a buffer\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {string} [options.format='png']\n * @param {object} [options.encoder] - Specify options for the encoder if applicable.\n * @return {Uint8Array}\n */\n toBuffer(options = {}) {\n const { format = 'png', encoder: encoderOptions = undefined } = options;\n switch (format.toLowerCase()) {\n case 'png':\n return encodePng(this, encoderOptions);\n case 'jpeg':\n case 'jpg':\n return encodeJpeg(this, encoderOptions);\n case 'bmp':\n return encodeBmp(this, encoderOptions);\n default:\n throw new RangeError(`invalid output format: ${format}`);\n }\n },\n\n /**\n * Creates a base64 string from the image.\n * @memberof Image\n * @instance\n * @param {string} [type='image/png']\n * @param {object} [options] - Same options as toDataURL\n * @return {string|Promise}\n */\n toBase64(type = 'image/png', options = {}) {\n if (options.async) {\n return this.toDataURL(type, options).then(function (dataURL) {\n return dataURL.substring(dataURL.indexOf(',') + 1);\n });\n } else {\n const dataURL = this.toDataURL(type, options);\n return dataURL.substring(dataURL.indexOf(',') + 1);\n }\n },\n\n /**\n * Creates a blob from the image and return a Promise.\n * This function is only available in the browser.\n * @memberof Image\n * @instance\n * @param {string} [type='image/png'] A String indicating the image format. The default type is image/png.\n * @param {string} [quality=0.8] A Number between 0 and 1 indicating image quality if the requested type is image/jpeg or image/webp. If this argument is anything else, the default value for image quality is used. Other arguments are ignored.\n * @return {Promise}\n */\n toBlob(type = 'image/png', quality = 0.8) {\n return canvasToBlob(this.getCanvas(), type, quality);\n },\n\n /**\n * Creates a new canvas element and draw the image inside it\n * @memberof Image\n * @instance\n * @return {Canvas}\n */\n getCanvas() {\n const data = new ImageData(\n this.getRGBAData({ clamped: true }),\n this.width,\n this.height,\n );\n let canvas = createCanvas(this.width, this.height);\n let ctx = canvas.getContext('2d');\n ctx.putImageData(data, 0, 0);\n return canvas;\n },\n};\n\nexport default function setExportMethods(Image) {\n for (const i in exportMethods) {\n Image.prototype[i] = exportMethods[i];\n }\n}\n","\nvar hasOwnProperty = Object.prototype.hasOwnProperty;\n\nmodule.exports = exports = function hasOwn(prop, obj) {\n return hasOwnProperty.call(obj, prop);\n}\n\nexports.version = require('./package.json').version;\n","import hasOwn from 'has-own';\n\nimport Image from '../Image';\n\nlet computedPropertyDescriptor = {\n configurable: true,\n enumerable: false,\n get: undefined,\n};\n\nexport function extendMethod(name, method, options = {}) {\n let { inPlace = false, returnThis = true, partialArgs = [] } = options;\n\n if (inPlace) {\n Image.prototype[name] = function (...args) {\n // remove computed properties\n this.computed = null;\n let result = method.apply(this, [...partialArgs, ...args]);\n if (returnThis) {\n return this;\n }\n return result;\n };\n } else {\n Image.prototype[name] = function (...args) {\n return method.apply(this, [...partialArgs, ...args]);\n };\n }\n return Image;\n}\n\nexport function extendProperty(name, method, options = {}) {\n let { partialArgs = [] } = options;\n\n computedPropertyDescriptor.get = function () {\n if (this.computed === null) {\n this.computed = {};\n } else if (hasOwn(name, this.computed)) {\n return this.computed[name];\n }\n let result = method.apply(this, partialArgs);\n this.computed[name] = result;\n return result;\n };\n Object.defineProperty(Image.prototype, name, computedPropertyDescriptor);\n return Image;\n}\n","/**\n * Color model of an image\n * @typedef {('GREY'|'RGB'|'HSL'|'HSV'|'CMYK')} ColorModel\n */\n\nexport const GREY = 'GREY';\nexport const RGB = 'RGB';\nexport const HSL = 'HSL';\nexport const HSV = 'HSV';\nexport const CMYK = 'CMYK';\n","import { RGB } from '../model/model';\n\n/**\n * Retrieve the data of the current image as RGBA 8 bits\n * The source image may be:\n * * a mask (binary image)\n * * a grey image (8 16 bits) with or without alpha channel\n * * a color image (8 or 16 bits) with or without alpha channel in with RGB model\n * @instance\n * @memberof Image\n * @param {object} [options]\n * @param {boolean} [options.clamped] - If true, the function will return a Uint8ClampedArray\n * @return {Uint8Array|Uint8ClampedArray} - Array with the data\n */\nexport default function getRGBAData(options = {}) {\n const { clamped } = options;\n this.checkProcessable('getRGBAData', {\n components: [1, 3],\n bitDepth: [1, 8, 16, 32],\n });\n const arrayLength = this.width * this.height * 4;\n let newData = clamped\n ? new Uint8ClampedArray(arrayLength)\n : new Uint8Array(arrayLength);\n if (this.bitDepth === 1) {\n fillDataFromBinary(this, newData);\n } else if (this.bitDepth === 32) {\n this.checkProcessable('getRGBAData', { alpha: 0 });\n if (this.components === 1) {\n fillDataFromGrey32(this, newData);\n } else if (this.components === 3) {\n this.checkProcessable('getRGBAData', { colorModel: [RGB] });\n fillDataFromRGB32(this, newData);\n }\n } else {\n if (this.components === 1) {\n fillDataFromGrey(this, newData);\n } else if (this.components === 3) {\n this.checkProcessable('getRGBAData', { colorModel: [RGB] });\n fillDataFromRGB(this, newData);\n }\n }\n if (this.alpha === 1) {\n this.checkProcessable('getRGBAData', { bitDepth: [8, 16] });\n copyAlpha(this, newData);\n } else {\n fillAlpha(this, newData);\n }\n return newData;\n}\n\nfunction fillDataFromBinary(image, newData) {\n for (let i = 0; i < image.size; i++) {\n const value = image.getBit(i);\n newData[i * 4] = value * 255;\n newData[i * 4 + 1] = value * 255;\n newData[i * 4 + 2] = value * 255;\n }\n}\n\nfunction fillDataFromGrey32(image, newData) {\n const min = image.min[0];\n const max = image.max[0];\n const range = max - min;\n for (let i = 0; i < image.size; i++) {\n const val = Math.floor((255 * (image.data[i] - min)) / range);\n newData[i * 4] = val;\n newData[i * 4 + 1] = val;\n newData[i * 4 + 2] = val;\n }\n}\n\nfunction fillDataFromRGB32(image, newData) {\n const min = Math.min(...image.min);\n const max = Math.max(...image.max);\n const range = max - min;\n for (let i = 0; i < image.size; i++) {\n const val1 = Math.floor((255 * (image.data[i * 3] - min)) / range);\n const val2 = Math.floor((255 * (image.data[i * 3 + 1] - min)) / range);\n const val3 = Math.floor((255 * (image.data[i * 3 + 2] - min)) / range);\n newData[i * 4] = val1;\n newData[i * 4 + 1] = val2;\n newData[i * 4 + 2] = val3;\n }\n}\n\nfunction fillDataFromGrey(image, newData) {\n for (let i = 0; i < image.size; i++) {\n newData[i * 4] = image.data[i * image.channels] >>> (image.bitDepth - 8);\n newData[i * 4 + 1] =\n image.data[i * image.channels] >>> (image.bitDepth - 8);\n newData[i * 4 + 2] =\n image.data[i * image.channels] >>> (image.bitDepth - 8);\n }\n}\n\nfunction fillDataFromRGB(image, newData) {\n for (let i = 0; i < image.size; i++) {\n newData[i * 4] = image.data[i * image.channels] >>> (image.bitDepth - 8);\n newData[i * 4 + 1] =\n image.data[i * image.channels + 1] >>> (image.bitDepth - 8);\n newData[i * 4 + 2] =\n image.data[i * image.channels + 2] >>> (image.bitDepth - 8);\n }\n}\n\nfunction copyAlpha(image, newData) {\n for (let i = 0; i < image.size; i++) {\n newData[i * 4 + 3] =\n image.data[i * image.channels + image.components] >> (image.bitDepth - 8);\n }\n}\n\nfunction fillAlpha(image, newData) {\n for (let i = 0; i < image.size; i++) {\n newData[i * 4 + 3] = 255;\n }\n}\n","// Shortcuts for common image kinds\n\nexport const BINARY = 'BINARY';\nexport const GREY = 'GREY';\nexport const GREYA = 'GREYA';\nexport const RGB = 'RGB';\nexport const RGBA = 'RGBA';\nexport const CMYK = 'CMYK';\nexport const CMYKA = 'CMYKA';\n","import * as ColorModel from '../model/model';\n\nimport * as Kind from './kindNames';\n\nconst kinds = {};\n\nkinds[Kind.BINARY] = {\n components: 1,\n alpha: 0,\n bitDepth: 1,\n colorModel: ColorModel.GREY,\n};\n\nkinds[Kind.GREYA] = {\n components: 1,\n alpha: 1,\n bitDepth: 8,\n colorModel: ColorModel.GREY,\n};\n\nkinds[Kind.GREY] = {\n components: 1,\n alpha: 0,\n bitDepth: 8,\n colorModel: ColorModel.GREY,\n};\n\nkinds[Kind.RGBA] = {\n components: 3,\n alpha: 1,\n bitDepth: 8,\n colorModel: ColorModel.RGB,\n};\n\nkinds[Kind.RGB] = {\n components: 3,\n alpha: 0,\n bitDepth: 8,\n colorModel: ColorModel.RGB,\n};\n\nkinds[Kind.CMYK] = {\n components: 4,\n alpha: 0,\n bitDepth: 8,\n colorModel: ColorModel.CMYK,\n};\n\nkinds[Kind.CMYKA] = {\n components: 4,\n alpha: 1,\n bitDepth: 8,\n colorModel: ColorModel.CMYK,\n};\n\nexport function getKind(kind) {\n const result = kinds[kind];\n if (!result) {\n throw new RangeError(`invalid image kind: ${kind}`);\n }\n return result;\n}\nconst validBitDepth = [1, 8, 16, 32];\nexport function verifyKindDefinition(definition) {\n const { components, alpha, bitDepth, colorModel } = definition;\n if (!Number.isInteger(components) || components <= 0) {\n throw new RangeError(\n `invalid components: ${components}. Must be a positive integer`,\n );\n }\n if (alpha !== 0 && alpha !== 1 && typeof alpha !== 'boolean') {\n throw new TypeError(`invalid alpha: ${alpha}: must be a boolean, 0 or 1`);\n }\n if (!validBitDepth.includes(bitDepth)) {\n throw new RangeError(\n `invalid bitDepth: ${bitDepth}. Must be one of ${validBitDepth.join(\n ', ',\n )}`,\n );\n }\n // eslint-disable-next-line import/namespace\n if (!ColorModel[colorModel]) {\n throw new RangeError(\n `invalid colorModel: ${colorModel}. Must be one of ${Object.keys(\n ColorModel,\n ).join(', ')}`,\n );\n }\n}\n\nexport function getTheoreticalPixelArraySize(size, channels, bitDepth) {\n let length = channels * size;\n if (bitDepth === 1) {\n length = Math.ceil(length / 8);\n }\n return length;\n}\n\nexport function createPixelArray(\n size,\n components,\n alpha,\n channels,\n bitDepth,\n maxValue,\n) {\n const length = channels * size;\n let arr;\n switch (bitDepth) {\n case 1:\n arr = new Uint8Array(Math.ceil(length / 8));\n break;\n case 8:\n arr = new Uint8Array(length);\n break;\n case 16:\n arr = new Uint16Array(length);\n break;\n case 32:\n arr = new Float32Array(length);\n break;\n default:\n throw new Error(`Cannot create pixel array for bit depth ${bitDepth}`);\n }\n\n // alpha channel is 100% by default\n if (alpha) {\n for (let i = components; i < arr.length; i += channels) {\n arr[i] = maxValue;\n }\n }\n\n return arr;\n}\n","'use strict';\n\nconst defaultByteLength = 1024 * 8;\nconst charArray = [];\n\nclass IOBuffer {\n constructor(data, options) {\n options = options || {};\n if (data === undefined) {\n data = defaultByteLength;\n }\n if (typeof data === 'number') {\n data = new ArrayBuffer(data);\n }\n let length = data.byteLength;\n const offset = options.offset ? options.offset>>>0 : 0;\n if (data.buffer) {\n length = data.byteLength - offset;\n if (data.byteLength !== data.buffer.byteLength) { // Node.js buffer from pool\n data = data.buffer.slice(data.byteOffset + offset, data.byteOffset + data.byteLength);\n } else if (offset) {\n data = data.buffer.slice(offset);\n } else {\n data = data.buffer;\n }\n }\n this.buffer = data;\n this.length = length;\n this.byteLength = length;\n this.byteOffset = 0;\n this.offset = 0;\n this.littleEndian = true;\n this._data = new DataView(this.buffer);\n this._increment = length || defaultByteLength;\n this._mark = 0;\n }\n\n available(byteLength) {\n if (byteLength === undefined) byteLength = 1;\n return (this.offset + byteLength) <= this.length;\n }\n\n isLittleEndian() {\n return this.littleEndian;\n }\n\n setLittleEndian() {\n this.littleEndian = true;\n }\n\n isBigEndian() {\n return !this.littleEndian;\n }\n\n setBigEndian() {\n this.littleEndian = false;\n }\n\n skip(n) {\n if (n === undefined) n = 1;\n this.offset += n;\n }\n\n seek(offset) {\n this.offset = offset;\n }\n\n mark() {\n this._mark = this.offset;\n }\n\n reset() {\n this.offset = this._mark;\n }\n\n rewind() {\n this.offset = 0;\n }\n\n ensureAvailable(byteLength) {\n if (byteLength === undefined) byteLength = 1;\n if (!this.available(byteLength)) {\n const newIncrement = this._increment + this._increment;\n this._increment = newIncrement;\n const newLength = this.length + newIncrement;\n const newArray = new Uint8Array(newLength);\n newArray.set(new Uint8Array(this.buffer));\n this.buffer = newArray.buffer;\n this.length = newLength;\n this._data = new DataView(this.buffer);\n }\n }\n\n readBoolean() {\n return this.readUint8() !== 0;\n }\n\n readInt8() {\n return this._data.getInt8(this.offset++);\n }\n\n readUint8() {\n return this._data.getUint8(this.offset++);\n }\n\n readByte() {\n return this.readUint8();\n }\n\n readBytes(n) {\n if (n === undefined) n = 1;\n var bytes = new Uint8Array(n);\n for (var i = 0; i < n; i++) {\n bytes[i] = this.readByte();\n }\n return bytes;\n }\n\n readInt16() {\n var value = this._data.getInt16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n\n readUint16() {\n var value = this._data.getUint16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n\n readInt32() {\n var value = this._data.getInt32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n\n readUint32() {\n var value = this._data.getUint32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n\n readFloat32() {\n var value = this._data.getFloat32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n\n readFloat64() {\n var value = this._data.getFloat64(this.offset, this.littleEndian);\n this.offset += 8;\n return value;\n }\n\n readChar() {\n return String.fromCharCode(this.readInt8());\n }\n\n readChars(n) {\n if (n === undefined) n = 1;\n charArray.length = n;\n for (var i = 0; i < n; i++) {\n charArray[i] = this.readChar();\n }\n return charArray.join('');\n }\n\n writeBoolean(bool) {\n this.writeUint8(bool ? 0xff : 0x00);\n }\n\n writeInt8(value) {\n this.ensureAvailable(1);\n this._data.setInt8(this.offset++, value);\n }\n\n writeUint8(value) {\n this.ensureAvailable(1);\n this._data.setUint8(this.offset++, value);\n }\n\n writeByte(value) {\n this.writeUint8(value);\n }\n\n writeBytes(bytes) {\n this.ensureAvailable(bytes.length);\n for (var i = 0; i < bytes.length; i++) {\n this._data.setUint8(this.offset++, bytes[i]);\n }\n }\n\n writeInt16(value) {\n this.ensureAvailable(2);\n this._data.setInt16(this.offset, value, this.littleEndian);\n this.offset += 2;\n }\n\n writeUint16(value) {\n this.ensureAvailable(2);\n this._data.setUint16(this.offset, value, this.littleEndian);\n this.offset += 2;\n }\n\n writeInt32(value) {\n this.ensureAvailable(4);\n this._data.setInt32(this.offset, value, this.littleEndian);\n this.offset += 4;\n }\n\n writeUint32(value) {\n this.ensureAvailable(4);\n this._data.setUint32(this.offset, value, this.littleEndian);\n this.offset += 4;\n }\n\n writeFloat32(value) {\n this.ensureAvailable(4);\n this._data.setFloat32(this.offset, value, this.littleEndian);\n this.offset += 4;\n }\n\n writeFloat64(value) {\n this.ensureAvailable(8);\n this._data.setFloat64(this.offset, value, this.littleEndian);\n this.offset += 8;\n }\n\n writeChar(str) {\n this.writeUint8(str.charCodeAt(0));\n }\n\n writeChars(str) {\n for (var i = 0; i < str.length; i++) {\n this.writeUint8(str.charCodeAt(i));\n }\n }\n\n toArray() {\n return new Uint8Array(this.buffer, 0, this.offset);\n }\n}\n\nmodule.exports = IOBuffer;\n","'use strict';\n\nconst tagsById = {\n // Baseline tags\n 0x00FE: 'NewSubfileType',\n 0x00FF: 'SubfileType',\n 0x0100: 'ImageWidth',\n 0x0101: 'ImageLength',\n 0x0102: 'BitsPerSample',\n 0x0103: 'Compression',\n 0x0106: 'PhotometricInterpretation',\n 0x0107: 'Threshholding',\n 0x0108: 'CellWidth',\n 0x0109: 'CellLength',\n 0x010A: 'FillOrder',\n 0x010E: 'ImageDescription',\n 0x010F: 'Make',\n 0x0110: 'Model',\n 0x0111: 'StripOffsets',\n 0x0112: 'Orientation',\n 0x0115: 'SamplesPerPixel',\n 0x0116: 'RowsPerStrip',\n 0x0117: 'StripByteCounts',\n 0x0118: 'MinSampleValue',\n 0x0119: 'MaxSampleValue',\n 0x011A: 'XResolution',\n 0x011B: 'YResolution',\n 0x011C: 'PlanarConfiguration',\n 0x0120: 'FreeOffsets',\n 0x0121: 'FreeByteCounts',\n 0x0122: 'GrayResponseUnit',\n 0x0123: 'GrayResponseCurve',\n 0x0128: 'ResolutionUnit',\n 0x0131: 'Software',\n 0x0132: 'DateTime',\n 0x013B: 'Artist',\n 0x013C: 'HostComputer',\n 0x0140: 'ColorMap',\n 0x0152: 'ExtraSamples',\n 0x8298: 'Copyright',\n\n // Extension tags\n 0x010D: 'DocumentName',\n 0x011D: 'PageName',\n 0x011E: 'XPosition',\n 0x011F: 'YPosition',\n 0x0124: 'T4Options',\n 0x0125: 'T6Options',\n 0x0129: 'PageNumber',\n 0x012D: 'TransferFunction',\n 0x013D: 'Predictor',\n 0x013E: 'WhitePoint',\n 0x013F: 'PrimaryChromaticities',\n 0x0141: 'HalftoneHints',\n 0x0142: 'TileWidth',\n 0x0143: 'TileLength',\n 0x0144: 'TileOffsets',\n 0x0145: 'TileByteCounts',\n 0x0146: 'BadFaxLines',\n 0x0147: 'CleanFaxData',\n 0x0148: 'ConsecutiveBadFaxLines',\n 0x014A: 'SubIFDs',\n 0x014C: 'InkSet',\n 0x014D: 'InkNames',\n 0x014E: 'NumberOfInks',\n 0x0150: 'DotRange',\n 0x0151: 'TargetPrinter',\n 0x0153: 'SampleFormat',\n 0x0154: 'SMinSampleValue',\n 0x0155: 'SMaxSampleValue',\n 0x0156: 'TransferRange',\n 0x0157: 'ClipPath',\n 0x0158: 'XClipPathUnits',\n 0x0159: 'YClipPathUnits',\n 0x015A: 'Indexed',\n 0x015B: 'JPEGTables',\n 0x015F: 'OPIProxy',\n 0x0190: 'GlobalParametersIFD',\n 0x0191: 'ProfileType',\n 0x0192: 'FaxProfile',\n 0x0193: 'CodingMethods',\n 0x0194: 'VersionYear',\n 0x0195: 'ModeNumber',\n 0x01B1: 'Decode',\n 0x01B2: 'DefaultImageColor',\n 0x0200: 'JPEGProc',\n 0x0201: 'JPEGInterchangeFormat',\n 0x0202: 'JPEGInterchangeFormatLength',\n 0x0203: 'JPEGRestartInterval',\n 0x0205: 'JPEGLosslessPredictors',\n 0x0206: 'JPEGPointTransforms',\n 0x0207: 'JPEGQTables',\n 0x0208: 'JPEGDCTables',\n 0x0209: 'JPEGACTables',\n 0x0211: 'YCbCrCoefficients',\n 0x0212: 'YCbCrSubSampling',\n 0x0213: 'YCbCrPositioning',\n 0x0214: 'ReferenceBlackWhite',\n 0x022F: 'StripRowCounts',\n 0x02BC: 'XMP',\n 0x800D: 'ImageID',\n 0x87AC: 'ImageLayer',\n\n // Private tags\n 0x80A4: 'WangAnnotatio',\n 0x82A5: 'MDFileTag',\n 0x82A6: 'MDScalePixel',\n 0x82A7: 'MDColorTable',\n 0x82A8: 'MDLabName',\n 0x82A9: 'MDSampleInfo',\n 0x82AA: 'MDPrepDate',\n 0x82AB: 'MDPrepTime',\n 0x82AC: 'MDFileUnits',\n 0x830E: 'ModelPixelScaleTag',\n 0x83BB: 'IPTC',\n 0x847E: 'INGRPacketDataTag',\n 0x847F: 'INGRFlagRegisters',\n 0x8480: 'IrasBTransformationMatrix',\n 0x8482: 'ModelTiepointTag',\n 0x85D8: 'ModelTransformationTag',\n 0x8649: 'Photoshop',\n 0x8769: 'ExifIFD',\n 0x8773: 'ICCProfile',\n 0x87AF: 'GeoKeyDirectoryTag',\n 0x87B0: 'GeoDoubleParamsTag',\n 0x87B1: 'GeoAsciiParamsTag',\n 0x8825: 'GPSIFD',\n 0x885C: 'HylaFAXFaxRecvParams',\n 0x885D: 'HylaFAXFaxSubAddress',\n 0x885E: 'HylaFAXFaxRecvTime',\n 0x935C: 'ImageSourceData',\n 0xA005: 'InteroperabilityIFD',\n 0xA480: 'GDAL_METADATA',\n 0xA481: 'GDAL_NODATA',\n 0xC427: 'OceScanjobDescription',\n 0xC428: 'OceApplicationSelector',\n 0xC429: 'OceIdentificationNumber',\n 0xC42A: 'OceImageLogicCharacteristics',\n 0xC612: 'DNGVersion',\n 0xC613: 'DNGBackwardVersion',\n 0xC614: 'UniqueCameraModel',\n 0xC615: 'LocalizedCameraModel',\n 0xC616: 'CFAPlaneColor',\n 0xC617: 'CFALayout',\n 0xC618: 'LinearizationTable',\n 0xC619: 'BlackLevelRepeatDim',\n 0xC61A: 'BlackLevel',\n 0xC61B: 'BlackLevelDeltaH',\n 0xC61C: 'BlackLevelDeltaV',\n 0xC61D: 'WhiteLevel',\n 0xC61E: 'DefaultScale',\n 0xC61F: 'DefaultCropOrigin',\n 0xC620: 'DefaultCropSize',\n 0xC621: 'ColorMatrix1',\n 0xC622: 'ColorMatrix2',\n 0xC623: 'CameraCalibration1',\n 0xC624: 'CameraCalibration2',\n 0xC625: 'ReductionMatrix1',\n 0xC626: 'ReductionMatrix2',\n 0xC627: 'AnalogBalance',\n 0xC628: 'AsShotNeutral',\n 0xC629: 'AsShotWhiteXY',\n 0xC62A: 'BaselineExposure',\n 0xC62B: 'BaselineNoise',\n 0xC62C: 'BaselineSharpness',\n 0xC62D: 'BayerGreenSplit',\n 0xC62E: 'LinearResponseLimit',\n 0xC62F: 'CameraSerialNumber',\n 0xC630: 'LensInfo',\n 0xC631: 'ChromaBlurRadius',\n 0xC632: 'AntiAliasStrength',\n 0xC634: 'DNGPrivateData',\n 0xC635: 'MakerNoteSafety',\n 0xC65A: 'CalibrationIlluminant1',\n 0xC65B: 'CalibrationIlluminant2',\n 0xC65C: 'BestQualityScale',\n 0xC660: 'AliasLayerMetadata'\n};\n\nconst tagsByName = {};\nfor (var i in tagsById) {\n tagsByName[tagsById[i]] = i;\n}\n\nmodule.exports = {\n tagsById,\n tagsByName\n};\n","'use strict';\n\nconst tagsById = {\n 0x829A: 'ExposureTime',\n 0x829D: 'FNumber',\n 0x8822: 'ExposureProgram',\n 0x8824: 'SpectralSensitivity',\n 0x8827: 'ISOSpeedRatings',\n 0x8828: 'OECF',\n 0x8830: 'SensitivityType',\n 0x8831: 'StandardOutputSensitivity',\n 0x8832: 'RecommendedExposureIndex',\n 0x8833: 'ISOSpeed',\n 0x8834: 'ISOSpeedLatitudeyyy',\n 0x8835: 'ISOSpeedLatitudezzz',\n 0x9000: 'ExifVersion',\n 0x9003: 'DateTimeOriginal',\n 0x9004: 'DateTimeDigitized',\n 0x9101: 'ComponentsConfiguration',\n 0x9102: 'CompressedBitsPerPixel',\n 0x9201: 'ShutterSpeedValue',\n 0x9202: 'ApertureValue',\n 0x9203: 'BrightnessValue',\n 0x9204: 'ExposureBiasValue',\n 0x9205: 'MaxApertureValue',\n 0x9206: 'SubjectDistance',\n 0x9207: 'MeteringMode',\n 0x9208: 'LightSource',\n 0x9209: 'Flash',\n 0x920A: 'FocalLength',\n 0x9214: 'SubjectArea',\n 0x927C: 'MakerNote',\n 0x9286: 'UserComment',\n 0x9290: 'SubsecTime',\n 0x9291: 'SubsecTimeOriginal',\n 0x9292: 'SubsecTimeDigitized',\n 0xA000: 'FlashpixVersion',\n 0xA001: 'ColorSpace',\n 0xA002: 'PixelXDimension',\n 0xA003: 'PixelYDimension',\n 0xA004: 'RelatedSoundFile',\n 0xA20B: 'FlashEnergy',\n 0xA20C: 'SpatialFrequencyResponse',\n 0xA20E: 'FocalPlaneXResolution',\n 0xA20F: 'FocalPlaneYResolution',\n 0xA210: 'FocalPlaneResolutionUnit',\n 0xA214: 'SubjectLocation',\n 0xA215: 'ExposureIndex',\n 0xA217: 'SensingMethod',\n 0xA300: 'FileSource',\n 0xA301: 'SceneType',\n 0xA302: 'CFAPattern',\n 0xA401: 'CustomRendered',\n 0xA402: 'ExposureMode',\n 0xA403:\t'WhiteBalance',\n 0xA404:\t'DigitalZoomRatio',\n 0xA405:\t'FocalLengthIn35mmFilm',\n 0xA406:\t'SceneCaptureType',\n 0xA407:\t'GainControl',\n 0xA408:\t'Contrast',\n 0xA409:\t'Saturation',\n 0xA40A:\t'Sharpness',\n 0xA40B:\t'DeviceSettingDescription',\n 0xA40C:\t'SubjectDistanceRange',\n 0xA420:\t'ImageUniqueID',\n 0xA430: 'CameraOwnerName',\n 0xA431: 'BodySerialNumber',\n 0xA432: 'LensSpecification',\n 0xA433: 'LensMake',\n 0xA434: 'LensModel',\n 0xA435: 'LensSerialNumber',\n 0xA500: 'Gamma'\n};\n\nconst tagsByName = {};\nfor (var i in tagsById) {\n tagsByName[tagsById[i]] = i;\n}\n\nmodule.exports = {\n tagsById,\n tagsByName\n};\n","'use strict';\n\nconst tagsById = {\n 0x0000: 'GPSVersionID',\n 0x0001: 'GPSLatitudeRef',\n 0x0002: 'GPSLatitude',\n 0x0003: 'GPSLongitudeRef',\n 0x0004: 'GPSLongitude',\n 0x0005: 'GPSAltitudeRef',\n 0x0006: 'GPSAltitude',\n 0x0007: 'GPSTimeStamp',\n 0x0008: 'GPSSatellites',\n 0x0009: 'GPSStatus',\n 0x000A: 'GPSMeasureMode',\n 0x000B: 'GPSDOP',\n 0x000C: 'GPSSpeedRef',\n 0x000D: 'GPSSpeed',\n 0x000E: 'GPSTrackRef',\n 0x000F: 'GPSTrack',\n 0x0010: 'GPSImgDirectionRef',\n 0x0011: 'GPSImgDirection',\n 0x0012: 'GPSMapDatum',\n 0x0013: 'GPSDestLatitudeRef',\n 0x0014: 'GPSDestLatitude',\n 0x0015: 'GPSDestLongitudeRef',\n 0x0016: 'GPSDestLongitude',\n 0x0017: 'GPSDestBearingRef',\n 0x0018: 'GPSDestBearing',\n 0x0019: 'GPSDestDistanceRef',\n 0x001A: 'GPSDestDistance',\n 0x001B: 'GPSProcessingMethod',\n 0x001C: 'GPSAreaInformation',\n 0x001D: 'GPSDateStamp',\n 0x001E: 'GPSDifferential',\n 0x001F: 'GPSHPositioningError'\n};\n\nconst tagsByName = {};\nfor (var i in tagsById) {\n tagsByName[tagsById[i]] = i;\n}\n\nmodule.exports = {\n tagsById,\n tagsByName\n};\n","'use strict';\n\nconst tags = {\n standard: require('./tags/standard'),\n exif: require('./tags/exif'),\n gps: require('./tags/gps')\n};\n\nclass IFD {\n constructor(kind) {\n if (!kind) {\n throw new Error('missing kind');\n }\n this.data = null;\n this.fields = new Map();\n this.kind = kind;\n this._map = null;\n }\n\n get(tag) {\n if (typeof tag === 'number') {\n return this.fields.get(tag);\n } else if (typeof tag === 'string') {\n return this.fields.get(tags[this.kind].tagsByName[tag]);\n } else {\n throw new Error('expected a number or string');\n }\n }\n\n get map() {\n if (!this._map) {\n this._map = {};\n const taglist = tags[this.kind].tagsById;\n for (var key of this.fields.keys()) {\n if (taglist[key]) {\n this._map[taglist[key]] = this.fields.get(key);\n }\n }\n }\n return this._map;\n }\n}\n\nmodule.exports = IFD;\n","'use strict';\n\nconst Ifd = require('./ifd');\n\nconst dateTimeRegex = /^(\\d{4}):(\\d{2}):(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/;\n\nclass TiffIfd extends Ifd {\n constructor() {\n super('standard');\n }\n\n // Custom fields\n get size() {\n return this.width * this.height;\n }\n get width() {\n return this.imageWidth;\n }\n get height() {\n return this.imageLength;\n }\n get components() {\n return this.samplesPerPixel;\n }\n get date() {\n var date = new Date();\n var result = dateTimeRegex.exec(this.dateTime);\n date.setFullYear(result[1], result[2] - 1, result[3]);\n date.setHours(result[4], result[5], result[6]);\n return date;\n }\n\n // IFD fields\n get newSubfileType() {\n return this.get(254);\n }\n get imageWidth() {\n return this.get(256);\n }\n get imageLength() {\n return this.get(257);\n }\n get bitsPerSample() {\n return this.get(258);\n }\n get compression() {\n return this.get(259) || 1;\n }\n get type() {\n return this.get(262);\n }\n get fillOrder() {\n return this.get(266) || 1;\n }\n get documentName() {\n return this.get(269);\n }\n get imageDescription() {\n return this.get(270);\n }\n get stripOffsets() {\n return alwaysArray(this.get(273));\n }\n get orientation() {\n return this.get(274);\n }\n get samplesPerPixel() {\n return this.get(277);\n }\n get rowsPerStrip() {\n return this.get(278);\n }\n get stripByteCounts() {\n return alwaysArray(this.get(279));\n }\n get minSampleValue() {\n return this.get(280) || 0;\n }\n get maxSampleValue() {\n return this.get(281) || Math.pow(2, this.bitsPerSample) - 1;\n }\n get xResolution() {\n return this.get(282);\n }\n get yResolution() {\n return this.get(283);\n }\n get planarConfiguration() {\n return this.get(284) || 1;\n }\n get resolutionUnit() {\n return this.get(296) || 2;\n }\n get dateTime() {\n return this.get(306);\n }\n get predictor() {\n return this.get(317) || 1;\n }\n get sampleFormat() {\n return this.get(339) || 1;\n }\n get sMinSampleValue() {\n return this.get(340) || this.minSampleValue;\n }\n get sMaxSampleValue() {\n return this.get(341) || this.maxSampleValue;\n }\n}\n\nfunction alwaysArray(value) {\n if (typeof value === 'number') return [value];\n return value;\n}\n\nmodule.exports = TiffIfd;\n","'use strict';\n\nvar types = new Map([\n [1, [1, readByte]], // BYTE\n [2, [1, readASCII]], // ASCII\n [3, [2, readShort]], // SHORT\n [4, [4, readLong]], // LONG\n [5, [8, readRational]], // RATIONAL\n [6, [1, readSByte]], // SBYTE\n [7, [1, readByte]], // UNDEFINED\n [8, [2, readSShort]], // SSHORT\n [9, [4, readSLong]], // SLONG\n [10, [8, readSRational]], // SRATIONAL\n [11, [4, readFloat]], // FLOAT\n [12, [8, readDouble]] // DOUBLE\n]);\n\nexports.getByteLength = function (type, count) {\n return types.get(type)[0] * count;\n};\n\nexports.readData = function (decoder, type, count) {\n return types.get(type)[1](decoder, count);\n};\n\nfunction readByte(decoder, count) {\n if (count === 1) return decoder.readUint8();\n var array = new Uint8Array(count);\n for (var i = 0; i < count; i++) {\n array[i] = decoder.readUint8();\n }\n return array;\n}\n\nfunction readASCII(decoder, count) {\n var strings = [];\n var currentString = '';\n for (var i = 0; i < count; i++) {\n var char = String.fromCharCode(decoder.readUint8());\n if (char === '\\0') {\n strings.push(currentString);\n currentString = '';\n } else {\n currentString += char;\n }\n }\n if (strings.length === 1) {\n return strings[0];\n } else {\n return strings;\n }\n}\n\nfunction readShort(decoder, count) {\n if (count === 1) return decoder.readUint16();\n var array = new Uint16Array(count);\n for (var i = 0; i < count; i++) {\n array[i] = decoder.readUint16();\n }\n return array;\n}\n\nfunction readLong(decoder, count) {\n if (count === 1) return decoder.readUint32();\n var array = new Uint32Array(count);\n for (var i = 0; i < count; i++) {\n array[i] = decoder.readUint32();\n }\n return array;\n}\n\nfunction readRational(decoder, count) {\n if (count === 1) {\n return decoder.readUint32() / decoder.readUint32();\n }\n var rationals = new Array(count);\n for (var i = 0; i < count; i++) {\n rationals[i] = decoder.readUint32() / decoder.readUint32();\n }\n return rationals;\n}\n\nfunction readSByte(decoder, count) {\n if (count === 1) return decoder.readInt8();\n var array = new Int8Array(count);\n for (var i = 0; i < count; i++) {\n array[i] = decoder.readInt8();\n }\n return array;\n}\n\nfunction readSShort(decoder, count) {\n if (count === 1) return decoder.readInt16();\n var array = new Int16Array(count);\n for (var i = 0; i < count; i++) {\n array[i] = decoder.readInt16();\n }\n return array;\n}\n\nfunction readSLong(decoder, count) {\n if (count === 1) return decoder.readInt32();\n var array = new Int32Array(count);\n for (var i = 0; i < count; i++) {\n array[i] = decoder.readInt32();\n }\n return array;\n}\n\nfunction readSRational(decoder, count) {\n if (count === 1) {\n return decoder.readInt32() / decoder.readInt32();\n }\n var rationals = new Array(count);\n for (var i = 0; i < count; i++) {\n rationals[i] = decoder.readInt32() / decoder.readInt32();\n }\n return rationals;\n}\n\nfunction readFloat(decoder, count) {\n if (count === 1) return decoder.readFloat32();\n var array = new Float32Array(count);\n for (var i = 0; i < count; i++) {\n array[i] = decoder.readFloat32();\n }\n return array;\n}\n\nfunction readDouble(decoder, count) {\n if (count === 1) return decoder.readFloat64();\n var array = new Float64Array(count);\n for (var i = 0; i < count; i++) {\n array[i] = decoder.readFloat64();\n }\n return array;\n}\n","'use strict';\n\nconst IOBuffer = require('iobuffer');\nconst IFD = require('./ifd');\nconst TiffIFD = require('./tiffIfd');\nconst IFDValue = require('./ifdValue');\n\nconst defaultOptions = {\n ignoreImageData: false,\n onlyFirst: false\n};\n\nclass TIFFDecoder extends IOBuffer {\n constructor(data, options) {\n super(data, options);\n this._nextIFD = 0;\n }\n\n decode(options) {\n options = Object.assign({}, defaultOptions, options);\n const result = [];\n this.decodeHeader();\n while (this._nextIFD) {\n result.push(this.decodeIFD(options));\n if (options.onlyFirst) {\n return result[0];\n }\n }\n return result;\n }\n\n decodeHeader() {\n // Byte offset\n let value = this.readUint16();\n if (value === 0x4949) {\n this.setLittleEndian();\n } else if (value === 0x4D4D) {\n this.setBigEndian();\n } else {\n throw new Error('invalid byte order: 0x' + value.toString(16));\n }\n\n // Magic number\n value = this.readUint16();\n if (value !== 42) {\n throw new Error('not a TIFF file');\n }\n\n // Offset of the first IFD\n this._nextIFD = this.readUint32();\n }\n\n decodeIFD(options) {\n this.seek(this._nextIFD);\n\n var ifd;\n if (!options.kind) {\n ifd = new TiffIFD();\n } else {\n ifd = new IFD(options.kind);\n }\n\n const numEntries = this.readUint16();\n for (var i = 0; i < numEntries; i++) {\n this.decodeIFDEntry(ifd);\n }\n if (!options.ignoreImageData) {\n this.decodeImageData(ifd);\n }\n this._nextIFD = this.readUint32();\n return ifd;\n }\n\n decodeIFDEntry(ifd) {\n const offset = this.offset;\n const tag = this.readUint16();\n const type = this.readUint16();\n const numValues = this.readUint32();\n\n if (type < 1 || type > 12) {\n this.skip(4); // unknown type, skip this value\n return;\n }\n\n const valueByteLength = IFDValue.getByteLength(type, numValues);\n if (valueByteLength > 4) {\n this.seek(this.readUint32());\n }\n\n const value = IFDValue.readData(this, type, numValues);\n ifd.fields.set(tag, value);\n\n // Read sub-IFDs\n if (tag === 0x8769 || tag === 0x8825) {\n let currentOffset = this.offset;\n let kind;\n if (tag === 0x8769) {\n kind = 'exif';\n } else if (tag === 0x8825) {\n kind = 'gps';\n }\n this._nextIFD = value;\n ifd[kind] = this.decodeIFD({\n kind,\n ignoreImageData: true\n });\n this.offset = currentOffset;\n }\n\n // go to the next entry\n this.seek(offset);\n this.skip(12);\n }\n\n decodeImageData(ifd) {\n const orientation = ifd.orientation;\n if (orientation && orientation !== 1) {\n unsupported('orientation', orientation);\n }\n switch (ifd.type) {\n case 1: // BlackIsZero\n case 2: // RGB\n this.readStripData(ifd);\n break;\n default:\n unsupported('image type', ifd.type);\n break;\n }\n }\n\n readStripData(ifd) {\n const width = ifd.width;\n const height = ifd.height;\n\n const bitDepth = validateBitDepth(ifd.bitsPerSample);\n const sampleFormat = ifd.sampleFormat;\n let size = width * height;\n const data = getDataArray(size, 1, bitDepth, sampleFormat);\n\n const compression = ifd.compression;\n const rowsPerStrip = ifd.rowsPerStrip;\n const maxPixels = rowsPerStrip * width;\n const stripOffsets = ifd.stripOffsets;\n const stripByteCounts = ifd.stripByteCounts;\n\n var pixel = 0;\n for (var i = 0; i < stripOffsets.length; i++) {\n var stripData = this.getStripData(compression, stripOffsets[i], stripByteCounts[i]);\n // Last strip can be smaller\n var length = size > maxPixels ? maxPixels : size;\n size -= length;\n if (bitDepth === 8) {\n pixel = fill8bit(data, stripData, pixel, length);\n } else if (bitDepth === 16) {\n pixel = fill16bit(data, stripData, pixel, length, this.isLittleEndian());\n } else if (bitDepth === 32 && sampleFormat === 3) {\n pixel = fillFloat32(data, stripData, pixel, length, this.isLittleEndian());\n } else {\n unsupported('bitDepth', bitDepth);\n }\n }\n\n ifd.data = data;\n }\n\n getStripData(compression, offset, byteCounts) {\n switch (compression) {\n case 1: // No compression\n return new DataView(this.buffer, offset, byteCounts);\n case 2: // CCITT Group 3 1-Dimensional Modified Huffman run length encoding\n case 32773: // PackBits compression\n return unsupported('Compression', compression);\n default:\n throw new Error('invalid compression: ' + compression);\n }\n }\n}\n\nmodule.exports = TIFFDecoder;\n\nfunction getDataArray(size, channels, bitDepth, sampleFormat) {\n if (bitDepth === 8) {\n return new Uint8Array(size * channels);\n } else if (bitDepth === 16) {\n return new Uint16Array(size * channels);\n } else if (bitDepth === 32 && sampleFormat === 3) {\n return new Float32Array(size * channels);\n } else {\n return unsupported('bit depth / sample format', bitDepth + ' / ' + sampleFormat);\n }\n}\n\nfunction fill8bit(dataTo, dataFrom, index, length) {\n for (var i = 0; i < length; i++) {\n dataTo[index++] = dataFrom.getUint8(i);\n }\n return index;\n}\n\nfunction fill16bit(dataTo, dataFrom, index, length, littleEndian) {\n for (var i = 0; i < length * 2; i += 2) {\n dataTo[index++] = dataFrom.getUint16(i, littleEndian);\n }\n return index;\n}\n\nfunction fillFloat32(dataTo, dataFrom, index, length, littleEndian) {\n for (var i = 0; i < length * 4; i += 4) {\n dataTo[index++] = dataFrom.getFloat32(i, littleEndian);\n }\n return index;\n}\n\nfunction unsupported(type, value) {\n throw new Error('Unsupported ' + type + ': ' + value);\n}\n\nfunction validateBitDepth(bitDepth) {\n if (bitDepth.length) {\n const bitDepthArray = bitDepth;\n bitDepth = bitDepthArray[0];\n for (var i = 0; i < bitDepthArray.length; i++) {\n if (bitDepthArray[i] !== bitDepth) {\n unsupported('bit depth', bitDepthArray);\n }\n }\n }\n return bitDepth;\n}\n","'use strict';\n\nconst TIFFDecoder = require('./tiffDecoder');\n\nmodule.exports = function decodeTIFF(data, options) {\n const decoder = new TIFFDecoder(data, options);\n return decoder.decode(options);\n};\n","'use strict';\n\nexports.decode = require('./decode');\n","'use strict';\n\nconst IOBuffer = require('iobuffer');\nconst tiff = require('tiff');\n\nfunction decode(data) {\n const buffer = new IOBuffer(data);\n const result = {};\n buffer.setBigEndian();\n const val = buffer.readUint16();\n if (val !== 0xffd8) {\n throw new Error('SOI marker not found. Not a valid JPEG file');\n }\n const next = buffer.readUint16();\n if (next === 0xffe1) {\n const length = buffer.readUint16();\n const header = buffer.readBytes(6);\n if (header[0] === 69 && // E\n header[1] === 120 && // x\n header[2] === 105 && // i\n header[3] === 102 && // f\n header[4] === 0 &&\n header[5] === 0) {\n // buffer.skip(2);\n const exif = tiff.decode(buffer, {\n onlyFirst: true,\n ignoreImageData: true,\n offset: buffer.offset\n });\n result.exif = exif;\n }\n }\n return result;\n}\n\nmodule.exports = decode;\n","'use strict';\n\nexports.decode = require('./decode');\n","'use strict';\nconst toBytes = s => [...s].map(c => c.charCodeAt(0));\nconst xpiZipFilename = toBytes('META-INF/mozilla.rsa');\nconst oxmlContentTypes = toBytes('[Content_Types].xml');\nconst oxmlRels = toBytes('_rels/.rels');\n\nfunction readUInt64LE(buf, offset = 0) {\n\tlet n = buf[offset];\n\tlet mul = 1;\n\tlet i = 0;\n\twhile (++i < 8) {\n\t\tmul *= 0x100;\n\t\tn += buf[offset + i] * mul;\n\t}\n\n\treturn n;\n}\n\nconst fileType = input => {\n\tif (!(input instanceof Uint8Array || input instanceof ArrayBuffer || Buffer.isBuffer(input))) {\n\t\tthrow new TypeError(`Expected the \\`input\\` argument to be of type \\`Uint8Array\\` or \\`Buffer\\` or \\`ArrayBuffer\\`, got \\`${typeof input}\\``);\n\t}\n\n\tconst buf = input instanceof Uint8Array ? input : new Uint8Array(input);\n\n\tif (!(buf && buf.length > 1)) {\n\t\treturn null;\n\t}\n\n\tconst check = (header, options) => {\n\t\toptions = Object.assign({\n\t\t\toffset: 0\n\t\t}, options);\n\n\t\tfor (let i = 0; i < header.length; i++) {\n\t\t\t// If a bitmask is set\n\t\t\tif (options.mask) {\n\t\t\t\t// If header doesn't equal `buf` with bits masked off\n\t\t\t\tif (header[i] !== (options.mask[i] & buf[i + options.offset])) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t} else if (header[i] !== buf[i + options.offset]) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t};\n\n\tconst checkString = (header, options) => check(toBytes(header), options);\n\n\tif (check([0xFF, 0xD8, 0xFF])) {\n\t\treturn {\n\t\t\text: 'jpg',\n\t\t\tmime: 'image/jpeg'\n\t\t};\n\t}\n\n\tif (check([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A])) {\n\t\treturn {\n\t\t\text: 'png',\n\t\t\tmime: 'image/png'\n\t\t};\n\t}\n\n\tif (check([0x47, 0x49, 0x46])) {\n\t\treturn {\n\t\t\text: 'gif',\n\t\t\tmime: 'image/gif'\n\t\t};\n\t}\n\n\tif (check([0x57, 0x45, 0x42, 0x50], {offset: 8})) {\n\t\treturn {\n\t\t\text: 'webp',\n\t\t\tmime: 'image/webp'\n\t\t};\n\t}\n\n\tif (check([0x46, 0x4C, 0x49, 0x46])) {\n\t\treturn {\n\t\t\text: 'flif',\n\t\t\tmime: 'image/flif'\n\t\t};\n\t}\n\n\t// Needs to be before `tif` check\n\tif (\n\t\t(check([0x49, 0x49, 0x2A, 0x0]) || check([0x4D, 0x4D, 0x0, 0x2A])) &&\n\t\tcheck([0x43, 0x52], {offset: 8})\n\t) {\n\t\treturn {\n\t\t\text: 'cr2',\n\t\t\tmime: 'image/x-canon-cr2'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x49, 0x49, 0x2A, 0x0]) ||\n\t\tcheck([0x4D, 0x4D, 0x0, 0x2A])\n\t) {\n\t\treturn {\n\t\t\text: 'tif',\n\t\t\tmime: 'image/tiff'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x4D])) {\n\t\treturn {\n\t\t\text: 'bmp',\n\t\t\tmime: 'image/bmp'\n\t\t};\n\t}\n\n\tif (check([0x49, 0x49, 0xBC])) {\n\t\treturn {\n\t\t\text: 'jxr',\n\t\t\tmime: 'image/vnd.ms-photo'\n\t\t};\n\t}\n\n\tif (check([0x38, 0x42, 0x50, 0x53])) {\n\t\treturn {\n\t\t\text: 'psd',\n\t\t\tmime: 'image/vnd.adobe.photoshop'\n\t\t};\n\t}\n\n\t// Zip-based file formats\n\t// Need to be before the `zip` check\n\tif (check([0x50, 0x4B, 0x3, 0x4])) {\n\t\tif (\n\t\t\tcheck([0x6D, 0x69, 0x6D, 0x65, 0x74, 0x79, 0x70, 0x65, 0x61, 0x70, 0x70, 0x6C, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6F, 0x6E, 0x2F, 0x65, 0x70, 0x75, 0x62, 0x2B, 0x7A, 0x69, 0x70], {offset: 30})\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'epub',\n\t\t\t\tmime: 'application/epub+zip'\n\t\t\t};\n\t\t}\n\n\t\t// Assumes signed `.xpi` from addons.mozilla.org\n\t\tif (check(xpiZipFilename, {offset: 30})) {\n\t\t\treturn {\n\t\t\t\text: 'xpi',\n\t\t\t\tmime: 'application/x-xpinstall'\n\t\t\t};\n\t\t}\n\n\t\tif (checkString('mimetypeapplication/vnd.oasis.opendocument.text', {offset: 30})) {\n\t\t\treturn {\n\t\t\t\text: 'odt',\n\t\t\t\tmime: 'application/vnd.oasis.opendocument.text'\n\t\t\t};\n\t\t}\n\n\t\tif (checkString('mimetypeapplication/vnd.oasis.opendocument.spreadsheet', {offset: 30})) {\n\t\t\treturn {\n\t\t\t\text: 'ods',\n\t\t\t\tmime: 'application/vnd.oasis.opendocument.spreadsheet'\n\t\t\t};\n\t\t}\n\n\t\tif (checkString('mimetypeapplication/vnd.oasis.opendocument.presentation', {offset: 30})) {\n\t\t\treturn {\n\t\t\t\text: 'odp',\n\t\t\t\tmime: 'application/vnd.oasis.opendocument.presentation'\n\t\t\t};\n\t\t}\n\n\t\t// The docx, xlsx and pptx file types extend the Office Open XML file format:\n\t\t// https://en.wikipedia.org/wiki/Office_Open_XML_file_formats\n\t\t// We look for:\n\t\t// - one entry named '[Content_Types].xml' or '_rels/.rels',\n\t\t// - one entry indicating specific type of file.\n\t\t// MS Office, OpenOffice and LibreOffice may put the parts in different order, so the check should not rely on it.\n\t\tconst findNextZipHeaderIndex = (arr, startAt = 0) => arr.findIndex((el, i, arr) => i >= startAt && arr[i] === 0x50 && arr[i + 1] === 0x4B && arr[i + 2] === 0x3 && arr[i + 3] === 0x4);\n\n\t\tlet zipHeaderIndex = 0; // The first zip header was already found at index 0\n\t\tlet oxmlFound = false;\n\t\tlet type = null;\n\n\t\tdo {\n\t\t\tconst offset = zipHeaderIndex + 30;\n\n\t\t\tif (!oxmlFound) {\n\t\t\t\toxmlFound = (check(oxmlContentTypes, {offset}) || check(oxmlRels, {offset}));\n\t\t\t}\n\n\t\t\tif (!type) {\n\t\t\t\tif (checkString('word/', {offset})) {\n\t\t\t\t\ttype = {\n\t\t\t\t\t\text: 'docx',\n\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'\n\t\t\t\t\t};\n\t\t\t\t} else if (checkString('ppt/', {offset})) {\n\t\t\t\t\ttype = {\n\t\t\t\t\t\text: 'pptx',\n\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.presentationml.presentation'\n\t\t\t\t\t};\n\t\t\t\t} else if (checkString('xl/', {offset})) {\n\t\t\t\t\ttype = {\n\t\t\t\t\t\text: 'xlsx',\n\t\t\t\t\t\tmime: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (oxmlFound && type) {\n\t\t\t\treturn type;\n\t\t\t}\n\n\t\t\tzipHeaderIndex = findNextZipHeaderIndex(buf, offset);\n\t\t} while (zipHeaderIndex >= 0);\n\n\t\t// No more zip parts available in the buffer, but maybe we are almost certain about the type?\n\t\tif (type) {\n\t\t\treturn type;\n\t\t}\n\t}\n\n\tif (\n\t\tcheck([0x50, 0x4B]) &&\n\t\t(buf[2] === 0x3 || buf[2] === 0x5 || buf[2] === 0x7) &&\n\t\t(buf[3] === 0x4 || buf[3] === 0x6 || buf[3] === 0x8)\n\t) {\n\t\treturn {\n\t\t\text: 'zip',\n\t\t\tmime: 'application/zip'\n\t\t};\n\t}\n\n\tif (check([0x75, 0x73, 0x74, 0x61, 0x72], {offset: 257})) {\n\t\treturn {\n\t\t\text: 'tar',\n\t\t\tmime: 'application/x-tar'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x52, 0x61, 0x72, 0x21, 0x1A, 0x7]) &&\n\t\t(buf[6] === 0x0 || buf[6] === 0x1)\n\t) {\n\t\treturn {\n\t\t\text: 'rar',\n\t\t\tmime: 'application/x-rar-compressed'\n\t\t};\n\t}\n\n\tif (check([0x1F, 0x8B, 0x8])) {\n\t\treturn {\n\t\t\text: 'gz',\n\t\t\tmime: 'application/gzip'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x5A, 0x68])) {\n\t\treturn {\n\t\t\text: 'bz2',\n\t\t\tmime: 'application/x-bzip2'\n\t\t};\n\t}\n\n\tif (check([0x37, 0x7A, 0xBC, 0xAF, 0x27, 0x1C])) {\n\t\treturn {\n\t\t\text: '7z',\n\t\t\tmime: 'application/x-7z-compressed'\n\t\t};\n\t}\n\n\tif (check([0x78, 0x01])) {\n\t\treturn {\n\t\t\text: 'dmg',\n\t\t\tmime: 'application/x-apple-diskimage'\n\t\t};\n\t}\n\n\tif (check([0x33, 0x67, 0x70, 0x35]) || // 3gp5\n\t\t(\n\t\t\tcheck([0x0, 0x0, 0x0]) && check([0x66, 0x74, 0x79, 0x70], {offset: 4}) &&\n\t\t\t\t(\n\t\t\t\t\tcheck([0x6D, 0x70, 0x34, 0x31], {offset: 8}) || // MP41\n\t\t\t\t\tcheck([0x6D, 0x70, 0x34, 0x32], {offset: 8}) || // MP42\n\t\t\t\t\tcheck([0x69, 0x73, 0x6F, 0x6D], {offset: 8}) || // ISOM\n\t\t\t\t\tcheck([0x69, 0x73, 0x6F, 0x32], {offset: 8}) || // ISO2\n\t\t\t\t\tcheck([0x6D, 0x6D, 0x70, 0x34], {offset: 8}) || // MMP4\n\t\t\t\t\tcheck([0x4D, 0x34, 0x56], {offset: 8}) || // M4V\n\t\t\t\t\tcheck([0x64, 0x61, 0x73, 0x68], {offset: 8}) // DASH\n\t\t\t\t)\n\t\t)) {\n\t\treturn {\n\t\t\text: 'mp4',\n\t\t\tmime: 'video/mp4'\n\t\t};\n\t}\n\n\tif (check([0x4D, 0x54, 0x68, 0x64])) {\n\t\treturn {\n\t\t\text: 'mid',\n\t\t\tmime: 'audio/midi'\n\t\t};\n\t}\n\n\t// https://github.com/threatstack/libmagic/blob/master/magic/Magdir/matroska\n\tif (check([0x1A, 0x45, 0xDF, 0xA3])) {\n\t\tconst sliced = buf.subarray(4, 4 + 4096);\n\t\tconst idPos = sliced.findIndex((el, i, arr) => arr[i] === 0x42 && arr[i + 1] === 0x82);\n\n\t\tif (idPos !== -1) {\n\t\t\tconst docTypePos = idPos + 3;\n\t\t\tconst findDocType = type => [...type].every((c, i) => sliced[docTypePos + i] === c.charCodeAt(0));\n\n\t\t\tif (findDocType('matroska')) {\n\t\t\t\treturn {\n\t\t\t\t\text: 'mkv',\n\t\t\t\t\tmime: 'video/x-matroska'\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (findDocType('webm')) {\n\t\t\t\treturn {\n\t\t\t\t\text: 'webm',\n\t\t\t\t\tmime: 'video/webm'\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\tif (check([0x0, 0x0, 0x0, 0x14, 0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20]) ||\n\t\tcheck([0x66, 0x72, 0x65, 0x65], {offset: 4}) || // Type: `free`\n\t\tcheck([0x66, 0x74, 0x79, 0x70, 0x71, 0x74, 0x20, 0x20], {offset: 4}) ||\n\t\tcheck([0x6D, 0x64, 0x61, 0x74], {offset: 4}) || // MJPEG\n\t\tcheck([0x6D, 0x6F, 0x6F, 0x76], {offset: 4}) || // Type: `moov`\n\t\tcheck([0x77, 0x69, 0x64, 0x65], {offset: 4})) {\n\t\treturn {\n\t\t\text: 'mov',\n\t\t\tmime: 'video/quicktime'\n\t\t};\n\t}\n\n\t// RIFF file format which might be AVI, WAV, QCP, etc\n\tif (check([0x52, 0x49, 0x46, 0x46])) {\n\t\tif (check([0x41, 0x56, 0x49], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'avi',\n\t\t\t\tmime: 'video/vnd.avi'\n\t\t\t};\n\t\t}\n\n\t\tif (check([0x57, 0x41, 0x56, 0x45], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'wav',\n\t\t\t\tmime: 'audio/vnd.wave'\n\t\t\t};\n\t\t}\n\n\t\t// QLCM, QCP file\n\t\tif (check([0x51, 0x4C, 0x43, 0x4D], {offset: 8})) {\n\t\t\treturn {\n\t\t\t\text: 'qcp',\n\t\t\t\tmime: 'audio/qcelp'\n\t\t\t};\n\t\t}\n\t}\n\n\t// ASF_Header_Object first 80 bytes\n\tif (check([0x30, 0x26, 0xB2, 0x75, 0x8E, 0x66, 0xCF, 0x11, 0xA6, 0xD9])) {\n\t\t// Search for header should be in first 1KB of file.\n\n\t\tlet offset = 30;\n\t\tdo {\n\t\t\tconst objectSize = readUInt64LE(buf, offset + 16);\n\t\t\tif (check([0x91, 0x07, 0xDC, 0xB7, 0xB7, 0xA9, 0xCF, 0x11, 0x8E, 0xE6, 0x00, 0xC0, 0x0C, 0x20, 0x53, 0x65], {offset})) {\n\t\t\t\t// Sync on Stream-Properties-Object (B7DC0791-A9B7-11CF-8EE6-00C00C205365)\n\t\t\t\tif (check([0x40, 0x9E, 0x69, 0xF8, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B], {offset: offset + 24})) {\n\t\t\t\t\t// Found audio:\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'wma',\n\t\t\t\t\t\tmime: 'audio/x-ms-wma'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tif (check([0xC0, 0xEF, 0x19, 0xBC, 0x4D, 0x5B, 0xCF, 0x11, 0xA8, 0xFD, 0x00, 0x80, 0x5F, 0x5C, 0x44, 0x2B], {offset: offset + 24})) {\n\t\t\t\t\t// Found video:\n\t\t\t\t\treturn {\n\t\t\t\t\t\text: 'wmv',\n\t\t\t\t\t\tmime: 'video/x-ms-asf'\n\t\t\t\t\t};\n\t\t\t\t}\n\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\toffset += objectSize;\n\t\t} while (offset + 24 <= buf.length);\n\n\t\t// Default to ASF generic extension\n\t\treturn {\n\t\t\text: 'asf',\n\t\t\tmime: 'application/vnd.ms-asf'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x0, 0x0, 0x1, 0xBA]) ||\n\t\tcheck([0x0, 0x0, 0x1, 0xB3])\n\t) {\n\t\treturn {\n\t\t\text: 'mpg',\n\t\t\tmime: 'video/mpeg'\n\t\t};\n\t}\n\n\tif (check([0x66, 0x74, 0x79, 0x70, 0x33, 0x67], {offset: 4})) {\n\t\treturn {\n\t\t\text: '3gp',\n\t\t\tmime: 'video/3gpp'\n\t\t};\n\t}\n\n\t// Check for MPEG header at different starting offsets\n\tfor (let start = 0; start < 2 && start < (buf.length - 16); start++) {\n\t\tif (\n\t\t\tcheck([0x49, 0x44, 0x33], {offset: start}) || // ID3 header\n\t\t\tcheck([0xFF, 0xE2], {offset: start, mask: [0xFF, 0xE2]}) // MPEG 1 or 2 Layer 3 header\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'mp3',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\tif (\n\t\t\tcheck([0xFF, 0xE4], {offset: start, mask: [0xFF, 0xE4]}) // MPEG 1 or 2 Layer 2 header\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'mp2',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\tif (\n\t\t\tcheck([0xFF, 0xF8], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 2 layer 0 using ADTS\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'mp2',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\n\t\tif (\n\t\t\tcheck([0xFF, 0xF0], {offset: start, mask: [0xFF, 0xFC]}) // MPEG 4 layer 0 using ADTS\n\t\t) {\n\t\t\treturn {\n\t\t\t\text: 'mp4',\n\t\t\t\tmime: 'audio/mpeg'\n\t\t\t};\n\t\t}\n\t}\n\n\tif (\n\t\tcheck([0x66, 0x74, 0x79, 0x70, 0x4D, 0x34, 0x41], {offset: 4})\n\t) {\n\t\treturn { // MPEG-4 layer 3 (audio)\n\t\t\text: 'm4a',\n\t\t\tmime: 'audio/mp4' // RFC 4337\n\t\t};\n\t}\n\n\t// Needs to be before `ogg` check\n\tif (check([0x4F, 0x70, 0x75, 0x73, 0x48, 0x65, 0x61, 0x64], {offset: 28})) {\n\t\treturn {\n\t\t\text: 'opus',\n\t\t\tmime: 'audio/opus'\n\t\t};\n\t}\n\n\t// If 'OggS' in first bytes, then OGG container\n\tif (check([0x4F, 0x67, 0x67, 0x53])) {\n\t\t// This is a OGG container\n\n\t\t// If ' theora' in header.\n\t\tif (check([0x80, 0x74, 0x68, 0x65, 0x6F, 0x72, 0x61], {offset: 28})) {\n\t\t\treturn {\n\t\t\t\text: 'ogv',\n\t\t\t\tmime: 'video/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If '\\x01video' in header.\n\t\tif (check([0x01, 0x76, 0x69, 0x64, 0x65, 0x6F, 0x00], {offset: 28})) {\n\t\t\treturn {\n\t\t\t\text: 'ogm',\n\t\t\t\tmime: 'video/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If ' FLAC' in header https://xiph.org/flac/faq.html\n\t\tif (check([0x7F, 0x46, 0x4C, 0x41, 0x43], {offset: 28})) {\n\t\t\treturn {\n\t\t\t\text: 'oga',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// 'Speex ' in header https://en.wikipedia.org/wiki/Speex\n\t\tif (check([0x53, 0x70, 0x65, 0x65, 0x78, 0x20, 0x20], {offset: 28})) {\n\t\t\treturn {\n\t\t\t\text: 'spx',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// If '\\x01vorbis' in header\n\t\tif (check([0x01, 0x76, 0x6F, 0x72, 0x62, 0x69, 0x73], {offset: 28})) {\n\t\t\treturn {\n\t\t\t\text: 'ogg',\n\t\t\t\tmime: 'audio/ogg'\n\t\t\t};\n\t\t}\n\n\t\t// Default OGG container https://www.iana.org/assignments/media-types/application/ogg\n\t\treturn {\n\t\t\text: 'ogx',\n\t\t\tmime: 'application/ogg'\n\t\t};\n\t}\n\n\tif (check([0x66, 0x4C, 0x61, 0x43])) {\n\t\treturn {\n\t\t\text: 'flac',\n\t\t\tmime: 'audio/x-flac'\n\t\t};\n\t}\n\n\tif (check([0x4D, 0x41, 0x43, 0x20])) { // 'MAC '\n\t\treturn {\n\t\t\text: 'ape',\n\t\t\tmime: 'audio/ape'\n\t\t};\n\t}\n\n\tif (check([0x77, 0x76, 0x70, 0x6B])) { // 'wvpk'\n\t\treturn {\n\t\t\text: 'wv',\n\t\t\tmime: 'audio/wavpack'\n\t\t};\n\t}\n\n\tif (check([0x23, 0x21, 0x41, 0x4D, 0x52, 0x0A])) {\n\t\treturn {\n\t\t\text: 'amr',\n\t\t\tmime: 'audio/amr'\n\t\t};\n\t}\n\n\tif (check([0x25, 0x50, 0x44, 0x46])) {\n\t\treturn {\n\t\t\text: 'pdf',\n\t\t\tmime: 'application/pdf'\n\t\t};\n\t}\n\n\tif (check([0x4D, 0x5A])) {\n\t\treturn {\n\t\t\text: 'exe',\n\t\t\tmime: 'application/x-msdownload'\n\t\t};\n\t}\n\n\tif (\n\t\t(buf[0] === 0x43 || buf[0] === 0x46) &&\n\t\tcheck([0x57, 0x53], {offset: 1})\n\t) {\n\t\treturn {\n\t\t\text: 'swf',\n\t\t\tmime: 'application/x-shockwave-flash'\n\t\t};\n\t}\n\n\tif (check([0x7B, 0x5C, 0x72, 0x74, 0x66])) {\n\t\treturn {\n\t\t\text: 'rtf',\n\t\t\tmime: 'application/rtf'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x61, 0x73, 0x6D])) {\n\t\treturn {\n\t\t\text: 'wasm',\n\t\t\tmime: 'application/wasm'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x77, 0x4F, 0x46, 0x46]) &&\n\t\t(\n\t\t\tcheck([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||\n\t\t\tcheck([0x4F, 0x54, 0x54, 0x4F], {offset: 4})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'woff',\n\t\t\tmime: 'font/woff'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x77, 0x4F, 0x46, 0x32]) &&\n\t\t(\n\t\t\tcheck([0x00, 0x01, 0x00, 0x00], {offset: 4}) ||\n\t\t\tcheck([0x4F, 0x54, 0x54, 0x4F], {offset: 4})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'woff2',\n\t\t\tmime: 'font/woff2'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x4C, 0x50], {offset: 34}) &&\n\t\t(\n\t\t\tcheck([0x00, 0x00, 0x01], {offset: 8}) ||\n\t\t\tcheck([0x01, 0x00, 0x02], {offset: 8}) ||\n\t\t\tcheck([0x02, 0x00, 0x02], {offset: 8})\n\t\t)\n\t) {\n\t\treturn {\n\t\t\text: 'eot',\n\t\t\tmime: 'application/vnd.ms-fontobject'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x01, 0x00, 0x00, 0x00])) {\n\t\treturn {\n\t\t\text: 'ttf',\n\t\t\tmime: 'font/ttf'\n\t\t};\n\t}\n\n\tif (check([0x4F, 0x54, 0x54, 0x4F, 0x00])) {\n\t\treturn {\n\t\t\text: 'otf',\n\t\t\tmime: 'font/otf'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x01, 0x00])) {\n\t\treturn {\n\t\t\text: 'ico',\n\t\t\tmime: 'image/x-icon'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x02, 0x00])) {\n\t\treturn {\n\t\t\text: 'cur',\n\t\t\tmime: 'image/x-icon'\n\t\t};\n\t}\n\n\tif (check([0x46, 0x4C, 0x56, 0x01])) {\n\t\treturn {\n\t\t\text: 'flv',\n\t\t\tmime: 'video/x-flv'\n\t\t};\n\t}\n\n\tif (check([0x25, 0x21])) {\n\t\treturn {\n\t\t\text: 'ps',\n\t\t\tmime: 'application/postscript'\n\t\t};\n\t}\n\n\tif (check([0xFD, 0x37, 0x7A, 0x58, 0x5A, 0x00])) {\n\t\treturn {\n\t\t\text: 'xz',\n\t\t\tmime: 'application/x-xz'\n\t\t};\n\t}\n\n\tif (check([0x53, 0x51, 0x4C, 0x69])) {\n\t\treturn {\n\t\t\text: 'sqlite',\n\t\t\tmime: 'application/x-sqlite3'\n\t\t};\n\t}\n\n\tif (check([0x4E, 0x45, 0x53, 0x1A])) {\n\t\treturn {\n\t\t\text: 'nes',\n\t\t\tmime: 'application/x-nintendo-nes-rom'\n\t\t};\n\t}\n\n\tif (check([0x43, 0x72, 0x32, 0x34])) {\n\t\treturn {\n\t\t\text: 'crx',\n\t\t\tmime: 'application/x-google-chrome-extension'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x4D, 0x53, 0x43, 0x46]) ||\n\t\tcheck([0x49, 0x53, 0x63, 0x28])\n\t) {\n\t\treturn {\n\t\t\text: 'cab',\n\t\t\tmime: 'application/vnd.ms-cab-compressed'\n\t\t};\n\t}\n\n\t// Needs to be before `ar` check\n\tif (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E, 0x0A, 0x64, 0x65, 0x62, 0x69, 0x61, 0x6E, 0x2D, 0x62, 0x69, 0x6E, 0x61, 0x72, 0x79])) {\n\t\treturn {\n\t\t\text: 'deb',\n\t\t\tmime: 'application/x-deb'\n\t\t};\n\t}\n\n\tif (check([0x21, 0x3C, 0x61, 0x72, 0x63, 0x68, 0x3E])) {\n\t\treturn {\n\t\t\text: 'ar',\n\t\t\tmime: 'application/x-unix-archive'\n\t\t};\n\t}\n\n\tif (check([0xED, 0xAB, 0xEE, 0xDB])) {\n\t\treturn {\n\t\t\text: 'rpm',\n\t\t\tmime: 'application/x-rpm'\n\t\t};\n\t}\n\n\tif (\n\t\tcheck([0x1F, 0xA0]) ||\n\t\tcheck([0x1F, 0x9D])\n\t) {\n\t\treturn {\n\t\t\text: 'Z',\n\t\t\tmime: 'application/x-compress'\n\t\t};\n\t}\n\n\tif (check([0x4C, 0x5A, 0x49, 0x50])) {\n\t\treturn {\n\t\t\text: 'lz',\n\t\t\tmime: 'application/x-lzip'\n\t\t};\n\t}\n\n\tif (check([0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1])) {\n\t\treturn {\n\t\t\text: 'msi',\n\t\t\tmime: 'application/x-msi'\n\t\t};\n\t}\n\n\tif (check([0x06, 0x0E, 0x2B, 0x34, 0x02, 0x05, 0x01, 0x01, 0x0D, 0x01, 0x02, 0x01, 0x01, 0x02])) {\n\t\treturn {\n\t\t\text: 'mxf',\n\t\t\tmime: 'application/mxf'\n\t\t};\n\t}\n\n\tif (check([0x47], {offset: 4}) && (check([0x47], {offset: 192}) || check([0x47], {offset: 196}))) {\n\t\treturn {\n\t\t\text: 'mts',\n\t\t\tmime: 'video/mp2t'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x4C, 0x45, 0x4E, 0x44, 0x45, 0x52])) {\n\t\treturn {\n\t\t\text: 'blend',\n\t\t\tmime: 'application/x-blender'\n\t\t};\n\t}\n\n\tif (check([0x42, 0x50, 0x47, 0xFB])) {\n\t\treturn {\n\t\t\text: 'bpg',\n\t\t\tmime: 'image/bpg'\n\t\t};\n\t}\n\n\tif (check([0x00, 0x00, 0x00, 0x0C, 0x6A, 0x50, 0x20, 0x20, 0x0D, 0x0A, 0x87, 0x0A])) {\n\t\t// JPEG-2000 family\n\n\t\tif (check([0x6A, 0x70, 0x32, 0x20], {offset: 20})) {\n\t\t\treturn {\n\t\t\t\text: 'jp2',\n\t\t\t\tmime: 'image/jp2'\n\t\t\t};\n\t\t}\n\n\t\tif (check([0x6A, 0x70, 0x78, 0x20], {offset: 20})) {\n\t\t\treturn {\n\t\t\t\text: 'jpx',\n\t\t\t\tmime: 'image/jpx'\n\t\t\t};\n\t\t}\n\n\t\tif (check([0x6A, 0x70, 0x6D, 0x20], {offset: 20})) {\n\t\t\treturn {\n\t\t\t\text: 'jpm',\n\t\t\t\tmime: 'image/jpm'\n\t\t\t};\n\t\t}\n\n\t\tif (check([0x6D, 0x6A, 0x70, 0x32], {offset: 20})) {\n\t\t\treturn {\n\t\t\t\text: 'mj2',\n\t\t\t\tmime: 'image/mj2'\n\t\t\t};\n\t\t}\n\t}\n\n\tif (check([0x46, 0x4F, 0x52, 0x4D])) {\n\t\treturn {\n\t\t\text: 'aif',\n\t\t\tmime: 'audio/aiff'\n\t\t};\n\t}\n\n\tif (checkString(' new Promise((resolve, reject) => {\n\t// Using `eval` to work around issues when bundling with Webpack\n\tconst stream = eval('require')('stream'); // eslint-disable-line no-eval\n\n\treadableStream.once('readable', () => {\n\t\tconst pass = new stream.PassThrough();\n\t\tconst chunk = readableStream.read(module.exports.minimumBytes) || readableStream.read();\n\t\ttry {\n\t\t\tpass.fileType = fileType(chunk);\n\t\t} catch (error) {\n\t\t\treject(error);\n\t\t}\n\n\t\treadableStream.unshift(chunk);\n\n\t\tif (stream.pipeline) {\n\t\t\tresolve(stream.pipeline(readableStream, pass, () => {}));\n\t\t} else {\n\t\t\tresolve(readableStream.pipe(pass));\n\t\t}\n\t});\n});\n","'use strict';\nconst fileType = require('file-type');\n\nconst imageExts = new Set([\n\t'jpg',\n\t'png',\n\t'gif',\n\t'webp',\n\t'flif',\n\t'cr2',\n\t'tif',\n\t'bmp',\n\t'jxr',\n\t'psd',\n\t'ico',\n\t'bpg',\n\t'jp2',\n\t'jpm',\n\t'jpx',\n\t'heic',\n\t'cur',\n\t'dcm'\n]);\n\nconst imageType = input => {\n\tconst ret = fileType(input);\n\treturn imageExts.has(ret && ret.ext) ? ret : null;\n};\n\nmodule.exports = imageType;\n// TODO: Remove this for the next major release\nmodule.exports.default = imageType;\n\nObject.defineProperty(imageType, 'minimumBytes', {value: fileType.minimumBytes});\n","// eslint-disable-next-line import/no-unassigned-import\nimport './text-encoding-polyfill';\nconst decoder = new TextDecoder('utf-8');\nexport function decode(bytes) {\n return decoder.decode(bytes);\n}\nconst encoder = new TextEncoder();\nexport function encode(str) {\n return encoder.encode(str);\n}\n//# sourceMappingURL=utf8.browser.js.map","import { decode, encode } from './utf8';\nconst defaultByteLength = 1024 * 8;\nexport class IOBuffer {\n /**\n * @param data - The data to construct the IOBuffer with.\n * If data is a number, it will be the new buffer's length
\n * If data is `undefined`, the buffer will be initialized with a default length of 8Kb
\n * If data is an ArrayBuffer, SharedArrayBuffer, an ArrayBufferView (Typed Array), an IOBuffer instance,\n * or a Node.js Buffer, a view will be created over the underlying ArrayBuffer.\n * @param options\n */\n constructor(data = defaultByteLength, options = {}) {\n let dataIsGiven = false;\n if (typeof data === 'number') {\n data = new ArrayBuffer(data);\n }\n else {\n dataIsGiven = true;\n this.lastWrittenByte = data.byteLength;\n }\n const offset = options.offset ? options.offset >>> 0 : 0;\n const byteLength = data.byteLength - offset;\n let dvOffset = offset;\n if (ArrayBuffer.isView(data) || data instanceof IOBuffer) {\n if (data.byteLength !== data.buffer.byteLength) {\n dvOffset = data.byteOffset + offset;\n }\n data = data.buffer;\n }\n if (dataIsGiven) {\n this.lastWrittenByte = byteLength;\n }\n else {\n this.lastWrittenByte = 0;\n }\n this.buffer = data;\n this.length = byteLength;\n this.byteLength = byteLength;\n this.byteOffset = dvOffset;\n this.offset = 0;\n this.littleEndian = true;\n this._data = new DataView(this.buffer, dvOffset, byteLength);\n this._mark = 0;\n this._marks = [];\n }\n /**\n * Checks if the memory allocated to the buffer is sufficient to store more\n * bytes after the offset.\n * @param byteLength - The needed memory in bytes.\n * @returns `true` if there is sufficient space and `false` otherwise.\n */\n available(byteLength = 1) {\n return this.offset + byteLength <= this.length;\n }\n /**\n * Check if little-endian mode is used for reading and writing multi-byte\n * values.\n * @returns `true` if little-endian mode is used, `false` otherwise.\n */\n isLittleEndian() {\n return this.littleEndian;\n }\n /**\n * Set little-endian mode for reading and writing multi-byte values.\n */\n setLittleEndian() {\n this.littleEndian = true;\n return this;\n }\n /**\n * Check if big-endian mode is used for reading and writing multi-byte values.\n * @returns `true` if big-endian mode is used, `false` otherwise.\n */\n isBigEndian() {\n return !this.littleEndian;\n }\n /**\n * Switches to big-endian mode for reading and writing multi-byte values.\n */\n setBigEndian() {\n this.littleEndian = false;\n return this;\n }\n /**\n * Move the pointer n bytes forward.\n * @param n - Number of bytes to skip.\n */\n skip(n = 1) {\n this.offset += n;\n return this;\n }\n /**\n * Move the pointer to the given offset.\n * @param offset\n */\n seek(offset) {\n this.offset = offset;\n return this;\n }\n /**\n * Store the current pointer offset.\n * @see {@link IOBuffer#reset}\n */\n mark() {\n this._mark = this.offset;\n return this;\n }\n /**\n * Move the pointer back to the last pointer offset set by mark.\n * @see {@link IOBuffer#mark}\n */\n reset() {\n this.offset = this._mark;\n return this;\n }\n /**\n * Push the current pointer offset to the mark stack.\n * @see {@link IOBuffer#popMark}\n */\n pushMark() {\n this._marks.push(this.offset);\n return this;\n }\n /**\n * Pop the last pointer offset from the mark stack, and set the current\n * pointer offset to the popped value.\n * @see {@link IOBuffer#pushMark}\n */\n popMark() {\n const offset = this._marks.pop();\n if (offset === undefined) {\n throw new Error('Mark stack empty');\n }\n this.seek(offset);\n return this;\n }\n /**\n * Move the pointer offset back to 0.\n */\n rewind() {\n this.offset = 0;\n return this;\n }\n /**\n * Make sure the buffer has sufficient memory to write a given byteLength at\n * the current pointer offset.\n * If the buffer's memory is insufficient, this method will create a new\n * buffer (a copy) with a length that is twice (byteLength + current offset).\n * @param byteLength\n */\n ensureAvailable(byteLength = 1) {\n if (!this.available(byteLength)) {\n const lengthNeeded = this.offset + byteLength;\n const newLength = lengthNeeded * 2;\n const newArray = new Uint8Array(newLength);\n newArray.set(new Uint8Array(this.buffer));\n this.buffer = newArray.buffer;\n this.length = this.byteLength = newLength;\n this._data = new DataView(this.buffer);\n }\n return this;\n }\n /**\n * Read a byte and return false if the byte's value is 0, or true otherwise.\n * Moves pointer forward by one byte.\n */\n readBoolean() {\n return this.readUint8() !== 0;\n }\n /**\n * Read a signed 8-bit integer and move pointer forward by 1 byte.\n */\n readInt8() {\n return this._data.getInt8(this.offset++);\n }\n /**\n * Read an unsigned 8-bit integer and move pointer forward by 1 byte.\n */\n readUint8() {\n return this._data.getUint8(this.offset++);\n }\n /**\n * Alias for {@link IOBuffer#readUint8}.\n */\n readByte() {\n return this.readUint8();\n }\n /**\n * Read `n` bytes and move pointer forward by `n` bytes.\n */\n readBytes(n = 1) {\n const bytes = new Uint8Array(n);\n for (let i = 0; i < n; i++) {\n bytes[i] = this.readByte();\n }\n return bytes;\n }\n /**\n * Read a 16-bit signed integer and move pointer forward by 2 bytes.\n */\n readInt16() {\n const value = this._data.getInt16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n /**\n * Read a 16-bit unsigned integer and move pointer forward by 2 bytes.\n */\n readUint16() {\n const value = this._data.getUint16(this.offset, this.littleEndian);\n this.offset += 2;\n return value;\n }\n /**\n * Read a 32-bit signed integer and move pointer forward by 4 bytes.\n */\n readInt32() {\n const value = this._data.getInt32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 32-bit unsigned integer and move pointer forward by 4 bytes.\n */\n readUint32() {\n const value = this._data.getUint32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 32-bit floating number and move pointer forward by 4 bytes.\n */\n readFloat32() {\n const value = this._data.getFloat32(this.offset, this.littleEndian);\n this.offset += 4;\n return value;\n }\n /**\n * Read a 64-bit floating number and move pointer forward by 8 bytes.\n */\n readFloat64() {\n const value = this._data.getFloat64(this.offset, this.littleEndian);\n this.offset += 8;\n return value;\n }\n /**\n * Read a 1-byte ASCII character and move pointer forward by 1 byte.\n */\n readChar() {\n return String.fromCharCode(this.readInt8());\n }\n /**\n * Read `n` 1-byte ASCII characters and move pointer forward by `n` bytes.\n */\n readChars(n = 1) {\n let result = '';\n for (let i = 0; i < n; i++) {\n result += this.readChar();\n }\n return result;\n }\n /**\n * Read the next `n` bytes, return a UTF-8 decoded string and move pointer\n * forward by `n` bytes.\n */\n readUtf8(n = 1) {\n return decode(this.readBytes(n));\n }\n /**\n * Write 0xff if the passed value is truthy, 0x00 otherwise and move pointer\n * forward by 1 byte.\n */\n writeBoolean(value) {\n this.writeUint8(value ? 0xff : 0x00);\n return this;\n }\n /**\n * Write `value` as an 8-bit signed integer and move pointer forward by 1 byte.\n */\n writeInt8(value) {\n this.ensureAvailable(1);\n this._data.setInt8(this.offset++, value);\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as an 8-bit unsigned integer and move pointer forward by 1\n * byte.\n */\n writeUint8(value) {\n this.ensureAvailable(1);\n this._data.setUint8(this.offset++, value);\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * An alias for {@link IOBuffer#writeUint8}.\n */\n writeByte(value) {\n return this.writeUint8(value);\n }\n /**\n * Write all elements of `bytes` as uint8 values and move pointer forward by\n * `bytes.length` bytes.\n */\n writeBytes(bytes) {\n this.ensureAvailable(bytes.length);\n for (let i = 0; i < bytes.length; i++) {\n this._data.setUint8(this.offset++, bytes[i]);\n }\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 16-bit signed integer and move pointer forward by 2\n * bytes.\n */\n writeInt16(value) {\n this.ensureAvailable(2);\n this._data.setInt16(this.offset, value, this.littleEndian);\n this.offset += 2;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 16-bit unsigned integer and move pointer forward by 2\n * bytes.\n */\n writeUint16(value) {\n this.ensureAvailable(2);\n this._data.setUint16(this.offset, value, this.littleEndian);\n this.offset += 2;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit signed integer and move pointer forward by 4\n * bytes.\n */\n writeInt32(value) {\n this.ensureAvailable(4);\n this._data.setInt32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit unsigned integer and move pointer forward by 4\n * bytes.\n */\n writeUint32(value) {\n this.ensureAvailable(4);\n this._data.setUint32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 32-bit floating number and move pointer forward by 4\n * bytes.\n */\n writeFloat32(value) {\n this.ensureAvailable(4);\n this._data.setFloat32(this.offset, value, this.littleEndian);\n this.offset += 4;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write `value` as a 64-bit floating number and move pointer forward by 8\n * bytes.\n */\n writeFloat64(value) {\n this.ensureAvailable(8);\n this._data.setFloat64(this.offset, value, this.littleEndian);\n this.offset += 8;\n this._updateLastWrittenByte();\n return this;\n }\n /**\n * Write the charCode of `str`'s first character as an 8-bit unsigned integer\n * and move pointer forward by 1 byte.\n */\n writeChar(str) {\n return this.writeUint8(str.charCodeAt(0));\n }\n /**\n * Write the charCodes of all `str`'s characters as 8-bit unsigned integers\n * and move pointer forward by `str.length` bytes.\n */\n writeChars(str) {\n for (let i = 0; i < str.length; i++) {\n this.writeUint8(str.charCodeAt(i));\n }\n return this;\n }\n /**\n * UTF-8 encode and write `str` to the current pointer offset and move pointer\n * forward according to the encoded length.\n */\n writeUtf8(str) {\n return this.writeBytes(encode(str));\n }\n /**\n * Export a Uint8Array view of the internal buffer.\n * The view starts at the byte offset and its length\n * is calculated to stop at the last written byte or the original length.\n */\n toArray() {\n return new Uint8Array(this.buffer, this.byteOffset, this.lastWrittenByte);\n }\n /**\n * Update the last written byte offset\n * @private\n */\n _updateLastWrittenByte() {\n if (this.offset > this.lastWrittenByte) {\n this.lastWrittenByte = this.offset;\n }\n }\n}\n//# sourceMappingURL=IOBuffer.js.map","// Section 14: Differencing Predictor (p. 64)\nexport function applyHorizontalDifferencing8Bit(data, width, components) {\n let i = 0;\n while (i < data.length) {\n for (let j = components; j < width * components; j += components) {\n for (let k = 0; k < components; k++) {\n data[i + j + k] =\n (data[i + j + k] + data[i + j - (components - k)]) & 255;\n }\n }\n i += width * components;\n }\n}\nexport function applyHorizontalDifferencing16Bit(data, width, components) {\n let i = 0;\n while (i < data.length) {\n for (let j = components; j < width * components; j += components) {\n for (let k = 0; k < components; k++) {\n data[i + j + k] =\n (data[i + j + k] + data[i + j - (components - k)]) & 65535;\n }\n }\n i += width * components;\n }\n}\n//# sourceMappingURL=horizontalDifferencing.js.map","const tagsById = {\n 0x829a: 'ExposureTime',\n 0x829d: 'FNumber',\n 0x8822: 'ExposureProgram',\n 0x8824: 'SpectralSensitivity',\n 0x8827: 'ISOSpeedRatings',\n 0x8828: 'OECF',\n 0x8830: 'SensitivityType',\n 0x8831: 'StandardOutputSensitivity',\n 0x8832: 'RecommendedExposureIndex',\n 0x8833: 'ISOSpeed',\n 0x8834: 'ISOSpeedLatitudeyyy',\n 0x8835: 'ISOSpeedLatitudezzz',\n 0x9000: 'ExifVersion',\n 0x9003: 'DateTimeOriginal',\n 0x9004: 'DateTimeDigitized',\n 0x9101: 'ComponentsConfiguration',\n 0x9102: 'CompressedBitsPerPixel',\n 0x9201: 'ShutterSpeedValue',\n 0x9202: 'ApertureValue',\n 0x9203: 'BrightnessValue',\n 0x9204: 'ExposureBiasValue',\n 0x9205: 'MaxApertureValue',\n 0x9206: 'SubjectDistance',\n 0x9207: 'MeteringMode',\n 0x9208: 'LightSource',\n 0x9209: 'Flash',\n 0x920a: 'FocalLength',\n 0x9214: 'SubjectArea',\n 0x927c: 'MakerNote',\n 0x9286: 'UserComment',\n 0x9290: 'SubsecTime',\n 0x9291: 'SubsecTimeOriginal',\n 0x9292: 'SubsecTimeDigitized',\n 0xa000: 'FlashpixVersion',\n 0xa001: 'ColorSpace',\n 0xa002: 'PixelXDimension',\n 0xa003: 'PixelYDimension',\n 0xa004: 'RelatedSoundFile',\n 0xa20b: 'FlashEnergy',\n 0xa20c: 'SpatialFrequencyResponse',\n 0xa20e: 'FocalPlaneXResolution',\n 0xa20f: 'FocalPlaneYResolution',\n 0xa210: 'FocalPlaneResolutionUnit',\n 0xa214: 'SubjectLocation',\n 0xa215: 'ExposureIndex',\n 0xa217: 'SensingMethod',\n 0xa300: 'FileSource',\n 0xa301: 'SceneType',\n 0xa302: 'CFAPattern',\n 0xa401: 'CustomRendered',\n 0xa402: 'ExposureMode',\n 0xa403: 'WhiteBalance',\n 0xa404: 'DigitalZoomRatio',\n 0xa405: 'FocalLengthIn35mmFilm',\n 0xa406: 'SceneCaptureType',\n 0xa407: 'GainControl',\n 0xa408: 'Contrast',\n 0xa409: 'Saturation',\n 0xa40a: 'Sharpness',\n 0xa40b: 'DeviceSettingDescription',\n 0xa40c: 'SubjectDistanceRange',\n 0xa420: 'ImageUniqueID',\n 0xa430: 'CameraOwnerName',\n 0xa431: 'BodySerialNumber',\n 0xa432: 'LensSpecification',\n 0xa433: 'LensMake',\n 0xa434: 'LensModel',\n 0xa435: 'LensSerialNumber',\n 0xa500: 'Gamma',\n};\nconst tagsByName = {};\nfor (let i in tagsById) {\n tagsByName[tagsById[i]] = Number(i);\n}\nexport { tagsById, tagsByName };\n//# sourceMappingURL=exif.js.map","const tagsById = {\n 0x0000: 'GPSVersionID',\n 0x0001: 'GPSLatitudeRef',\n 0x0002: 'GPSLatitude',\n 0x0003: 'GPSLongitudeRef',\n 0x0004: 'GPSLongitude',\n 0x0005: 'GPSAltitudeRef',\n 0x0006: 'GPSAltitude',\n 0x0007: 'GPSTimeStamp',\n 0x0008: 'GPSSatellites',\n 0x0009: 'GPSStatus',\n 0x000a: 'GPSMeasureMode',\n 0x000b: 'GPSDOP',\n 0x000c: 'GPSSpeedRef',\n 0x000d: 'GPSSpeed',\n 0x000e: 'GPSTrackRef',\n 0x000f: 'GPSTrack',\n 0x0010: 'GPSImgDirectionRef',\n 0x0011: 'GPSImgDirection',\n 0x0012: 'GPSMapDatum',\n 0x0013: 'GPSDestLatitudeRef',\n 0x0014: 'GPSDestLatitude',\n 0x0015: 'GPSDestLongitudeRef',\n 0x0016: 'GPSDestLongitude',\n 0x0017: 'GPSDestBearingRef',\n 0x0018: 'GPSDestBearing',\n 0x0019: 'GPSDestDistanceRef',\n 0x001a: 'GPSDestDistance',\n 0x001b: 'GPSProcessingMethod',\n 0x001c: 'GPSAreaInformation',\n 0x001d: 'GPSDateStamp',\n 0x001e: 'GPSDifferential',\n 0x001f: 'GPSHPositioningError',\n};\nconst tagsByName = {};\nfor (let i in tagsById) {\n tagsByName[tagsById[i]] = Number(i);\n}\nexport { tagsById, tagsByName };\n//# sourceMappingURL=gps.js.map","const tagsById = {\n // Baseline tags\n 0x00fe: 'NewSubfileType',\n 0x00ff: 'SubfileType',\n 0x0100: 'ImageWidth',\n 0x0101: 'ImageLength',\n 0x0102: 'BitsPerSample',\n 0x0103: 'Compression',\n 0x0106: 'PhotometricInterpretation',\n 0x0107: 'Threshholding',\n 0x0108: 'CellWidth',\n 0x0109: 'CellLength',\n 0x010a: 'FillOrder',\n 0x010e: 'ImageDescription',\n 0x010f: 'Make',\n 0x0110: 'Model',\n 0x0111: 'StripOffsets',\n 0x0112: 'Orientation',\n 0x0115: 'SamplesPerPixel',\n 0x0116: 'RowsPerStrip',\n 0x0117: 'StripByteCounts',\n 0x0118: 'MinSampleValue',\n 0x0119: 'MaxSampleValue',\n 0x011a: 'XResolution',\n 0x011b: 'YResolution',\n 0x011c: 'PlanarConfiguration',\n 0x0120: 'FreeOffsets',\n 0x0121: 'FreeByteCounts',\n 0x0122: 'GrayResponseUnit',\n 0x0123: 'GrayResponseCurve',\n 0x0128: 'ResolutionUnit',\n 0x0131: 'Software',\n 0x0132: 'DateTime',\n 0x013b: 'Artist',\n 0x013c: 'HostComputer',\n 0x0140: 'ColorMap',\n 0x0152: 'ExtraSamples',\n 0x8298: 'Copyright',\n // Extension tags\n 0x010d: 'DocumentName',\n 0x011d: 'PageName',\n 0x011e: 'XPosition',\n 0x011f: 'YPosition',\n 0x0124: 'T4Options',\n 0x0125: 'T6Options',\n 0x0129: 'PageNumber',\n 0x012d: 'TransferFunction',\n 0x013d: 'Predictor',\n 0x013e: 'WhitePoint',\n 0x013f: 'PrimaryChromaticities',\n 0x0141: 'HalftoneHints',\n 0x0142: 'TileWidth',\n 0x0143: 'TileLength',\n 0x0144: 'TileOffsets',\n 0x0145: 'TileByteCounts',\n 0x0146: 'BadFaxLines',\n 0x0147: 'CleanFaxData',\n 0x0148: 'ConsecutiveBadFaxLines',\n 0x014a: 'SubIFDs',\n 0x014c: 'InkSet',\n 0x014d: 'InkNames',\n 0x014e: 'NumberOfInks',\n 0x0150: 'DotRange',\n 0x0151: 'TargetPrinter',\n 0x0153: 'SampleFormat',\n 0x0154: 'SMinSampleValue',\n 0x0155: 'SMaxSampleValue',\n 0x0156: 'TransferRange',\n 0x0157: 'ClipPath',\n 0x0158: 'XClipPathUnits',\n 0x0159: 'YClipPathUnits',\n 0x015a: 'Indexed',\n 0x015b: 'JPEGTables',\n 0x015f: 'OPIProxy',\n 0x0190: 'GlobalParametersIFD',\n 0x0191: 'ProfileType',\n 0x0192: 'FaxProfile',\n 0x0193: 'CodingMethods',\n 0x0194: 'VersionYear',\n 0x0195: 'ModeNumber',\n 0x01b1: 'Decode',\n 0x01b2: 'DefaultImageColor',\n 0x0200: 'JPEGProc',\n 0x0201: 'JPEGInterchangeFormat',\n 0x0202: 'JPEGInterchangeFormatLength',\n 0x0203: 'JPEGRestartInterval',\n 0x0205: 'JPEGLosslessPredictors',\n 0x0206: 'JPEGPointTransforms',\n 0x0207: 'JPEGQTables',\n 0x0208: 'JPEGDCTables',\n 0x0209: 'JPEGACTables',\n 0x0211: 'YCbCrCoefficients',\n 0x0212: 'YCbCrSubSampling',\n 0x0213: 'YCbCrPositioning',\n 0x0214: 'ReferenceBlackWhite',\n 0x022f: 'StripRowCounts',\n 0x02bc: 'XMP',\n 0x800d: 'ImageID',\n 0x87ac: 'ImageLayer',\n // Private tags\n 0x80a4: 'WangAnnotatio',\n 0x82a5: 'MDFileTag',\n 0x82a6: 'MDScalePixel',\n 0x82a7: 'MDColorTable',\n 0x82a8: 'MDLabName',\n 0x82a9: 'MDSampleInfo',\n 0x82aa: 'MDPrepDate',\n 0x82ab: 'MDPrepTime',\n 0x82ac: 'MDFileUnits',\n 0x830e: 'ModelPixelScaleTag',\n 0x83bb: 'IPTC',\n 0x847e: 'INGRPacketDataTag',\n 0x847f: 'INGRFlagRegisters',\n 0x8480: 'IrasBTransformationMatrix',\n 0x8482: 'ModelTiepointTag',\n 0x85d8: 'ModelTransformationTag',\n 0x8649: 'Photoshop',\n 0x8769: 'ExifIFD',\n 0x8773: 'ICCProfile',\n 0x87af: 'GeoKeyDirectoryTag',\n 0x87b0: 'GeoDoubleParamsTag',\n 0x87b1: 'GeoAsciiParamsTag',\n 0x8825: 'GPSIFD',\n 0x885c: 'HylaFAXFaxRecvParams',\n 0x885d: 'HylaFAXFaxSubAddress',\n 0x885e: 'HylaFAXFaxRecvTime',\n 0x935c: 'ImageSourceData',\n 0xa005: 'InteroperabilityIFD',\n 0xa480: 'GDAL_METADATA',\n 0xa481: 'GDAL_NODATA',\n 0xc427: 'OceScanjobDescription',\n 0xc428: 'OceApplicationSelector',\n 0xc429: 'OceIdentificationNumber',\n 0xc42a: 'OceImageLogicCharacteristics',\n 0xc612: 'DNGVersion',\n 0xc613: 'DNGBackwardVersion',\n 0xc614: 'UniqueCameraModel',\n 0xc615: 'LocalizedCameraModel',\n 0xc616: 'CFAPlaneColor',\n 0xc617: 'CFALayout',\n 0xc618: 'LinearizationTable',\n 0xc619: 'BlackLevelRepeatDim',\n 0xc61a: 'BlackLevel',\n 0xc61b: 'BlackLevelDeltaH',\n 0xc61c: 'BlackLevelDeltaV',\n 0xc61d: 'WhiteLevel',\n 0xc61e: 'DefaultScale',\n 0xc61f: 'DefaultCropOrigin',\n 0xc620: 'DefaultCropSize',\n 0xc621: 'ColorMatrix1',\n 0xc622: 'ColorMatrix2',\n 0xc623: 'CameraCalibration1',\n 0xc624: 'CameraCalibration2',\n 0xc625: 'ReductionMatrix1',\n 0xc626: 'ReductionMatrix2',\n 0xc627: 'AnalogBalance',\n 0xc628: 'AsShotNeutral',\n 0xc629: 'AsShotWhiteXY',\n 0xc62a: 'BaselineExposure',\n 0xc62b: 'BaselineNoise',\n 0xc62c: 'BaselineSharpness',\n 0xc62d: 'BayerGreenSplit',\n 0xc62e: 'LinearResponseLimit',\n 0xc62f: 'CameraSerialNumber',\n 0xc630: 'LensInfo',\n 0xc631: 'ChromaBlurRadius',\n 0xc632: 'AntiAliasStrength',\n 0xc634: 'DNGPrivateData',\n 0xc635: 'MakerNoteSafety',\n 0xc65a: 'CalibrationIlluminant1',\n 0xc65b: 'CalibrationIlluminant2',\n 0xc65c: 'BestQualityScale',\n 0xc660: 'AliasLayerMetadata',\n};\nconst tagsByName = {};\nfor (let i in tagsById) {\n tagsByName[tagsById[i]] = Number(i);\n}\nexport { tagsById, tagsByName };\n//# sourceMappingURL=standard.js.map","import * as exif from './tags/exif';\nimport * as gps from './tags/gps';\nimport * as standard from './tags/standard';\nconst tags = {\n standard,\n exif,\n gps,\n};\nexport default class IFD {\n kind;\n data;\n fields;\n exif;\n gps;\n _hasMap;\n _map;\n constructor(kind) {\n if (!kind) {\n throw new Error('missing kind');\n }\n this.data = new Uint8Array();\n this.fields = new Map();\n this.kind = kind;\n this._hasMap = false;\n this._map = {};\n }\n get(tag) {\n if (typeof tag === 'number') {\n return this.fields.get(tag);\n }\n else if (typeof tag === 'string') {\n return this.fields.get(tags[this.kind].tagsByName[tag]);\n }\n else {\n throw new Error('expected a number or string');\n }\n }\n get map() {\n if (!this._hasMap) {\n const taglist = tags[this.kind].tagsById;\n for (let key of this.fields.keys()) {\n if (taglist[key]) {\n this._map[taglist[key]] = this.fields.get(key);\n }\n }\n this._hasMap = true;\n }\n return this._map;\n }\n}\n//# sourceMappingURL=ifd.js.map","let types = new Map([\n [1, [1, readByte]],\n [2, [1, readASCII]],\n [3, [2, readShort]],\n [4, [4, readLong]],\n [5, [8, readRational]],\n [6, [1, readSByte]],\n [7, [1, readByte]],\n [8, [2, readSShort]],\n [9, [4, readSLong]],\n [10, [8, readSRational]],\n [11, [4, readFloat]],\n [12, [8, readDouble]], // DOUBLE\n]);\nexport function getByteLength(type, count) {\n const val = types.get(type);\n if (!val)\n throw new Error(`type not found: ${type}`);\n return val[0] * count;\n}\nexport function readData(decoder, type, count) {\n const val = types.get(type);\n if (!val)\n throw new Error(`type not found: ${type}`);\n return val[1](decoder, count);\n}\nfunction readByte(decoder, count) {\n if (count === 1)\n return decoder.readUint8();\n let array = new Uint8Array(count);\n for (let i = 0; i < count; i++) {\n array[i] = decoder.readUint8();\n }\n return array;\n}\nfunction readASCII(decoder, count) {\n let strings = [];\n let currentString = '';\n for (let i = 0; i < count; i++) {\n let char = String.fromCharCode(decoder.readUint8());\n if (char === '\\0') {\n strings.push(currentString);\n currentString = '';\n }\n else {\n currentString += char;\n }\n }\n if (strings.length === 1) {\n return strings[0];\n }\n else {\n return strings;\n }\n}\nfunction readShort(decoder, count) {\n if (count === 1)\n return decoder.readUint16();\n let array = new Uint16Array(count);\n for (let i = 0; i < count; i++) {\n array[i] = decoder.readUint16();\n }\n return array;\n}\nfunction readLong(decoder, count) {\n if (count === 1)\n return decoder.readUint32();\n let array = new Uint32Array(count);\n for (let i = 0; i < count; i++) {\n array[i] = decoder.readUint32();\n }\n return array;\n}\nfunction readRational(decoder, count) {\n if (count === 1) {\n return decoder.readUint32() / decoder.readUint32();\n }\n let rationals = new Array(count);\n for (let i = 0; i < count; i++) {\n rationals[i] = decoder.readUint32() / decoder.readUint32();\n }\n return rationals;\n}\nfunction readSByte(decoder, count) {\n if (count === 1)\n return decoder.readInt8();\n let array = new Int8Array(count);\n for (let i = 0; i < count; i++) {\n array[i] = decoder.readInt8();\n }\n return array;\n}\nfunction readSShort(decoder, count) {\n if (count === 1)\n return decoder.readInt16();\n let array = new Int16Array(count);\n for (let i = 0; i < count; i++) {\n array[i] = decoder.readInt16();\n }\n return array;\n}\nfunction readSLong(decoder, count) {\n if (count === 1)\n return decoder.readInt32();\n let array = new Int32Array(count);\n for (let i = 0; i < count; i++) {\n array[i] = decoder.readInt32();\n }\n return array;\n}\nfunction readSRational(decoder, count) {\n if (count === 1) {\n return decoder.readInt32() / decoder.readInt32();\n }\n let rationals = new Array(count);\n for (let i = 0; i < count; i++) {\n rationals[i] = decoder.readInt32() / decoder.readInt32();\n }\n return rationals;\n}\nfunction readFloat(decoder, count) {\n if (count === 1)\n return decoder.readFloat32();\n let array = new Float32Array(count);\n for (let i = 0; i < count; i++) {\n array[i] = decoder.readFloat32();\n }\n return array;\n}\nfunction readDouble(decoder, count) {\n if (count === 1)\n return decoder.readFloat64();\n let array = new Float64Array(count);\n for (let i = 0; i < count; i++) {\n array[i] = decoder.readFloat64();\n }\n return array;\n}\n//# sourceMappingURL=ifdValue.js.map","import { IOBuffer } from 'iobuffer';\nconst CLEAR_CODE = 256;\nconst EOI_CODE = 257;\n// 0-255 from the table + 256 for clear code + 257 for end of information code.\nconst TABLE_START = 258;\nconst MIN_BIT_LENGTH = 9;\nconst stringTable = [];\nfor (let i = 0; i < 256; i++) {\n stringTable.push([i]);\n}\n// Fill the table with dummy data.\n// Elements at indices > 257 will be replaced during decompression.\nconst dummyString = [0];\nfor (let i = 256; i < 4096; i++) {\n stringTable.push(dummyString);\n}\nclass LzwDecoder {\n stripArray;\n currentBit;\n tableLength;\n currentBitLength;\n outData;\n constructor(data) {\n this.stripArray = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);\n const table = new Map();\n for (let i = 0; i < 256; i++) {\n table.set(i, [i]);\n }\n this.currentBit = 0;\n this.tableLength = TABLE_START;\n this.currentBitLength = MIN_BIT_LENGTH;\n this.outData = new IOBuffer(data.byteLength);\n }\n decode() {\n let code = 0;\n let oldCode = 0;\n while ((code = this.getNextCode()) !== EOI_CODE) {\n if (code === CLEAR_CODE) {\n this.initializeTable();\n code = this.getNextCode();\n if (code === EOI_CODE) {\n break;\n }\n this.writeString(this.stringFromCode(code));\n oldCode = code;\n }\n else if (this.isInTable(code)) {\n this.writeString(this.stringFromCode(code));\n this.addStringToTable(this.stringFromCode(oldCode).concat(this.stringFromCode(code)[0]));\n oldCode = code;\n }\n else {\n const outString = this.stringFromCode(oldCode).concat(this.stringFromCode(oldCode)[0]);\n this.writeString(outString);\n this.addStringToTable(outString);\n oldCode = code;\n }\n }\n const outArray = this.outData.toArray();\n return new DataView(outArray.buffer, outArray.byteOffset, outArray.byteLength);\n }\n initializeTable() {\n this.tableLength = TABLE_START;\n this.currentBitLength = MIN_BIT_LENGTH;\n }\n writeString(string) {\n this.outData.writeBytes(string);\n }\n stringFromCode(code) {\n // At this point, `code` must be defined in the table.\n return stringTable[code];\n }\n isInTable(code) {\n return code < this.tableLength;\n }\n addStringToTable(string) {\n stringTable[this.tableLength++] = string;\n if (this.tableLength + 1 === 2 ** this.currentBitLength) {\n this.currentBitLength++;\n }\n }\n getNextCode() {\n const d = this.currentBit % 8;\n const a = this.currentBit >>> 3;\n const de = 8 - d;\n const ef = this.currentBit + this.currentBitLength - (a + 1) * 8;\n let fg = 8 * (a + 2) - (this.currentBit + this.currentBitLength);\n const dg = (a + 2) * 8 - this.currentBit;\n fg = Math.max(0, fg);\n let chunk1 = this.stripArray[a] & (2 ** (8 - d) - 1);\n chunk1 <<= this.currentBitLength - de;\n let chunks = chunk1;\n if (a + 1 < this.stripArray.length) {\n let chunk2 = this.stripArray[a + 1] >>> fg;\n chunk2 <<= Math.max(0, this.currentBitLength - dg);\n chunks += chunk2;\n }\n if (ef > 8 && a + 2 < this.stripArray.length) {\n const hi = (a + 3) * 8 - (this.currentBit + this.currentBitLength);\n const chunk3 = this.stripArray[a + 2] >>> hi;\n chunks += chunk3;\n }\n this.currentBit += this.currentBitLength;\n return chunks;\n }\n}\nexport function decompressLzw(stripData) {\n return new LzwDecoder(stripData).decode();\n}\n//# sourceMappingURL=lzw.js.map","import Ifd from './ifd';\n// eslint-disable-next-line prefer-named-capture-group\nconst dateTimeRegex = /^(\\d{4}):(\\d{2}):(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/;\nexport default class TiffIfd extends Ifd {\n constructor() {\n super('standard');\n }\n // Custom fields\n get size() {\n return this.width * this.height;\n }\n get width() {\n return this.imageWidth;\n }\n get height() {\n return this.imageLength;\n }\n get components() {\n return this.samplesPerPixel;\n }\n get date() {\n let date = new Date();\n let result = dateTimeRegex.exec(this.dateTime);\n if (result === null) {\n throw new Error(`invalid dateTime: ${this.dateTime}`);\n }\n date.setFullYear(Number(result[1]), Number(result[2]) - 1, Number(result[3]));\n date.setHours(Number(result[4]), Number(result[5]), Number(result[6]));\n return date;\n }\n // IFD fields\n get newSubfileType() {\n return this.get('NewSubfileType');\n }\n get imageWidth() {\n return this.get('ImageWidth');\n }\n get imageLength() {\n return this.get('ImageLength');\n }\n get bitsPerSample() {\n const data = this.get('BitsPerSample');\n if (data && typeof data !== 'number') {\n return data[0];\n }\n return data;\n }\n get alpha() {\n const extraSamples = this.extraSamples;\n if (!extraSamples)\n return false;\n return extraSamples[0] !== 0;\n }\n get associatedAlpha() {\n const extraSamples = this.extraSamples;\n if (!extraSamples)\n return false;\n return extraSamples[0] === 1;\n }\n get extraSamples() {\n return alwaysArray(this.get('ExtraSamples'));\n }\n get compression() {\n return this.get('Compression') || 1;\n }\n get type() {\n return this.get('PhotometricInterpretation');\n }\n get fillOrder() {\n return this.get('FillOrder') || 1;\n }\n get documentName() {\n return this.get('DocumentName');\n }\n get imageDescription() {\n return this.get('ImageDescription');\n }\n get stripOffsets() {\n return alwaysArray(this.get('StripOffsets'));\n }\n get orientation() {\n return this.get('Orientation');\n }\n get samplesPerPixel() {\n return this.get('SamplesPerPixel') || 1;\n }\n get rowsPerStrip() {\n return this.get('RowsPerStrip');\n }\n get stripByteCounts() {\n return alwaysArray(this.get('StripByteCounts'));\n }\n get minSampleValue() {\n return this.get('MinSampleValue') || 0;\n }\n get maxSampleValue() {\n return this.get('MaxSampleValue') || Math.pow(2, this.bitsPerSample) - 1;\n }\n get xResolution() {\n return this.get('XResolution');\n }\n get yResolution() {\n return this.get('YResolution');\n }\n get planarConfiguration() {\n return this.get('PlanarConfiguration') || 1;\n }\n get resolutionUnit() {\n return this.get('ResolutionUnit') || 2;\n }\n get dateTime() {\n return this.get('DateTime');\n }\n get predictor() {\n return this.get('Predictor') || 1;\n }\n get sampleFormat() {\n return this.get('SampleFormat') || 1;\n }\n get sMinSampleValue() {\n return this.get('SMinSampleValue') || this.minSampleValue;\n }\n get sMaxSampleValue() {\n return this.get('SMaxSampleValue') || this.maxSampleValue;\n }\n get palette() {\n const totalColors = 2 ** this.bitsPerSample;\n const colorMap = this.get('ColorMap');\n if (!colorMap)\n return undefined;\n if (colorMap.length !== 3 * totalColors) {\n throw new Error(`ColorMap size must be ${totalColors}`);\n }\n const palette = [];\n for (let i = 0; i < totalColors; i++) {\n palette.push([\n colorMap[i],\n colorMap[i + totalColors],\n colorMap[i + 2 * totalColors],\n ]);\n }\n return palette;\n }\n}\nfunction alwaysArray(value) {\n if (typeof value === 'number')\n return [value];\n return value;\n}\n//# sourceMappingURL=tiffIfd.js.map","import { inflate } from 'pako';\nexport function decompressZlib(stripData) {\n const stripUint8 = new Uint8Array(stripData.buffer, stripData.byteOffset, stripData.byteLength);\n const inflated = inflate(stripUint8);\n return new DataView(inflated.buffer, inflated.byteOffset, inflated.byteLength);\n}\n//# sourceMappingURL=zlib.js.map","import { IOBuffer } from 'iobuffer';\nimport { applyHorizontalDifferencing8Bit, applyHorizontalDifferencing16Bit, } from './horizontalDifferencing';\nimport IFD from './ifd';\nimport { getByteLength, readData } from './ifdValue';\nimport { decompressLzw } from './lzw';\nimport TiffIfd from './tiffIfd';\nimport { decompressZlib } from './zlib';\nconst defaultOptions = {\n ignoreImageData: false,\n onlyFirst: false,\n};\nexport default class TIFFDecoder extends IOBuffer {\n _nextIFD;\n constructor(data) {\n super(data);\n this._nextIFD = 0;\n }\n get isMultiPage() {\n let c = 0;\n this.decodeHeader();\n while (this._nextIFD) {\n c++;\n this.decodeIFD({ ignoreImageData: true }, true);\n if (c === 2) {\n return true;\n }\n }\n if (c === 1) {\n return false;\n }\n throw unsupported('ifdCount', c);\n }\n get pageCount() {\n let c = 0;\n this.decodeHeader();\n while (this._nextIFD) {\n c++;\n this.decodeIFD({ ignoreImageData: true }, true);\n }\n if (c > 0) {\n return c;\n }\n throw unsupported('ifdCount', c);\n }\n decode(options = {}) {\n options = Object.assign({}, defaultOptions, options);\n const result = [];\n this.decodeHeader();\n while (this._nextIFD) {\n result.push(this.decodeIFD(options, true));\n if (options.onlyFirst) {\n return [result[0]];\n }\n }\n return result;\n }\n decodeHeader() {\n // Byte offset\n const value = this.readUint16();\n if (value === 0x4949) {\n this.setLittleEndian();\n }\n else if (value === 0x4d4d) {\n this.setBigEndian();\n }\n else {\n throw new Error(`invalid byte order: 0x${value.toString(16)}`);\n }\n // Magic number\n if (this.readUint16() !== 42) {\n throw new Error('not a TIFF file');\n }\n // Offset of the first IFD\n this._nextIFD = this.readUint32();\n }\n decodeIFD(options, tiff) {\n this.seek(this._nextIFD);\n let ifd;\n if (tiff) {\n ifd = new TiffIfd();\n }\n else {\n if (!options.kind) {\n throw new Error(`kind is missing`);\n }\n ifd = new IFD(options.kind);\n }\n const numEntries = this.readUint16();\n for (let i = 0; i < numEntries; i++) {\n this.decodeIFDEntry(ifd);\n }\n if (!options.ignoreImageData) {\n if (!(ifd instanceof TiffIfd)) {\n throw new Error('must be a tiff ifd');\n }\n this.decodeImageData(ifd);\n }\n this._nextIFD = this.readUint32();\n return ifd;\n }\n decodeIFDEntry(ifd) {\n const offset = this.offset;\n const tag = this.readUint16();\n const type = this.readUint16();\n const numValues = this.readUint32();\n if (type < 1 || type > 12) {\n this.skip(4); // unknown type, skip this value\n return;\n }\n const valueByteLength = getByteLength(type, numValues);\n if (valueByteLength > 4) {\n this.seek(this.readUint32());\n }\n const value = readData(this, type, numValues);\n ifd.fields.set(tag, value);\n // Read sub-IFDs\n if (tag === 0x8769 || tag === 0x8825) {\n let currentOffset = this.offset;\n let kind = 'exif';\n if (tag === 0x8769) {\n kind = 'exif';\n }\n else if (tag === 0x8825) {\n kind = 'gps';\n }\n this._nextIFD = value;\n ifd[kind] = this.decodeIFD({\n kind,\n ignoreImageData: true,\n }, false);\n this.offset = currentOffset;\n }\n // go to the next entry\n this.seek(offset);\n this.skip(12);\n }\n decodeImageData(ifd) {\n const orientation = ifd.orientation;\n if (orientation && orientation !== 1) {\n throw unsupported('orientation', orientation);\n }\n switch (ifd.type) {\n case 0: // WhiteIsZero\n case 1: // BlackIsZero\n case 2: // RGB\n case 3: // Palette color\n this.readStripData(ifd);\n break;\n default:\n throw unsupported('image type', ifd.type);\n }\n this.applyPredictor(ifd);\n this.convertAlpha(ifd);\n if (ifd.type === 0) {\n // WhiteIsZero: we invert the values\n const bitDepth = ifd.bitsPerSample;\n const maxValue = Math.pow(2, bitDepth) - 1;\n for (let i = 0; i < ifd.data.length; i++) {\n ifd.data[i] = maxValue - ifd.data[i];\n }\n }\n }\n readStripData(ifd) {\n const width = ifd.width;\n const height = ifd.height;\n const bitDepth = ifd.bitsPerSample;\n const sampleFormat = ifd.sampleFormat;\n const size = width * height * ifd.samplesPerPixel;\n const data = getDataArray(size, bitDepth, sampleFormat);\n const rowsPerStrip = ifd.rowsPerStrip;\n const maxPixels = rowsPerStrip * width * ifd.samplesPerPixel;\n const stripOffsets = ifd.stripOffsets;\n const stripByteCounts = ifd.stripByteCounts;\n let remainingPixels = size;\n let pixel = 0;\n for (let i = 0; i < stripOffsets.length; i++) {\n let stripData = new DataView(this.buffer, stripOffsets[i], stripByteCounts[i]);\n // Last strip can be smaller\n let length = remainingPixels > maxPixels ? maxPixels : remainingPixels;\n remainingPixels -= length;\n let dataToFill = stripData;\n switch (ifd.compression) {\n case 1: {\n // No compression, nothing to do\n break;\n }\n case 5: {\n // LZW compression\n dataToFill = decompressLzw(stripData);\n break;\n }\n case 8: {\n // Zlib compression\n dataToFill = decompressZlib(stripData);\n break;\n }\n case 2: // CCITT Group 3 1-Dimensional Modified Huffman run length encoding\n throw unsupported('Compression', 'CCITT Group 3');\n case 32773: // PackBits compression\n throw unsupported('Compression', 'PackBits');\n default:\n throw unsupported('Compression', ifd.compression);\n }\n pixel = this.fillUncompressed(bitDepth, sampleFormat, data, dataToFill, pixel, length);\n }\n ifd.data = data;\n }\n fillUncompressed(bitDepth, sampleFormat, data, stripData, pixel, length) {\n if (bitDepth === 8) {\n return fill8bit(data, stripData, pixel, length);\n }\n else if (bitDepth === 16) {\n return fill16bit(data, stripData, pixel, length, this.isLittleEndian());\n }\n else if (bitDepth === 32 && sampleFormat === 3) {\n return fillFloat32(data, stripData, pixel, length, this.isLittleEndian());\n }\n else {\n throw unsupported('bitDepth', bitDepth);\n }\n }\n applyPredictor(ifd) {\n const bitDepth = ifd.bitsPerSample;\n switch (ifd.predictor) {\n case 1: {\n // No prediction scheme, nothing to do\n break;\n }\n case 2: {\n if (bitDepth === 8) {\n applyHorizontalDifferencing8Bit(ifd.data, ifd.width, ifd.components);\n }\n else if (bitDepth === 16) {\n applyHorizontalDifferencing16Bit(ifd.data, ifd.width, ifd.components);\n }\n else {\n throw new Error(`Horizontal differencing is only supported for images with a bit depth of ${bitDepth}`);\n }\n break;\n }\n default:\n throw new Error(`invalid predictor: ${ifd.predictor}`);\n }\n }\n convertAlpha(ifd) {\n if (ifd.alpha && ifd.associatedAlpha) {\n const { data, components, maxSampleValue } = ifd;\n for (let i = 0; i < data.length; i += components) {\n const alphaValue = data[i + components - 1];\n for (let j = 0; j < components - 1; j++) {\n data[i + j] = Math.round((data[i + j] * maxSampleValue) / alphaValue);\n }\n }\n }\n }\n}\nfunction getDataArray(size, bitDepth, sampleFormat) {\n if (bitDepth === 8) {\n return new Uint8Array(size);\n }\n else if (bitDepth === 16) {\n return new Uint16Array(size);\n }\n else if (bitDepth === 32 && sampleFormat === 3) {\n return new Float32Array(size);\n }\n else {\n throw unsupported('bit depth / sample format', `${bitDepth} / ${sampleFormat}`);\n }\n}\nfunction fill8bit(dataTo, dataFrom, index, length) {\n for (let i = 0; i < length; i++) {\n dataTo[index++] = dataFrom.getUint8(i);\n }\n return index;\n}\nfunction fill16bit(dataTo, dataFrom, index, length, littleEndian) {\n for (let i = 0; i < length * 2; i += 2) {\n dataTo[index++] = dataFrom.getUint16(i, littleEndian);\n }\n return index;\n}\nfunction fillFloat32(dataTo, dataFrom, index, length, littleEndian) {\n for (let i = 0; i < length * 4; i += 4) {\n dataTo[index++] = dataFrom.getFloat32(i, littleEndian);\n }\n return index;\n}\nfunction unsupported(type, value) {\n return new Error(`Unsupported ${type}: ${value}`);\n}\n//# sourceMappingURL=tiffDecoder.js.map","import TIFFDecoder from './tiffDecoder';\nfunction decodeTIFF(data, options) {\n const decoder = new TIFFDecoder(data);\n return decoder.decode(options);\n}\nfunction isMultiPage(data) {\n const decoder = new TIFFDecoder(data);\n return decoder.isMultiPage;\n}\nfunction pageCount(data) {\n const decoder = new TIFFDecoder(data);\n return decoder.pageCount;\n}\nexport { decodeTIFF as decode, isMultiPage, pageCount };\n//# sourceMappingURL=index.js.map","import Stack from '../Stack';\n\n// TODO this code seems buggy if it is not 0,0\n/**\n * We will try to move a set of images in order to get only the best common part of them.\n * In a stack, we compare 2 consecutive images or directly to a parent.\n * Ignoring border may be dangerous ! If there is a shape on the side of the image there will be a\n * continuous shift if you ignore border. By default it is better to leave it to 0,0\n * Now if the background is not black there will also be no way to shift ...\n * It may therefore be much better to make a background correction before trying to match and crop.\n * @memberof Stack\n * @instance\n * @param {object} [options]\n * @param {string} [options.algorithm='matchToPrevious'] - matchToPrevious or matchToFirst\n * @param {number[]} [options.ignoreBorder=[0, 0]]\n * @return {Stack}\n */\nexport default function matchAndCrop(options = {}) {\n let { algorithm = 'matchToPrevious', ignoreBorder = [0, 0] } = options;\n\n this.checkProcessable('matchAndCrop', {\n bitDepth: [8, 16],\n });\n\n let matchToPrevious = algorithm === 'matchToPrevious';\n\n let parent = this[0];\n let results = [];\n results[0] = {\n position: [0, 0],\n image: this[0],\n };\n\n let relativePosition = [0, 0];\n\n // we calculate the best relative position to the parent image\n for (let i = 1; i < this.length; i++) {\n let position = parent.getBestMatch(this[i], { border: ignoreBorder });\n\n results[i] = {\n position: [\n position[0] + relativePosition[0],\n position[1] + relativePosition[1],\n ],\n image: this[i],\n };\n if (matchToPrevious) {\n relativePosition[0] += position[0];\n relativePosition[1] += position[1];\n parent = this[i];\n }\n }\n // now we can calculate the cropping that we need to do\n\n let leftShift = 0;\n let rightShift = 0;\n let topShift = 0;\n let bottomShift = 0;\n\n for (let i = 0; i < results.length; i++) {\n let result = results[i];\n if (result.position[0] > leftShift) {\n leftShift = result.position[0];\n }\n if (result.position[0] < rightShift) {\n rightShift = result.position[0];\n }\n if (result.position[1] > topShift) {\n topShift = result.position[1];\n }\n if (result.position[1] < bottomShift) {\n bottomShift = result.position[1];\n }\n }\n rightShift = 0 - rightShift;\n bottomShift = 0 - bottomShift;\n\n for (let i = 0; i < results.length; i++) {\n let result = results[i];\n\n result.crop = result.image.crop({\n x: leftShift - result.position[0],\n y: topShift - result.position[1],\n width: parent.width - rightShift - leftShift,\n height: parent.height - bottomShift - topShift,\n });\n }\n\n // finally we crop and create a new array of images\n let newImages = [];\n for (let i = 0; i < results.length; i++) {\n newImages[i] = results[i].crop;\n }\n\n return new Stack(newImages);\n}\n","/**\n * @memberof Stack\n * @instance\n * @return {number[]}\n */\nexport default function min() {\n this.checkProcessable('min', {\n bitDepth: [8, 16],\n });\n\n let min = this[0].min;\n for (let i = 1; i < this.length; i++) {\n for (let j = 0; j < min.length; j++) {\n min[j] = Math.min(min[j], this[i].min[j]);\n }\n }\n return min;\n}\n","/**\n * @memberof Stack\n * @instance\n * @return {number[]}\n */\nexport default function max() {\n this.checkProcessable('min', {\n bitDepth: [8, 16],\n });\n\n let max = this[0].max;\n for (let i = 1; i < this.length; i++) {\n for (let j = 0; j < max.length; j++) {\n max[j] = Math.max(max[j], this[i].max[j]);\n }\n }\n return max;\n}\n","/**\n * Returns the median of an histogram\n * @param {number[]} histogram\n * @return {number}\n * @private\n */\nexport function median(histogram) {\n let total = histogram.reduce((sum, x) => sum + x);\n\n if (total === 0) {\n throw new Error('unreachable');\n }\n\n let position = 0;\n let currentTotal = 0;\n let middle = total / 2;\n let previous;\n\n while (true) {\n if (histogram[position] > 0) {\n if (previous !== undefined) {\n return (previous + position) / 2;\n }\n currentTotal += histogram[position];\n if (currentTotal > middle) {\n return position;\n } else if (currentTotal === middle) {\n previous = position;\n }\n }\n position++;\n }\n}\n\n/**\n * Retuns the mean of an histogram\n * @param {number[]} histogram\n * @return {number}\n * @private\n */\nexport function mean(histogram) {\n let total = 0;\n let sum = 0;\n\n for (let i = 0; i < histogram.length; i++) {\n total += histogram[i];\n sum += histogram[i] * i;\n }\n\n if (total === 0) {\n return 0;\n }\n\n return sum / total;\n}\n","import { median as medianFromHistogram } from '../../util/histogram';\n\n/**\n * @memberof Stack\n * @instance\n * @return {number[]}\n */\nexport default function median() {\n this.checkProcessable('median', {\n bitDepth: [8, 16],\n });\n\n let histograms = this.getHistograms({ maxSlots: this[0].maxValue + 1 });\n let result = new Array(histograms.length);\n for (let c = 0; c < histograms.length; c++) {\n let histogram = histograms[c];\n result[c] = medianFromHistogram(histogram);\n }\n return result;\n}\n","/**\n * @memberof Stack\n * @instance\n * @param {object} [options]\n * @return {number[]}\n */\nexport default function histogram(options) {\n this.checkProcessable('min', {\n bitDepth: [8, 16],\n });\n\n let histogram = this[0].getHistogram(options);\n for (let i = 1; i < this.length; i++) {\n let secondHistogram = this[i].getHistogram(options);\n for (let j = 0; j < histogram.length; j++) {\n histogram[j] += secondHistogram[j];\n }\n }\n return histogram;\n}\n","/**\n * @memberof Stack\n * @instance\n * @param {object} [options]\n * @return {Array>}\n */\nexport default function histograms(options) {\n this.checkProcessable('min', {\n bitDepth: [8, 16],\n });\n\n let histograms = this[0].getHistograms(options);\n let histogramLength = histograms[0].length;\n for (let i = 1; i < this.length; i++) {\n let secondHistograms = this[i].getHistograms(options);\n for (let c = 0; c < histograms.length; c++) {\n for (let j = 0; j < histogramLength; j++) {\n histograms[c][j] += secondHistograms[c][j];\n }\n }\n }\n return histograms;\n}\n","import Image from '../../image/Image';\n\n/**\n * @memberof Stack\n * @instance\n * @return {Image}\n */\nexport default function averageImage() {\n this.checkProcessable('averageImage', {\n bitDepth: [8, 16],\n });\n\n let data = new Uint32Array(this[0].data.length);\n for (let i = 0; i < this.length; i++) {\n let current = this[i];\n for (let j = 0; j < this[0].data.length; j++) {\n data[j] += current.data[j];\n }\n }\n\n let image = Image.createFrom(this[0]);\n let newData = image.data;\n\n for (let i = 0; i < this[0].data.length; i++) {\n newData[i] = data[i] / this.length;\n }\n\n return image;\n}\n","import Image from '../../image/Image';\n\n/**\n * @memberof Stack\n * @instance\n * @return {Image}\n */\nexport default function maxImage() {\n this.checkProcessable('max', {\n bitDepth: [8, 16],\n });\n\n let image = Image.createFrom(this[0]);\n image.data.fill(0);\n for (const current of this) {\n for (let j = 0; j < image.data.length; j++) {\n image.data[j] = Math.max(current.data[j], image.data[j]);\n }\n }\n\n return image;\n}\n","import Image from '../../image/Image';\n\n/**\n * @memberof Stack\n * @instance\n * @return {Image}\n */\nexport default function minImage() {\n this.checkProcessable('max', {\n bitDepth: [8, 16],\n });\n\n let image = Image.createFrom(this[0]);\n image.data.fill(image.maxValue);\n for (const current of this) {\n for (let j = 0; j < image.data.length; j++) {\n image.data[j] = Math.min(current.data[j], image.data[j]);\n }\n }\n\n return image;\n}\n","/* eslint-disable import/order */\nimport matchAndCrop from './transform/matchAndCrop';\n\nimport min from './compute/min';\nimport max from './compute/max';\nimport median from './compute/median';\nimport histogram from './compute/histogram';\nimport histograms from './compute/histograms';\n\nimport averageImage from './utility/averageImage';\nimport maxImage from './utility/maxImage';\nimport minImage from './utility/minImage';\n\nexport default function extend(Stack) {\n // let inPlace = {inPlace: true};\n Stack.extendMethod('matchAndCrop', matchAndCrop);\n\n Stack.extendMethod('getMin', min);\n Stack.extendMethod('getMax', max);\n Stack.extendMethod('getMedian', median);\n Stack.extendMethod('getHistogram', histogram);\n Stack.extendMethod('getHistograms', histograms);\n\n Stack.extendMethod('getAverage', averageImage); // to be removed but will be a breaking change\n\n Stack.extendMethod('getAverageImage', averageImage);\n Stack.extendMethod('getMaxImage', maxImage);\n Stack.extendMethod('getMinImage', minImage);\n}\n","import hasOwn from 'has-own';\n\nimport Image from '../image/Image';\n\nimport extend from './extend';\n\nlet computedPropertyDescriptor = {\n configurable: true,\n enumerable: false,\n get: undefined,\n};\n\n/**\n * Class representing stack of images\n * @class Stack\n */\nexport default class Stack extends Array {\n constructor(images) {\n if (Array.isArray(images)) {\n super(images.length);\n for (let i = 0; i < images.length; i++) {\n this[i] = images[i];\n }\n } else if (typeof images === 'number') {\n super(images);\n } else {\n super();\n }\n this.computed = null;\n }\n\n static load(urls) {\n return Promise.all(urls.map(Image.load)).then(\n (images) => new Stack(images),\n );\n }\n\n static extendMethod(name, method, options = {}) {\n let { inPlace = false, returnThis = true, partialArgs = [] } = options;\n\n if (inPlace) {\n Stack.prototype[name] = function (...args) {\n // remove computed properties\n this.computed = null;\n let result = method.apply(this, [...partialArgs, ...args]);\n if (returnThis) {\n return this;\n }\n return result;\n };\n } else {\n Stack.prototype[name] = function (...args) {\n return method.apply(this, [...partialArgs, ...args]);\n };\n }\n return Stack;\n }\n\n static extendProperty(name, method, options = {}) {\n let { partialArgs = [] } = options;\n\n computedPropertyDescriptor.get = function () {\n if (this.computed === null) {\n this.computed = {};\n } else if (hasOwn(name, this.computed)) {\n return this.computed[name];\n }\n let result = method.apply(this, partialArgs);\n this.computed[name] = result;\n return result;\n };\n Object.defineProperty(Stack.prototype, name, computedPropertyDescriptor);\n return Stack;\n }\n\n /**\n * Check if a process can be applied on the stack\n * @param {string} processName\n * @param {object} [options]\n * @private\n */\n checkProcessable(processName, options = {}) {\n if (typeof processName !== 'string') {\n throw new TypeError(\n 'checkProcessable requires as first parameter the processName (a string)',\n );\n }\n if (this.size === 0) {\n throw new TypeError(\n `The process: ${processName} can not be applied on an empty stack`,\n );\n }\n this[0].checkProcessable(processName, options);\n for (let i = 1; i < this.length; i++) {\n if (\n (options.sameSize === undefined || options.sameSize) &&\n this[0].width !== this[i].width\n ) {\n throw new TypeError(\n `The process: ${processName} can not be applied if width is not identical in all images`,\n );\n }\n if (\n (options.sameSize === undefined || options.sameSize) &&\n this[0].height !== this[i].height\n ) {\n throw new TypeError(\n `The process: ${processName} can not be applied if height is not identical in all images`,\n );\n }\n if (\n (options.sameAlpha === undefined || options.sameAlpha) &&\n this[0].alpha !== this[i].alpha\n ) {\n throw new TypeError(\n `The process: ${processName} can not be applied if alpha is not identical in all images`,\n );\n }\n if (\n (options.sameBitDepth === undefined || options.sameBitDepth) &&\n this[0].bitDepth !== this[i].bitDepth\n ) {\n throw new TypeError(\n `The process: ${processName} can not be applied if bitDepth is not identical in all images`,\n );\n }\n if (\n (options.sameColorModel === undefined || options.sameColorModel) &&\n this[0].colorModel !== this[i].colorModel\n ) {\n throw new TypeError(\n `The process: ${processName} can not be applied if colorModel is not identical in all images`,\n );\n }\n if (\n (options.sameNumberChannels === undefined ||\n options.sameNumberChannels) &&\n this[0].channels !== this[i].channels\n ) {\n throw new TypeError(\n `The process: ${processName} can not be applied if channels is not identical in all images`,\n );\n }\n }\n }\n}\n\nif (!Array[Symbol.species]) {\n // support old engines\n Stack.prototype.map = function (cb, thisArg) {\n if (typeof cb !== 'function') {\n throw new TypeError(`${cb} is not a function`);\n }\n let newStack = new Stack(this.length);\n for (let i = 0; i < this.length; i++) {\n newStack[i] = cb.call(thisArg, this[i], i, this);\n }\n return newStack;\n };\n}\n\nextend(Stack);\n","import { decode as decodeJpegExif } from 'fast-jpeg';\nimport { decode as decodePng } from 'fast-png';\nimport imageType from 'image-type';\nimport { decode as decodeJpeg } from 'jpeg-js';\nimport { decode as decodeTiff } from 'tiff';\n\nimport Stack from '../../stack/Stack';\nimport { decode as base64Decode, toBase64URL } from '../../util/base64';\nimport Image from '../Image';\nimport { GREY, RGB } from '../model/model';\n\nimport { fetchBinary, DOMImage, createCanvas } from './environment';\n\nconst isDataURL = /^data:[a-z]+\\/(?:[a-z]+);base64,/;\n\n/**\n * Load an image\n * @memberof Image\n * @static\n * @param {string|ArrayBuffer|Buffer|Uint8Array} image - URL of the image (browser, can be a dataURL) or path (Node.js)\n * or buffer containing the binary data\n * @param {object} [options] - In the browser, the options object is passed to the underlying `fetch` call.\n * @return {Promise}\n * @example\n * const image = await Image.load('https://example.com/image.png');\n */\nexport default function load(image, options) {\n if (typeof image === 'string') {\n return loadURL(image, options);\n } else if (image instanceof ArrayBuffer) {\n return Promise.resolve(loadBinary(new Uint8Array(image)));\n } else if (image.buffer) {\n return Promise.resolve(loadBinary(image));\n } else {\n throw new Error('argument to \"load\" must be a string or buffer.');\n }\n}\n\nfunction loadBinary(image, base64Url) {\n const type = imageType(image);\n if (type) {\n switch (type.mime) {\n case 'image/png':\n return loadPNG(image);\n case 'image/jpeg':\n return loadJPEG(image);\n case 'image/tiff':\n return loadTIFF(image);\n default:\n return loadGeneric(getBase64(type.mime));\n }\n }\n return loadGeneric(getBase64('application/octet-stream'));\n function getBase64(type) {\n if (base64Url) {\n return base64Url;\n } else {\n return toBase64URL(image, type);\n }\n }\n}\n\nfunction loadURL(url, options) {\n const dataURL = url.slice(0, 64).match(isDataURL);\n let binaryDataP;\n if (dataURL !== null) {\n binaryDataP = Promise.resolve(base64Decode(url.slice(dataURL[0].length)));\n } else {\n binaryDataP = fetchBinary(url, options);\n }\n return binaryDataP.then((binaryData) => {\n const uint8 = new Uint8Array(binaryData);\n return loadBinary(uint8, dataURL ? url : undefined);\n });\n}\n\nfunction loadPNG(data) {\n const png = decodePng(data);\n let channels = png.channels;\n let components;\n let alpha = 0;\n if (channels === 2 || channels === 4) {\n components = channels - 1;\n alpha = 1;\n } else {\n components = channels;\n }\n if (png.palette) {\n return loadPNGFromPalette(png);\n }\n\n return new Image(png.width, png.height, png.data, {\n components,\n alpha,\n bitDepth: png.depth,\n });\n}\n\nfunction loadPNGFromPalette(png) {\n const pixels = png.width * png.height;\n const channels = png.palette[0].length;\n const data = new Uint8Array(pixels * channels);\n const pixelsPerByte = 8 / png.depth;\n const factor = png.depth < 8 ? pixelsPerByte : 1;\n const mask = parseInt('1'.repeat(png.depth), 2);\n const hasAlpha = channels === 4;\n let dataIndex = 0;\n\n for (let i = 0; i < pixels; i++) {\n const index = Math.floor(i / factor);\n let value = png.data[index];\n if (png.depth < 8) {\n value =\n (value >>> (png.depth * (pixelsPerByte - 1 - (i % pixelsPerByte)))) &\n mask;\n }\n const paletteValue = png.palette[value];\n data[dataIndex++] = paletteValue[0];\n data[dataIndex++] = paletteValue[1];\n data[dataIndex++] = paletteValue[2];\n if (hasAlpha) {\n data[dataIndex++] = paletteValue[3];\n }\n }\n\n return new Image(png.width, png.height, data, {\n components: 3,\n alpha: hasAlpha,\n bitDepth: 8,\n });\n}\n\nfunction loadJPEG(data) {\n const decodedExif = decodeJpegExif(data);\n let meta;\n if (decodedExif.exif) {\n meta = getMetadata(decodedExif.exif);\n }\n const jpeg = decodeJpeg(data, { useTArray: true, maxMemoryUsageInMB: 1024 });\n let image = new Image(jpeg.width, jpeg.height, jpeg.data, { meta });\n if (meta && meta.tiff.tags.Orientation) {\n const orientation = meta.tiff.tags.Orientation;\n if (orientation > 2) {\n image = image.rotate(\n {\n 3: 180,\n 4: 180,\n 5: 90,\n 6: 90,\n 7: 270,\n 8: 270,\n }[orientation],\n );\n }\n if ([2, 4, 5, 7].includes(orientation)) {\n image = image.flipX();\n }\n }\n return image;\n}\n\nfunction loadTIFF(data) {\n let result = decodeTiff(data);\n if (result.length === 1) {\n return getImageFromIFD(result[0]);\n } else {\n return new Stack(result.map(getImageFromIFD));\n }\n}\n\nfunction getMetadata(image) {\n const metadata = {\n tiff: {\n fields: image.fields,\n tags: image.map,\n },\n };\n if (image.exif) {\n metadata.exif = image.exif;\n }\n if (image.gps) {\n metadata.gps = image.gps;\n }\n return metadata;\n}\n\nfunction getImageFromIFD(image) {\n if (image.type === 3) {\n // Palette\n const data = new Uint16Array(3 * image.width * image.height);\n const palette = image.palette;\n let ptr = 0;\n for (let i = 0; i < image.data.length; i++) {\n const index = image.data[i];\n const color = palette[index];\n data[ptr++] = color[0];\n data[ptr++] = color[1];\n data[ptr++] = color[2];\n }\n return new Image(image.width, image.height, data, {\n components: 3,\n alpha: image.alpha,\n colorModel: RGB,\n bitDepth: 16,\n meta: getMetadata(image),\n });\n } else {\n return new Image(image.width, image.height, image.data, {\n components: image.type === 2 ? 3 : 1,\n alpha: image.alpha,\n colorModel: image.type === 2 ? RGB : GREY,\n bitDepth: image.bitsPerSample.length\n ? image.bitsPerSample[0]\n : image.bitsPerSample,\n meta: getMetadata(image),\n });\n }\n}\n\nfunction loadGeneric(url, options) {\n options = options || {};\n return new Promise(function (resolve, reject) {\n let image = new DOMImage();\n image.onload = function () {\n let w = image.width;\n let h = image.height;\n let canvas = createCanvas(w, h);\n let ctx = canvas.getContext('2d');\n ctx.drawImage(image, 0, 0, w, h);\n let data = ctx.getImageData(0, 0, w, h).data;\n resolve(new Image(w, h, data, options));\n };\n image.onerror = function () {\n reject(new Error(`Could not load ${url}`));\n };\n image.src = url;\n });\n}\n","const valueMethods = {\n /**\n * Get the value of specific pixel channel\n * @memberof Image\n * @instance\n * @param {number} x - x coordinate (0 = left)\n * @param {number} y - y coordinate (0 = top)\n * @param {number} channel\n * @return {number} - the value of this pixel channel\n */\n getValueXY(x, y, channel) {\n return this.data[(y * this.width + x) * this.channels + channel];\n },\n\n /**\n * Set the value of specific pixel channel\n * @memberof Image\n * @instance\n * @param {number} x - x coordinate (0 = left)\n * @param {number} y - y coordinate (0 = top)\n * @param {number} channel\n * @param {number} value - the new value of this pixel channel\n * @return {this}\n */\n setValueXY(x, y, channel, value) {\n this.data[(y * this.width + x) * this.channels + channel] = value;\n this.computed = null;\n return this;\n },\n\n /**\n * Get the value of specific pixel channel\n * @memberof Image\n * @instance\n * @param {number} index - 1D index of the pixel\n * @param {number} channel\n * @return {number} - the value of this pixel channel\n */\n getValue(index, channel) {\n return this.data[index * this.channels + channel];\n },\n\n /**\n * Set the value of specific pixel channel\n * @memberof Image\n * @instance\n * @param {number} index - 1D index of the pixel\n * @param {number} channel\n * @param {number} value - the new value of this pixel channel\n * @return {this}\n */\n setValue(index, channel, value) {\n this.data[index * this.channels + channel] = value;\n this.computed = null;\n return this;\n },\n\n /**\n * Get the value of an entire pixel\n * @memberof Image\n * @instance\n * @param {number} x - x coordinate (0 = left)\n * @param {number} y - y coordinate (0 = top)\n * @return {number[]} the value of this pixel\n */\n getPixelXY(x, y) {\n return this.getPixel(y * this.width + x);\n },\n\n /**\n * Set the value of an entire pixel\n * @memberof Image\n * @instance\n * @param {number} x - x coordinate (0 = left)\n * @param {number} y - y coordinate (0 = top)\n * @param {number[]} value - the new value of this pixel\n * @return {this}\n */\n setPixelXY(x, y, value) {\n return this.setPixel(y * this.width + x, value);\n },\n\n /**\n * Get the value of an entire pixel\n * @memberof Image\n * @instance\n * @param {number} index - 1D index of the pixel\n * @return {number[]} the value of this pixel\n */\n getPixel(index) {\n const value = new Array(this.channels);\n const target = index * this.channels;\n for (let i = 0; i < this.channels; i++) {\n value[i] = this.data[target + i];\n }\n return value;\n },\n\n /**\n * Set the value of an entire pixel\n * @memberof Image\n * @instance\n * @param {number} index - 1D index of the pixel\n * @param {number[]} value - the new value of this pixel\n * @return {this}\n */\n setPixel(index, value) {\n const target = index * this.channels;\n for (let i = 0; i < value.length; i++) {\n this.data[target + i] = value[i];\n }\n this.computed = null;\n return this;\n },\n};\n\nexport default function setValueMethods(Image) {\n for (const i in valueMethods) {\n Image.prototype[i] = valueMethods[i];\n }\n}\n","export default function getImageParameters(image) {\n return {\n width: image.width,\n height: image.height,\n components: image.components,\n alpha: image.alpha,\n colorModel: image.colorModel,\n bitDepth: image.bitDepth,\n };\n}\n","import Image from '../Image';\n\nimport getImageParameters from './getImageParameters';\n\n/**\n * Use this function to support getting the output image of an algorithm from user-supplied\n * options.\n * @private\n * @param {Image} thisImage - Original image on which the algorithm will be applied\n * @param {object} options - Options object received by the algorithm\n * @param {Image} [options.out] - If set, must be an image compatible with the algorithm\n * @param {object} newParameters - Parameters that will be combined with the ones from `thisImage`.\n * @param {object} internalOptions - Some additional options on the way to create the output image\n * @return {Image}\n */\nexport function getOutputImage(\n thisImage,\n options,\n newParameters,\n internalOptions = {},\n) {\n const { out } = options;\n if (out === undefined) {\n if (internalOptions.copy) {\n return thisImage.clone();\n } else {\n return Image.createFrom(thisImage, newParameters);\n }\n } else {\n if (!Image.isImage(out)) {\n throw new TypeError('out must be an Image object');\n }\n const requirements = Object.assign(\n getImageParameters(thisImage),\n newParameters,\n );\n for (const property in requirements) {\n if (out[property] !== requirements[property]) {\n throw new RangeError(\n `cannot use out. Its ${property} must be \"${requirements[property]}\" (found \"${out[property]}\")`,\n );\n }\n }\n return out;\n }\n}\n\n/**\n * Same as getOutputImage but allows for an `inPlace` option.\n * @private\n * @param {Image} thisImage\n * @param {object} options\n * @param {boolean} [options.inPlace=false] - If true, thisImage is returned\n * @param {Image} [options.out]\n * @param {object} internalOptions - Additional internal options on how to create the output image\n * @param {boolean} [interalOptions.copy] - If true will copy the original image instead of creating a new empty image\n * @return {Image}\n */\nexport function getOutputImageOrInPlace(thisImage, options, internalOptions) {\n if (options.inPlace !== undefined && typeof options.inPlace !== 'boolean') {\n throw new TypeError('inPlace option must be a boolean');\n }\n if (options.inPlace) {\n if (options.out !== undefined) {\n throw new TypeError(\n 'out option must not be set if inPlace option is true',\n );\n }\n return thisImage;\n }\n return getOutputImage(thisImage, options, null, internalOptions);\n}\n","import { getOutputImageOrInPlace } from '../internal/getOutputImage';\n\n/**\n * Calculate the absolute values of an image.\n * Only works on 32-bit images.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {boolean} [options.inPlace=false]\n * @param {Image} [options.out]\n * @return {Image}\n */\nexport default function abs(options = {}) {\n this.checkProcessable('abs', {\n bitDepth: [32],\n });\n const out = getOutputImageOrInPlace(this, options);\n absolute(this, out);\n return out;\n}\n\nfunction absolute(image, out) {\n for (let i = 0; i < image.data.length; i++) {\n out.data[i] = Math.abs(image.data[i]);\n }\n}\n","/**\n * Copies the alpha channel from an image to another. no-op if one of the images has no alpha\n * @private\n * @param {Image} from\n * @param {Image} to\n */\nexport default function copyAlphaChannel(from, to) {\n if (from.alpha === 1 && to.alpha === 1) {\n for (let i = 0; i < from.size; i++) {\n to.data[i * to.channels + to.components] =\n from.data[i * from.channels + from.components];\n }\n }\n}\n","import copyAlphaChannel from '../internal/copyAlphaChannel';\nimport { getOutputImageOrInPlace } from '../internal/getOutputImage';\n\n/**\n * Invert the colors of an image\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {boolean} [options.inPlace=false]\n * @param {Image} [options.out]\n * @return {Image}\n */\nexport default function invert(options = {}) {\n this.checkProcessable('invert', {\n bitDepth: [1, 8, 16],\n });\n\n const out = getOutputImageOrInPlace(this, options);\n\n if (this.bitDepth === 1) {\n invertBinary(this, out);\n } else {\n invertColor(this, out);\n if (this !== out) {\n copyAlphaChannel(this, out);\n }\n }\n return out;\n}\n\nfunction invertBinary(image, out) {\n for (let i = 0; i < image.data.length; i++) {\n out.data[i] = ~image.data[i];\n }\n}\n\nfunction invertColor(image, out) {\n for (let pixel = 0; pixel < image.data.length; pixel += image.channels) {\n for (let c = 0; c < image.components; c++) {\n out.data[pixel + c] = image.maxValue - image.data[pixel + c];\n }\n }\n}\n","/**\n * Flip an image horizontally.\n * @memberof Image\n * @instance\n * @return {this}\n */\nexport default function flipX() {\n this.checkProcessable('flipX', {\n bitDepth: [8, 16],\n });\n\n for (let i = 0; i < this.height; i++) {\n let offsetY = i * this.width * this.channels;\n\n for (let j = 0; j < Math.floor(this.width / 2); j++) {\n let posCurrent = j * this.channels + offsetY;\n let posOpposite = (this.width - j - 1) * this.channels + offsetY;\n\n for (let k = 0; k < this.channels; k++) {\n let tmp = this.data[posCurrent + k];\n this.data[posCurrent + k] = this.data[posOpposite + k];\n this.data[posOpposite + k] = tmp;\n }\n }\n }\n\n return this;\n}\n","/**\n * Flip an image vertically. The image\n * @memberof Image\n * @instance\n * @return {this}\n */\nexport default function flipY() {\n this.checkProcessable('flipY', {\n bitDepth: [8, 16],\n });\n\n for (let i = 0; i < Math.floor(this.height / 2); i++) {\n for (let j = 0; j < this.width; j++) {\n let posCurrent = j * this.channels + i * this.width * this.channels;\n let posOpposite =\n j * this.channels + (this.height - 1 - i) * this.channels * this.width;\n\n for (let k = 0; k < this.channels; k++) {\n let tmp = this.data[posCurrent + k];\n this.data[posCurrent + k] = this.data[posOpposite + k];\n this.data[posOpposite + k] = tmp;\n }\n }\n }\n\n return this;\n}\n","/**\n * Blurs the image by averaging the neighboring pixels.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.radius=1] - Number of pixels around the current pixel to average\n * @return {Image}\n */\nexport default function blurFilter(options = {}) {\n const { radius = 1 } = options;\n\n if (radius < 1) {\n throw new Error('radius must be greater than 1');\n }\n\n const n = 2 * radius + 1;\n const kernel = new Array(n);\n for (let i = 0; i < n; i++) {\n kernel[i] = new Array(n);\n for (let j = 0; j < n; j++) {\n kernel[i][j] = 1 / (n * n);\n }\n }\n\n return this.convolution(kernel);\n}\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 * as Model from '../image/model/model';\n\n/**\n * Specify which channels should be processed\n * * undefined : we take all the channels but alpha\n * * number : this specific channel\n * * string : converted to a channel based on rgb, cmyk, hsl or hsv (one letter code)\n * * [number] : array of channels as numbers\n * * [string] : array of channels as one letter string\n * @typedef {undefined|number|string|Array|Array} SelectedChannels\n */\n\nexport function validateArrayOfChannels(image, options = {}) {\n let {\n channels,\n allowAlpha, // are we allowing the selection of an alpha channel ?\n defaultAlpha, // if no channels are selected should we take the alpha channel ?\n } = options;\n\n if (typeof allowAlpha !== 'boolean') {\n allowAlpha = true;\n }\n\n if (typeof channels === 'undefined') {\n return allChannels(image, defaultAlpha);\n } else {\n return validateChannels(image, channels, allowAlpha);\n }\n}\n\nfunction allChannels(image, defaultAlpha) {\n let length = defaultAlpha ? image.channels : image.components;\n let array = new Array(length);\n for (let i = 0; i < length; i++) {\n array[i] = i;\n }\n return array;\n}\n\nfunction validateChannels(image, channels, allowAlpha) {\n if (!Array.isArray(channels)) {\n channels = [channels];\n }\n for (let c = 0; c < channels.length; c++) {\n channels[c] = validateChannel(image, channels[c], allowAlpha);\n }\n return channels;\n}\n\nexport function validateChannel(image, channel, allowAlpha = true) {\n if (channel === undefined) {\n throw new RangeError(\n `validateChannel : the channel has to be >=0 and <${image.channels}`,\n );\n }\n\n if (typeof channel === 'string') {\n switch (image.colorModel) {\n case Model.GREY:\n break;\n case Model.RGB:\n if ('rgb'.includes(channel)) {\n switch (channel) {\n case 'r':\n channel = 0;\n break;\n case 'g':\n channel = 1;\n break;\n case 'b':\n channel = 2;\n break;\n // no default\n }\n }\n break;\n case Model.HSL:\n if ('hsl'.includes(channel)) {\n switch (channel) {\n case 'h':\n channel = 0;\n break;\n case 's':\n channel = 1;\n break;\n case 'l':\n channel = 2;\n break;\n // no default\n }\n }\n break;\n case Model.HSV:\n if ('hsv'.includes(channel)) {\n switch (channel) {\n case 'h':\n channel = 0;\n break;\n case 's':\n channel = 1;\n break;\n case 'v':\n channel = 2;\n break;\n // no default\n }\n }\n break;\n case Model.CMYK:\n if ('cmyk'.includes(channel)) {\n switch (channel) {\n case 'c':\n channel = 0;\n break;\n case 'm':\n channel = 1;\n break;\n case 'y':\n channel = 2;\n break;\n case 'k':\n channel = 3;\n break;\n // no default\n }\n }\n break;\n default:\n throw new Error(`Unexpected color model: ${image.colorModel}`);\n }\n\n if (channel === 'a') {\n if (!image.alpha) {\n throw new Error(\n 'validateChannel : the image does not contain alpha channel',\n );\n }\n channel = image.components;\n }\n\n if (typeof channel === 'string') {\n throw new Error(`validateChannel : undefined channel: ${channel}`);\n }\n }\n\n if (channel >= image.channels) {\n throw new RangeError(\n `validateChannel : the channel has to be >=0 and <${image.channels}`,\n );\n }\n\n if (!allowAlpha && channel >= image.components) {\n throw new RangeError('validateChannel : alpha channel may not be selected');\n }\n\n return channel;\n}\n","import quickSelectMedian from 'median-quickselect';\n\nimport { validateArrayOfChannels } from '../../util/channel';\nimport Image from '../Image';\n\n/**\n * Each pixel of the image becomes the median of the neighbor pixels.\n * @memberof Image\n * @instance\n * @param {object} options\n * @param {SelectedChannels} [options.channels] - Specify which channels should be processed.\n * @param {number} [options.radius=1] - Distance of the square to take the mean of.\n * @param {string} [options.border='copy'] - Algorithm that will be applied after to deal with borders.\n * @return {Image}\n */\nexport default function medianFilter(options = {}) {\n let { radius = 1, border = 'copy', channels } = options;\n\n this.checkProcessable('medianFilter', {\n bitDepth: [8, 16],\n });\n\n if (radius < 1) {\n throw new Error('radius must be greater than 0');\n }\n\n channels = validateArrayOfChannels(this, channels, true);\n\n let kWidth = radius;\n let kHeight = radius;\n let newImage = Image.createFrom(this);\n\n let size = (kWidth * 2 + 1) * (kHeight * 2 + 1);\n let kernel = new Array(size);\n\n for (let channel = 0; channel < channels.length; channel++) {\n let c = channels[channel];\n for (let y = kHeight; y < this.height - kHeight; y++) {\n for (let x = kWidth; x < this.width - kWidth; x++) {\n let n = 0;\n for (let j = -kHeight; j <= kHeight; j++) {\n for (let i = -kWidth; i <= kWidth; i++) {\n let index = ((y + j) * this.width + x + i) * this.channels + c;\n kernel[n++] = this.data[index];\n }\n }\n\n let index = (y * this.width + x) * this.channels + c;\n\n newImage.data[index] = quickSelectMedian(kernel);\n }\n }\n }\n if (this.alpha && !channels.includes(this.channels)) {\n for (let i = this.components; i < this.data.length; i = i + this.channels) {\n newImage.data[i] = this.data[i];\n }\n }\n\n newImage.setBorder({ size: [kWidth, kHeight], algorithm: border });\n\n return newImage;\n}\n","/**\n * Apply a gaussian filter to the image.\n * @memberof Image\n * @instance\n * @param {object} options\n * @param {number} [options.radius=1] - Number of pixels around the current pixel.\n * @param {number} [options.sigma] - Sigma parameter for the gaussian.\n * @param {number[]|string[]} [options.channels] - To which channel to apply the filter.\n * @param {string} [options.border='copy']\n * @return {Image}\n */\nexport default function gaussianFilter(options = {}) {\n let { radius = 1, sigma, channels, border = 'copy' } = options;\n\n this.checkProcessable('gaussian', {\n bitDepth: [8, 16],\n });\n\n const kernel = getKernel(radius, sigma);\n return this.convolution([kernel, kernel], {\n border,\n channels,\n algorithm: 'separable',\n });\n}\n\nfunction getKernel(radius, sigma) {\n const n = radius * 2 + 1;\n const kernel = new Array(n);\n const sigmaX = sigma ? sigma : ((n - 1) * 0.5 - 1) * 0.3 + 0.8;\n const scale2X = -0.5 / (sigmaX * sigmaX);\n let sum = 0;\n for (let i = 0; i < n; i++) {\n const x = i - radius;\n const t = Math.exp(scale2X * x * x);\n kernel[i] = t;\n sum += t;\n }\n\n for (let i = 0; i < n; i++) {\n kernel[i] /= sum;\n }\n return kernel;\n}\n","export const DISCRETE_LAPLACE_4 = [\n [0, 1, 0],\n [1, -4, 1],\n [0, 1, 0],\n];\n\nexport const DISCRETE_LAPLACE_8 = [\n [1, 1, 1],\n [1, -8, 1],\n [1, 1, 1],\n];\n\nexport const SOBEL_X = [\n [-1, 0, +1],\n [-2, 0, +2],\n [-1, 0, +1],\n];\n\nexport const SOBEL_Y = [\n [-1, -2, -1],\n [0, 0, 0],\n [+1, +2, +1],\n];\n\nexport const SCHARR_X = [\n [3, 0, -3],\n [10, 0, -10],\n [3, 0, -3],\n];\n\nexport const SCHARR_Y = [\n [3, 10, 3],\n [0, 0, 0],\n [-3, -10, -3],\n];\n\nexport const SECOND_DERIVATIVE = [\n [-1, -2, 0, 2, 1],\n [-2, -4, 0, 4, 2],\n [0, 0, 0, 0, 0],\n [1, 2, 0, -2, -1],\n [2, 4, 0, -4, -2],\n];\n\nexport const SECOND_DERIVATIVE_INV = [\n [1, 2, 0, -2, -1],\n [2, 4, 0, -4, -2],\n [0, 0, 0, 0, 0],\n [-2, -4, 0, 4, 2],\n [-1, -2, 0, 2, 1],\n];\n","/**\n * Fast Fourier Transform module\n * 1D-FFT/IFFT, 2D-FFT/IFFT (radix-2)\n */\nvar FFT = (function(){\n var FFT; \n \n if(typeof exports !== 'undefined') {\n FFT = exports; // for CommonJS\n } else {\n FFT = {};\n }\n \n var version = {\n release: '0.3.0',\n date: '2013-03'\n };\n FFT.toString = function() {\n return \"version \" + version.release + \", released \" + version.date;\n };\n\n // core operations\n var _n = 0, // order\n _bitrev = null, // bit reversal table\n _cstb = null; // sin/cos table\n\n var core = {\n init : function(n) {\n if(n !== 0 && (n & (n - 1)) === 0) {\n _n = n;\n core._initArray();\n core._makeBitReversalTable();\n core._makeCosSinTable();\n } else {\n throw new Error(\"init: radix-2 required\");\n }\n },\n // 1D-FFT\n fft1d : function(re, im) {\n core.fft(re, im, 1);\n },\n // 1D-IFFT\n ifft1d : function(re, im) {\n var n = 1/_n;\n core.fft(re, im, -1);\n for(var i=0; i<_n; i++) {\n re[i] *= n;\n im[i] *= n;\n }\n },\n // 1D-IFFT\n bt1d : function(re, im) {\n core.fft(re, im, -1);\n },\n // 2D-FFT Not very useful if the number of rows have to be equal to cols\n fft2d : function(re, im) {\n var tre = [],\n tim = [],\n i = 0;\n // x-axis\n for(var y=0; y<_n; y++) {\n i = y*_n;\n for(var x1=0; x1<_n; x1++) {\n tre[x1] = re[x1 + i];\n tim[x1] = im[x1 + i];\n }\n core.fft1d(tre, tim);\n for(var x2=0; x2<_n; x2++) {\n re[x2 + i] = tre[x2];\n im[x2 + i] = tim[x2];\n }\n }\n // y-axis\n for(var x=0; x<_n; x++) {\n for(var y1=0; y1<_n; y1++) {\n i = x + y1*_n;\n tre[y1] = re[i];\n tim[y1] = im[i];\n }\n core.fft1d(tre, tim);\n for(var y2=0; y2<_n; y2++) {\n i = x + y2*_n;\n re[i] = tre[y2];\n im[i] = tim[y2];\n }\n }\n },\n // 2D-IFFT\n ifft2d : function(re, im) {\n var tre = [],\n tim = [],\n i = 0;\n // x-axis\n for(var y=0; y<_n; y++) {\n i = y*_n;\n for(var x1=0; x1<_n; x1++) {\n tre[x1] = re[x1 + i];\n tim[x1] = im[x1 + i];\n }\n core.ifft1d(tre, tim);\n for(var x2=0; x2<_n; x2++) {\n re[x2 + i] = tre[x2];\n im[x2 + i] = tim[x2];\n }\n }\n // y-axis\n for(var x=0; x<_n; x++) {\n for(var y1=0; y1<_n; y1++) {\n i = x + y1*_n;\n tre[y1] = re[i];\n tim[y1] = im[i];\n }\n core.ifft1d(tre, tim);\n for(var y2=0; y2<_n; y2++) {\n i = x + y2*_n;\n re[i] = tre[y2];\n im[i] = tim[y2];\n }\n }\n },\n // core operation of FFT\n fft : function(re, im, inv) {\n var d, h, ik, m, tmp, wr, wi, xr, xi,\n n4 = _n >> 2;\n // bit reversal\n for(var l=0; l<_n; l++) {\n m = _bitrev[l];\n if(l < m) {\n tmp = re[l];\n re[l] = re[m];\n re[m] = tmp;\n tmp = im[l];\n im[l] = im[m];\n im[m] = tmp;\n }\n }\n // butterfly operation\n for(var k=1; k<_n; k<<=1) {\n h = 0;\n d = _n/(k << 1);\n for(var j=0; j> 1;\n while(k <= j) {\n j -= k;\n k >>= 1;\n }\n j += k;\n _bitrev[i] = j;\n }\n },\n // makes trigonometiric function table\n _makeCosSinTable : function() {\n var n2 = _n >> 1,\n n4 = _n >> 2,\n n8 = _n >> 3,\n n2p4 = n2 + n4,\n t = Math.sin(Math.PI/_n),\n dc = 2*t*t,\n ds = Math.sqrt(dc*(2 - dc)),\n c = _cstb[n4] = 1,\n s = _cstb[0] = 0;\n t = 2*dc;\n for(var i=1; i= 0; iRow--) {\n tmpCols.re[iRow] = ft[(iRow * 2) * ftCols + iCol];\n tmpCols.im[iRow] = ft[(iRow * 2 + 1) * ftCols + iCol];\n }\n //Unnormalized inverse transform\n FFT.bt(tmpCols.re, tmpCols.im);\n for (var iRow = nRows - 1; iRow >= 0; iRow--) {\n tempTransform[(iRow * 2) * ftCols + iCol] = tmpCols.re[iRow];\n tempTransform[(iRow * 2 + 1) * ftCols + iCol] = tmpCols.im[iRow];\n }\n }\n\n // reverse row transform\n var finalTransform = new Array(nRows * nCols);\n FFT.init(nCols);\n var tmpRows = {re: new Array(nCols), im: new Array(nCols)};\n var scale = nCols * nRows;\n for (var iRow = 0; iRow < ftRows; iRow += 2) {\n tmpRows.re[0] = tempTransform[iRow * ftCols];\n tmpRows.im[0] = tempTransform[(iRow + 1) * ftCols];\n for (var iCol = 1; iCol < ftCols; iCol++) {\n tmpRows.re[iCol] = tempTransform[iRow * ftCols + iCol];\n tmpRows.im[iCol] = tempTransform[(iRow + 1) * ftCols + iCol];\n tmpRows.re[nCols - iCol] = tempTransform[iRow * ftCols + iCol];\n tmpRows.im[nCols - iCol] = -tempTransform[(iRow + 1) * ftCols + iCol];\n }\n //Unnormalized inverse transform\n FFT.bt(tmpRows.re, tmpRows.im);\n\n var indexB = (iRow / 2) * nCols;\n for (var iCol = nCols - 1; iCol >= 0; iCol--) {\n finalTransform[indexB + iCol] = tmpRows.re[iCol] / scale;\n }\n }\n return finalTransform;\n },\n /**\n * Calculates the fourier transform of a matrix of size (nRows,nCols) It is\n * assumed that both nRows and nCols are a power of two\n *\n * On exit the matrix has dimensions (nRows * 2, nCols / 2 + 1) where the\n * even rows contain the real part and the odd rows the imaginary part of the\n * transform\n * @param data\n * @param nRows\n * @param nCols\n * @return\n */\n fft2DArray:function(data, nRows, nCols, opt) {\n var options = Object.assign({},{inplace:true})\n var ftCols = (nCols / 2 + 1);\n var ftRows = nRows * 2;\n var tempTransform = new Array(ftRows * ftCols);\n FFT.init(nCols);\n // transform rows\n var tmpRows = {re: new Array(nCols), im: new Array(nCols)};\n var row1 = {re: new Array(nCols), im: new Array(nCols)}\n var row2 = {re: new Array(nCols), im: new Array(nCols)}\n var index, iRow0, iRow1, iRow2, iRow3;\n for (var iRow = 0; iRow < nRows / 2; iRow++) {\n index = (iRow * 2) * nCols;\n tmpRows.re = data.slice(index, index + nCols);\n\n index = (iRow * 2 + 1) * nCols;\n tmpRows.im = data.slice(index, index + nCols);\n\n FFT.fft1d(tmpRows.re, tmpRows.im);\n\n this.reconstructTwoRealFFT(tmpRows, row1, row2);\n //Now lets put back the result into the output array\n iRow0 = (iRow * 4) * ftCols;\n iRow1 = (iRow * 4 + 1) * ftCols;\n iRow2 = (iRow * 4 + 2) * ftCols;\n iRow3 = (iRow * 4 + 3) * ftCols;\n for (var k = ftCols - 1; k >= 0; k--) {\n tempTransform[iRow0 + k] = row1.re[k];\n tempTransform[iRow1 + k] = row1.im[k];\n tempTransform[iRow2 + k] = row2.re[k];\n tempTransform[iRow3 + k] = row2.im[k];\n }\n }\n\n //console.log(tempTransform);\n row1 = null;\n row2 = null;\n // transform columns\n var finalTransform = new Array(ftRows * ftCols);\n\n FFT.init(nRows);\n var tmpCols = {re: new Array(nRows), im: new Array(nRows)};\n for (var iCol = ftCols - 1; iCol >= 0; iCol--) {\n for (var iRow = nRows - 1; iRow >= 0; iRow--) {\n tmpCols.re[iRow] = tempTransform[(iRow * 2) * ftCols + iCol];\n tmpCols.im[iRow] = tempTransform[(iRow * 2 + 1) * ftCols + iCol];\n //TODO Chech why this happens\n if(isNaN(tmpCols.re[iRow])){\n tmpCols.re[iRow]=0;\n }\n if(isNaN(tmpCols.im[iRow])){\n tmpCols.im[iRow]=0;\n }\n }\n FFT.fft1d(tmpCols.re, tmpCols.im);\n for (var iRow = nRows - 1; iRow >= 0; iRow--) {\n finalTransform[(iRow * 2) * ftCols + iCol] = tmpCols.re[iRow];\n finalTransform[(iRow * 2 + 1) * ftCols + iCol] = tmpCols.im[iRow];\n }\n }\n\n //console.log(finalTransform);\n return finalTransform;\n\n },\n /**\n *\n * @param fourierTransform\n * @param realTransform1\n * @param realTransform2\n *\n * Reconstructs the individual Fourier transforms of two simultaneously\n * transformed series. Based on the Symmetry relationships (the asterisk\n * denotes the complex conjugate)\n *\n * F_{N-n} = F_n^{*} for a purely real f transformed to F\n *\n * G_{N-n} = G_n^{*} for a purely imaginary g transformed to G\n *\n */\n reconstructTwoRealFFT:function(fourierTransform, realTransform1, realTransform2) {\n var length = fourierTransform.re.length;\n\n // the components n=0 are trivial\n realTransform1.re[0] = fourierTransform.re[0];\n realTransform1.im[0] = 0.0;\n realTransform2.re[0] = fourierTransform.im[0];\n realTransform2.im[0] = 0.0;\n var rm, rp, im, ip, j;\n for (var i = length / 2; i > 0; i--) {\n j = length - i;\n rm = 0.5 * (fourierTransform.re[i] - fourierTransform.re[j]);\n rp = 0.5 * (fourierTransform.re[i] + fourierTransform.re[j]);\n im = 0.5 * (fourierTransform.im[i] - fourierTransform.im[j]);\n ip = 0.5 * (fourierTransform.im[i] + fourierTransform.im[j]);\n realTransform1.re[i] = rp;\n realTransform1.im[i] = im;\n realTransform1.re[j] = rp;\n realTransform1.im[j] = -im;\n realTransform2.re[i] = ip;\n realTransform2.im[i] = -rm;\n realTransform2.re[j] = ip;\n realTransform2.im[j] = rm;\n }\n },\n\n /**\n * In place version of convolute 2D\n *\n * @param ftSignal\n * @param ftFilter\n * @param ftRows\n * @param ftCols\n * @return\n */\n convolute2DI:function(ftSignal, ftFilter, ftRows, ftCols) {\n var re, im;\n for (var iRow = 0; iRow < ftRows / 2; iRow++) {\n for (var iCol = 0; iCol < ftCols; iCol++) {\n //\n re = ftSignal[(iRow * 2) * ftCols + iCol]\n * ftFilter[(iRow * 2) * ftCols + iCol]\n - ftSignal[(iRow * 2 + 1) * ftCols + iCol]\n * ftFilter[(iRow * 2 + 1) * ftCols + iCol];\n im = ftSignal[(iRow * 2) * ftCols + iCol]\n * ftFilter[(iRow * 2 + 1) * ftCols + iCol]\n + ftSignal[(iRow * 2 + 1) * ftCols + iCol]\n * ftFilter[(iRow * 2) * ftCols + iCol];\n //\n ftSignal[(iRow * 2) * ftCols + iCol] = re;\n ftSignal[(iRow * 2 + 1) * ftCols + iCol] = im;\n }\n }\n },\n /**\n *\n * @param data\n * @param kernel\n * @param nRows\n * @param nCols\n * @returns {*}\n */\n convolute:function(data, kernel, nRows, nCols, opt) {\n var ftSpectrum = new Array(nCols * nRows);\n for (var i = 0; i>++cols)!=0);\n cols=1<>++rows)!=0);\n rows=1< 1 && arguments[1] !== undefined ? arguments[1] : {};\n\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 var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var maxValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] > maxValue) maxValue = input[i];\n }\n\n return maxValue;\n}\n\nexport default max;\n","import isArray from 'is-any-array';\n\nfunction min(input) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\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 var _options$fromIndex = options.fromIndex,\n fromIndex = _options$fromIndex === void 0 ? 0 : _options$fromIndex,\n _options$toIndex = options.toIndex,\n toIndex = _options$toIndex === void 0 ? input.length : _options$toIndex;\n\n if (fromIndex < 0 || fromIndex >= input.length || !Number.isInteger(fromIndex)) {\n throw new Error('fromIndex must be a positive integer smaller than length');\n }\n\n if (toIndex <= fromIndex || toIndex > input.length || !Number.isInteger(toIndex)) {\n throw new Error('toIndex must be an integer greater than fromIndex and at most equal to length');\n }\n\n var minValue = input[fromIndex];\n\n for (var i = fromIndex + 1; i < toIndex; i++) {\n if (input[i] < minValue) minValue = input[i];\n }\n\n return minValue;\n}\n\nexport default min;\n","import isArray from 'is-any-array';\nimport max from 'ml-array-max';\nimport min from 'ml-array-min';\n\nfunction rescale(input) {\n var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n\n if (!isArray(input)) {\n throw new TypeError('input must be an array');\n } else if (input.length === 0) {\n throw new TypeError('input must not be empty');\n }\n\n var output;\n\n if (options.output !== undefined) {\n if (!isArray(options.output)) {\n throw new TypeError('output option must be an array if specified');\n }\n\n output = options.output;\n } else {\n output = new Array(input.length);\n }\n\n var currentMin = min(input);\n var currentMax = max(input);\n\n if (currentMin === currentMax) {\n throw new RangeError('minimum and maximum input values are equal. Cannot rescale a constant array');\n }\n\n var _options$min = options.min,\n minValue = _options$min === void 0 ? options.autoMinMax ? currentMin : 0 : _options$min,\n _options$max = options.max,\n maxValue = _options$max === void 0 ? options.autoMinMax ? currentMax : 1 : _options$max;\n\n if (minValue >= maxValue) {\n throw new RangeError('min option must be smaller than max option');\n }\n\n var factor = (maxValue - minValue) / (currentMax - currentMin);\n\n for (var i = 0; i < input.length; i++) {\n output[i] = (input[i] - currentMin) * factor + minValue;\n }\n\n return output;\n}\n\nexport default rescale;\n","const indent = ' '.repeat(2);\nconst indentData = ' '.repeat(4);\n\nexport function inspectMatrix() {\n return inspectMatrixWithOptions(this);\n}\n\nexport function inspectMatrixWithOptions(matrix, options = {}) {\n const { maxRows = 15, maxColumns = 10, maxNumSize = 8 } = options;\n return `${matrix.constructor.name} {\n${indent}[\n${indentData}${inspectData(matrix, maxRows, maxColumns, maxNumSize)}\n${indent}]\n${indent}rows: ${matrix.rows}\n${indent}columns: ${matrix.columns}\n}`;\n}\n\nfunction inspectData(matrix, maxRows, maxColumns, maxNumSize) {\n const { rows, columns } = matrix;\n const maxI = Math.min(rows, maxRows);\n const maxJ = Math.min(columns, maxColumns);\n const result = [];\n for (let i = 0; i < maxI; i++) {\n let line = [];\n for (let j = 0; j < maxJ; j++) {\n line.push(formatNumber(matrix.get(i, j), maxNumSize));\n }\n result.push(`${line.join(' ')}`);\n }\n if (maxJ !== columns) {\n result[result.length - 1] += ` ... ${columns - maxColumns} more columns`;\n }\n if (maxI !== rows) {\n result.push(`... ${rows - maxRows} more rows`);\n }\n return result.join(`\\n${indentData}`);\n}\n\nfunction formatNumber(num, maxNumSize) {\n const numStr = String(num);\n if (numStr.length <= maxNumSize) {\n return numStr.padEnd(maxNumSize, ' ');\n }\n const precise = num.toPrecision(maxNumSize - 2);\n if (precise.length <= maxNumSize) {\n return precise;\n }\n const exponential = num.toExponential(maxNumSize - 2);\n const eIndex = exponential.indexOf('e');\n const e = exponential.slice(eIndex);\n return exponential.slice(0, maxNumSize - e.length) + e;\n}\n","export function installMathOperations(AbstractMatrix, Matrix) {\n AbstractMatrix.prototype.add = function add(value) {\n if (typeof value === 'number') return this.addS(value);\n return this.addM(value);\n };\n\n AbstractMatrix.prototype.addS = function addS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.addM = function addM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.add = function add(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.add(value);\n };\n\n AbstractMatrix.prototype.sub = function sub(value) {\n if (typeof value === 'number') return this.subS(value);\n return this.subM(value);\n };\n\n AbstractMatrix.prototype.subS = function subS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.subM = function subM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.sub = function sub(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sub(value);\n };\n AbstractMatrix.prototype.subtract = AbstractMatrix.prototype.sub;\n AbstractMatrix.prototype.subtractS = AbstractMatrix.prototype.subS;\n AbstractMatrix.prototype.subtractM = AbstractMatrix.prototype.subM;\n AbstractMatrix.subtract = AbstractMatrix.sub;\n\n AbstractMatrix.prototype.mul = function mul(value) {\n if (typeof value === 'number') return this.mulS(value);\n return this.mulM(value);\n };\n\n AbstractMatrix.prototype.mulS = function mulS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.mulM = function mulM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.mul = function mul(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.mul(value);\n };\n AbstractMatrix.prototype.multiply = AbstractMatrix.prototype.mul;\n AbstractMatrix.prototype.multiplyS = AbstractMatrix.prototype.mulS;\n AbstractMatrix.prototype.multiplyM = AbstractMatrix.prototype.mulM;\n AbstractMatrix.multiply = AbstractMatrix.mul;\n\n AbstractMatrix.prototype.div = function div(value) {\n if (typeof value === 'number') return this.divS(value);\n return this.divM(value);\n };\n\n AbstractMatrix.prototype.divS = function divS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.divM = function divM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.div = function div(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.div(value);\n };\n AbstractMatrix.prototype.divide = AbstractMatrix.prototype.div;\n AbstractMatrix.prototype.divideS = AbstractMatrix.prototype.divS;\n AbstractMatrix.prototype.divideM = AbstractMatrix.prototype.divM;\n AbstractMatrix.divide = AbstractMatrix.div;\n\n AbstractMatrix.prototype.mod = function mod(value) {\n if (typeof value === 'number') return this.modS(value);\n return this.modM(value);\n };\n\n AbstractMatrix.prototype.modS = function modS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) % value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.modM = function modM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) % matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.mod = function mod(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.mod(value);\n };\n AbstractMatrix.prototype.modulus = AbstractMatrix.prototype.mod;\n AbstractMatrix.prototype.modulusS = AbstractMatrix.prototype.modS;\n AbstractMatrix.prototype.modulusM = AbstractMatrix.prototype.modM;\n AbstractMatrix.modulus = AbstractMatrix.mod;\n\n AbstractMatrix.prototype.and = function and(value) {\n if (typeof value === 'number') return this.andS(value);\n return this.andM(value);\n };\n\n AbstractMatrix.prototype.andS = function andS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) & value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.andM = function andM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) & matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.and = function and(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.and(value);\n };\n\n AbstractMatrix.prototype.or = function or(value) {\n if (typeof value === 'number') return this.orS(value);\n return this.orM(value);\n };\n\n AbstractMatrix.prototype.orS = function orS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) | value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.orM = function orM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) | matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.or = function or(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.or(value);\n };\n\n AbstractMatrix.prototype.xor = function xor(value) {\n if (typeof value === 'number') return this.xorS(value);\n return this.xorM(value);\n };\n\n AbstractMatrix.prototype.xorS = function xorS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) ^ value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.xorM = function xorM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) ^ matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.xor = function xor(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.xor(value);\n };\n\n AbstractMatrix.prototype.leftShift = function leftShift(value) {\n if (typeof value === 'number') return this.leftShiftS(value);\n return this.leftShiftM(value);\n };\n\n AbstractMatrix.prototype.leftShiftS = function leftShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) << value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.leftShiftM = function leftShiftM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) << matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.leftShift = function leftShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.leftShift(value);\n };\n\n AbstractMatrix.prototype.signPropagatingRightShift = function signPropagatingRightShift(value) {\n if (typeof value === 'number') return this.signPropagatingRightShiftS(value);\n return this.signPropagatingRightShiftM(value);\n };\n\n AbstractMatrix.prototype.signPropagatingRightShiftS = function signPropagatingRightShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >> value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.signPropagatingRightShiftM = function signPropagatingRightShiftM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >> matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.signPropagatingRightShift = function signPropagatingRightShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.signPropagatingRightShift(value);\n };\n\n AbstractMatrix.prototype.rightShift = function rightShift(value) {\n if (typeof value === 'number') return this.rightShiftS(value);\n return this.rightShiftM(value);\n };\n\n AbstractMatrix.prototype.rightShiftS = function rightShiftS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >>> value);\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.rightShiftM = function rightShiftM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) >>> matrix.get(i, j));\n }\n }\n return this;\n };\n\n AbstractMatrix.rightShift = function rightShift(matrix, value) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.rightShift(value);\n };\n AbstractMatrix.prototype.zeroFillRightShift = AbstractMatrix.prototype.rightShift;\n AbstractMatrix.prototype.zeroFillRightShiftS = AbstractMatrix.prototype.rightShiftS;\n AbstractMatrix.prototype.zeroFillRightShiftM = AbstractMatrix.prototype.rightShiftM;\n AbstractMatrix.zeroFillRightShift = AbstractMatrix.rightShift;\n\n AbstractMatrix.prototype.not = function not() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, ~(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.not = function not(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.not();\n };\n\n AbstractMatrix.prototype.abs = function abs() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.abs(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.abs = function abs(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.abs();\n };\n\n AbstractMatrix.prototype.acos = function acos() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.acos(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.acos = function acos(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.acos();\n };\n\n AbstractMatrix.prototype.acosh = function acosh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.acosh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.acosh = function acosh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.acosh();\n };\n\n AbstractMatrix.prototype.asin = function asin() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.asin(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.asin = function asin(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.asin();\n };\n\n AbstractMatrix.prototype.asinh = function asinh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.asinh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.asinh = function asinh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.asinh();\n };\n\n AbstractMatrix.prototype.atan = function atan() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.atan(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.atan = function atan(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.atan();\n };\n\n AbstractMatrix.prototype.atanh = function atanh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.atanh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.atanh = function atanh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.atanh();\n };\n\n AbstractMatrix.prototype.cbrt = function cbrt() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cbrt(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cbrt = function cbrt(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cbrt();\n };\n\n AbstractMatrix.prototype.ceil = function ceil() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.ceil(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.ceil = function ceil(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.ceil();\n };\n\n AbstractMatrix.prototype.clz32 = function clz32() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.clz32(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.clz32 = function clz32(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.clz32();\n };\n\n AbstractMatrix.prototype.cos = function cos() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cos(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cos = function cos(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cos();\n };\n\n AbstractMatrix.prototype.cosh = function cosh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.cosh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.cosh = function cosh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.cosh();\n };\n\n AbstractMatrix.prototype.exp = function exp() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.exp(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.exp = function exp(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.exp();\n };\n\n AbstractMatrix.prototype.expm1 = function expm1() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.expm1(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.expm1 = function expm1(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.expm1();\n };\n\n AbstractMatrix.prototype.floor = function floor() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.floor(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.floor = function floor(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.floor();\n };\n\n AbstractMatrix.prototype.fround = function fround() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.fround(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.fround = function fround(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.fround();\n };\n\n AbstractMatrix.prototype.log = function log() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log = function log(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log();\n };\n\n AbstractMatrix.prototype.log1p = function log1p() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log1p(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log1p = function log1p(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log1p();\n };\n\n AbstractMatrix.prototype.log10 = function log10() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log10(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log10 = function log10(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log10();\n };\n\n AbstractMatrix.prototype.log2 = function log2() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.log2(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.log2 = function log2(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.log2();\n };\n\n AbstractMatrix.prototype.round = function round() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.round(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.round = function round(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.round();\n };\n\n AbstractMatrix.prototype.sign = function sign() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sign(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sign = function sign(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sign();\n };\n\n AbstractMatrix.prototype.sin = function sin() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sin(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sin = function sin(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sin();\n };\n\n AbstractMatrix.prototype.sinh = function sinh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sinh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sinh = function sinh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sinh();\n };\n\n AbstractMatrix.prototype.sqrt = function sqrt() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.sqrt(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.sqrt = function sqrt(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.sqrt();\n };\n\n AbstractMatrix.prototype.tan = function tan() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.tan(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.tan = function tan(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.tan();\n };\n\n AbstractMatrix.prototype.tanh = function tanh() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.tanh(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.tanh = function tanh(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.tanh();\n };\n\n AbstractMatrix.prototype.trunc = function trunc() {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.trunc(this.get(i, j)));\n }\n }\n return this;\n };\n\n AbstractMatrix.trunc = function trunc(matrix) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.trunc();\n };\n\n AbstractMatrix.pow = function pow(matrix, arg0) {\n const newMatrix = new Matrix(matrix);\n return newMatrix.pow(arg0);\n };\n\n AbstractMatrix.prototype.pow = function pow(value) {\n if (typeof value === 'number') return this.powS(value);\n return this.powM(value);\n };\n\n AbstractMatrix.prototype.powS = function powS(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.pow(this.get(i, j), value));\n }\n }\n return this;\n };\n\n AbstractMatrix.prototype.powM = function powM(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (this.rows !== matrix.rows ||\n this.columns !== matrix.columns) {\n throw new RangeError('Matrices dimensions must be equal');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, Math.pow(this.get(i, j), matrix.get(i, j)));\n }\n }\n return this;\n };\n}\n","/**\n * @private\n * Check that a row index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkRowIndex(matrix, index, outer) {\n let max = outer ? matrix.rows : matrix.rows - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Row index out of range');\n }\n}\n\n/**\n * @private\n * Check that a column index is not out of bounds\n * @param {Matrix} matrix\n * @param {number} index\n * @param {boolean} [outer]\n */\nexport function checkColumnIndex(matrix, index, outer) {\n let max = outer ? matrix.columns : matrix.columns - 1;\n if (index < 0 || index > max) {\n throw new RangeError('Column index out of range');\n }\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexport function checkRowVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.columns) {\n throw new RangeError(\n 'vector size must be the same as the number of columns',\n );\n }\n return vector;\n}\n\n/**\n * @private\n * Check that the provided vector is an array with the right length\n * @param {Matrix} matrix\n * @param {Array|Matrix} vector\n * @return {Array}\n * @throws {RangeError}\n */\nexport function checkColumnVector(matrix, vector) {\n if (vector.to1DArray) {\n vector = vector.to1DArray();\n }\n if (vector.length !== matrix.rows) {\n throw new RangeError('vector size must be the same as the number of rows');\n }\n return vector;\n}\n\nexport function checkIndices(matrix, rowIndices, columnIndices) {\n return {\n row: checkRowIndices(matrix, rowIndices),\n column: checkColumnIndices(matrix, columnIndices),\n };\n}\n\nexport function checkRowIndices(matrix, rowIndices) {\n if (typeof rowIndices !== 'object') {\n throw new TypeError('unexpected type for row indices');\n }\n\n let rowOut = rowIndices.some((r) => {\n return r < 0 || r >= matrix.rows;\n });\n\n if (rowOut) {\n throw new RangeError('row indices are out of range');\n }\n\n if (!Array.isArray(rowIndices)) rowIndices = Array.from(rowIndices);\n\n return rowIndices;\n}\n\nexport function checkColumnIndices(matrix, columnIndices) {\n if (typeof columnIndices !== 'object') {\n throw new TypeError('unexpected type for column indices');\n }\n\n let columnOut = columnIndices.some((c) => {\n return c < 0 || c >= matrix.columns;\n });\n\n if (columnOut) {\n throw new RangeError('column indices are out of range');\n }\n if (!Array.isArray(columnIndices)) columnIndices = Array.from(columnIndices);\n\n return columnIndices;\n}\n\nexport function checkRange(matrix, startRow, endRow, startColumn, endColumn) {\n if (arguments.length !== 5) {\n throw new RangeError('expected 4 arguments');\n }\n checkNumber('startRow', startRow);\n checkNumber('endRow', endRow);\n checkNumber('startColumn', startColumn);\n checkNumber('endColumn', endColumn);\n if (\n startRow > endRow ||\n startColumn > endColumn ||\n startRow < 0 ||\n startRow >= matrix.rows ||\n endRow < 0 ||\n endRow >= matrix.rows ||\n startColumn < 0 ||\n startColumn >= matrix.columns ||\n endColumn < 0 ||\n endColumn >= matrix.columns\n ) {\n throw new RangeError('Submatrix indices are out of range');\n }\n}\n\nexport function newArray(length, value = 0) {\n let array = [];\n for (let i = 0; i < length; i++) {\n array.push(value);\n }\n return array;\n}\n\nfunction checkNumber(name, value) {\n if (typeof value !== 'number') {\n throw new TypeError(`${name} must be a number`);\n }\n}\n\nexport function checkNonEmpty(matrix) {\n if (matrix.isEmpty()) {\n throw new Error('Empty matrix has no elements to index');\n }\n}\n","import { newArray } from './util';\n\nexport function sumByRow(matrix) {\n let sum = newArray(matrix.rows);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumByColumn(matrix) {\n let sum = newArray(matrix.columns);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] += matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function sumAll(matrix) {\n let v = 0;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v += matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function productByRow(matrix) {\n let sum = newArray(matrix.rows, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[i] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productByColumn(matrix) {\n let sum = newArray(matrix.columns, 1);\n for (let i = 0; i < matrix.rows; ++i) {\n for (let j = 0; j < matrix.columns; ++j) {\n sum[j] *= matrix.get(i, j);\n }\n }\n return sum;\n}\n\nexport function productAll(matrix) {\n let v = 1;\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n v *= matrix.get(i, j);\n }\n }\n return v;\n}\n\nexport function varianceByRow(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let i = 0; i < rows; i++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean[i];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / cols) / (cols - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / cols) / cols);\n }\n }\n return variance;\n}\n\nexport function varianceByColumn(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const variance = [];\n\n for (let j = 0; j < cols; j++) {\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n x = matrix.get(i, j) - mean[j];\n sum1 += x;\n sum2 += x * x;\n }\n if (unbiased) {\n variance.push((sum2 - (sum1 * sum1) / rows) / (rows - 1));\n } else {\n variance.push((sum2 - (sum1 * sum1) / rows) / rows);\n }\n }\n return variance;\n}\n\nexport function varianceAll(matrix, unbiased, mean) {\n const rows = matrix.rows;\n const cols = matrix.columns;\n const size = rows * cols;\n\n let sum1 = 0;\n let sum2 = 0;\n let x = 0;\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < cols; j++) {\n x = matrix.get(i, j) - mean;\n sum1 += x;\n sum2 += x * x;\n }\n }\n if (unbiased) {\n return (sum2 - (sum1 * sum1) / size) / (size - 1);\n } else {\n return (sum2 - (sum1 * sum1) / size) / size;\n }\n}\n\nexport function centerByRow(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[i]);\n }\n }\n}\n\nexport function centerByColumn(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean[j]);\n }\n }\n}\n\nexport function centerAll(matrix, mean) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) - mean);\n }\n }\n}\n\nexport function getScaleByRow(matrix) {\n const scale = [];\n for (let i = 0; i < matrix.rows; i++) {\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.columns - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByRow(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[i]);\n }\n }\n}\n\nexport function getScaleByColumn(matrix) {\n const scale = [];\n for (let j = 0; j < matrix.columns; j++) {\n let sum = 0;\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / (matrix.rows - 1);\n }\n scale.push(Math.sqrt(sum));\n }\n return scale;\n}\n\nexport function scaleByColumn(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale[j]);\n }\n }\n}\n\nexport function getScaleAll(matrix) {\n const divider = matrix.size - 1;\n let sum = 0;\n for (let j = 0; j < matrix.columns; j++) {\n for (let i = 0; i < matrix.rows; i++) {\n sum += Math.pow(matrix.get(i, j), 2) / divider;\n }\n }\n return Math.sqrt(sum);\n}\n\nexport function scaleAll(matrix, scale) {\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n matrix.set(i, j, matrix.get(i, j) / scale);\n }\n }\n}\n","import rescale from 'ml-array-rescale';\n\nimport { inspectMatrix, inspectMatrixWithOptions } from './inspect';\nimport { installMathOperations } from './mathOperations';\nimport {\n sumByRow,\n sumByColumn,\n sumAll,\n productByRow,\n productByColumn,\n productAll,\n varianceByRow,\n varianceByColumn,\n varianceAll,\n centerByRow,\n centerByColumn,\n centerAll,\n scaleByRow,\n scaleByColumn,\n scaleAll,\n getScaleByRow,\n getScaleByColumn,\n getScaleAll,\n} from './stat';\nimport {\n checkRowVector,\n checkRowIndex,\n checkColumnIndex,\n checkColumnVector,\n checkRange,\n checkIndices,\n checkNonEmpty,\n} from './util';\n\nexport class AbstractMatrix {\n static from1DArray(newRows, newColumns, newData) {\n let length = newRows * newColumns;\n if (length !== newData.length) {\n throw new RangeError('data length does not match given dimensions');\n }\n let newMatrix = new Matrix(newRows, newColumns);\n for (let row = 0; row < newRows; row++) {\n for (let column = 0; column < newColumns; column++) {\n newMatrix.set(row, column, newData[row * newColumns + column]);\n }\n }\n return newMatrix;\n }\n\n static rowVector(newData) {\n let vector = new Matrix(1, newData.length);\n for (let i = 0; i < newData.length; i++) {\n vector.set(0, i, newData[i]);\n }\n return vector;\n }\n\n static columnVector(newData) {\n let vector = new Matrix(newData.length, 1);\n for (let i = 0; i < newData.length; i++) {\n vector.set(i, 0, newData[i]);\n }\n return vector;\n }\n\n static zeros(rows, columns) {\n return new Matrix(rows, columns);\n }\n\n static ones(rows, columns) {\n return new Matrix(rows, columns).fill(1);\n }\n\n static rand(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { random = Math.random } = options;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.set(i, j, random());\n }\n }\n return matrix;\n }\n\n static randInt(rows, columns, options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1000, random = Math.random } = options;\n if (!Number.isInteger(min)) throw new TypeError('min must be an integer');\n if (!Number.isInteger(max)) throw new TypeError('max must be an integer');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let interval = max - min;\n let matrix = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n let value = min + Math.round(random() * interval);\n matrix.set(i, j, value);\n }\n }\n return matrix;\n }\n\n static eye(rows, columns, value) {\n if (columns === undefined) columns = rows;\n if (value === undefined) value = 1;\n let min = Math.min(rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, value);\n }\n return matrix;\n }\n\n static diag(data, rows, columns) {\n let l = data.length;\n if (rows === undefined) rows = l;\n if (columns === undefined) columns = rows;\n let min = Math.min(l, rows, columns);\n let matrix = this.zeros(rows, columns);\n for (let i = 0; i < min; i++) {\n matrix.set(i, i, data[i]);\n }\n return matrix;\n }\n\n static min(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n result.set(i, j, Math.min(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n static max(matrix1, matrix2) {\n matrix1 = this.checkMatrix(matrix1);\n matrix2 = this.checkMatrix(matrix2);\n let rows = matrix1.rows;\n let columns = matrix1.columns;\n let result = new this(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n result.set(i, j, Math.max(matrix1.get(i, j), matrix2.get(i, j)));\n }\n }\n return result;\n }\n\n static checkMatrix(value) {\n return AbstractMatrix.isMatrix(value) ? value : new Matrix(value);\n }\n\n static isMatrix(value) {\n return value != null && value.klass === 'Matrix';\n }\n\n get size() {\n return this.rows * this.columns;\n }\n\n apply(callback) {\n if (typeof callback !== 'function') {\n throw new TypeError('callback must be a function');\n }\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n callback.call(this, i, j);\n }\n }\n return this;\n }\n\n to1DArray() {\n let array = [];\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n array.push(this.get(i, j));\n }\n }\n return array;\n }\n\n to2DArray() {\n let copy = [];\n for (let i = 0; i < this.rows; i++) {\n copy.push([]);\n for (let j = 0; j < this.columns; j++) {\n copy[i].push(this.get(i, j));\n }\n }\n return copy;\n }\n\n toJSON() {\n return this.to2DArray();\n }\n\n isRowVector() {\n return this.rows === 1;\n }\n\n isColumnVector() {\n return this.columns === 1;\n }\n\n isVector() {\n return this.rows === 1 || this.columns === 1;\n }\n\n isSquare() {\n return this.rows === this.columns;\n }\n\n isEmpty() {\n return this.rows === 0 || this.columns === 0;\n }\n\n isSymmetric() {\n if (this.isSquare()) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j <= i; j++) {\n if (this.get(i, j) !== this.get(j, i)) {\n return false;\n }\n }\n }\n return true;\n }\n return false;\n }\n\n isEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isEchelonForm = true;\n let checked = false;\n while (i < this.rows && isEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isEchelonForm = false;\n checked = true;\n }\n }\n i++;\n }\n return isEchelonForm;\n }\n\n isReducedEchelonForm() {\n let i = 0;\n let j = 0;\n let previousColumn = -1;\n let isReducedEchelonForm = true;\n let checked = false;\n while (i < this.rows && isReducedEchelonForm) {\n j = 0;\n checked = false;\n while (j < this.columns && checked === false) {\n if (this.get(i, j) === 0) {\n j++;\n } else if (this.get(i, j) === 1 && j > previousColumn) {\n checked = true;\n previousColumn = j;\n } else {\n isReducedEchelonForm = false;\n checked = true;\n }\n }\n for (let k = j + 1; k < this.rows; k++) {\n if (this.get(i, k) !== 0) {\n isReducedEchelonForm = false;\n }\n }\n i++;\n }\n return isReducedEchelonForm;\n }\n\n echelonForm() {\n let result = this.clone();\n let h = 0;\n let k = 0;\n while (h < result.rows && k < result.columns) {\n let iMax = h;\n for (let i = h; i < result.rows; i++) {\n if (result.get(i, k) > result.get(iMax, k)) {\n iMax = i;\n }\n }\n if (result.get(iMax, k) === 0) {\n k++;\n } else {\n result.swapRows(h, iMax);\n let tmp = result.get(h, k);\n for (let j = k; j < result.columns; j++) {\n result.set(h, j, result.get(h, j) / tmp);\n }\n for (let i = h + 1; i < result.rows; i++) {\n let factor = result.get(i, k) / result.get(h, k);\n result.set(i, k, 0);\n for (let j = k + 1; j < result.columns; j++) {\n result.set(i, j, result.get(i, j) - result.get(h, j) * factor);\n }\n }\n h++;\n k++;\n }\n }\n return result;\n }\n\n reducedEchelonForm() {\n let result = this.echelonForm();\n let m = result.columns;\n let n = result.rows;\n let h = n - 1;\n while (h >= 0) {\n if (result.maxRow(h) === 0) {\n h--;\n } else {\n let p = 0;\n let pivot = false;\n while (p < n && pivot === false) {\n if (result.get(h, p) === 1) {\n pivot = true;\n } else {\n p++;\n }\n }\n for (let i = 0; i < h; i++) {\n let factor = result.get(i, p);\n for (let j = p; j < m; j++) {\n let tmp = result.get(i, j) - factor * result.get(h, j);\n result.set(i, j, tmp);\n }\n }\n h--;\n }\n }\n return result;\n }\n\n set() {\n throw new Error('set method is unimplemented');\n }\n\n get() {\n throw new Error('get method is unimplemented');\n }\n\n repeat(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { rows = 1, columns = 1 } = options;\n if (!Number.isInteger(rows) || rows <= 0) {\n throw new TypeError('rows must be a positive integer');\n }\n if (!Number.isInteger(columns) || columns <= 0) {\n throw new TypeError('columns must be a positive integer');\n }\n let matrix = new Matrix(this.rows * rows, this.columns * columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n matrix.setSubMatrix(this, this.rows * i, this.columns * j);\n }\n }\n return matrix;\n }\n\n fill(value) {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, value);\n }\n }\n return this;\n }\n\n neg() {\n return this.mulS(-1);\n }\n\n getRow(index) {\n checkRowIndex(this, index);\n let row = [];\n for (let i = 0; i < this.columns; i++) {\n row.push(this.get(index, i));\n }\n return row;\n }\n\n getRowVector(index) {\n return Matrix.rowVector(this.getRow(index));\n }\n\n setRow(index, array) {\n checkRowIndex(this, index);\n array = checkRowVector(this, array);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, array[i]);\n }\n return this;\n }\n\n swapRows(row1, row2) {\n checkRowIndex(this, row1);\n checkRowIndex(this, row2);\n for (let i = 0; i < this.columns; i++) {\n let temp = this.get(row1, i);\n this.set(row1, i, this.get(row2, i));\n this.set(row2, i, temp);\n }\n return this;\n }\n\n getColumn(index) {\n checkColumnIndex(this, index);\n let column = [];\n for (let i = 0; i < this.rows; i++) {\n column.push(this.get(i, index));\n }\n return column;\n }\n\n getColumnVector(index) {\n return Matrix.columnVector(this.getColumn(index));\n }\n\n setColumn(index, array) {\n checkColumnIndex(this, index);\n array = checkColumnVector(this, array);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, array[i]);\n }\n return this;\n }\n\n swapColumns(column1, column2) {\n checkColumnIndex(this, column1);\n checkColumnIndex(this, column2);\n for (let i = 0; i < this.rows; i++) {\n let temp = this.get(i, column1);\n this.set(i, column1, this.get(i, column2));\n this.set(i, column2, temp);\n }\n return this;\n }\n\n addRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[j]);\n }\n }\n return this;\n }\n\n subRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[j]);\n }\n }\n return this;\n }\n\n mulRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[j]);\n }\n }\n return this;\n }\n\n divRowVector(vector) {\n vector = checkRowVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[j]);\n }\n }\n return this;\n }\n\n addColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) + vector[i]);\n }\n }\n return this;\n }\n\n subColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) - vector[i]);\n }\n }\n return this;\n }\n\n mulColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) * vector[i]);\n }\n }\n return this;\n }\n\n divColumnVector(vector) {\n vector = checkColumnVector(this, vector);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n this.set(i, j, this.get(i, j) / vector[i]);\n }\n }\n return this;\n }\n\n mulRow(index, value) {\n checkRowIndex(this, index);\n for (let i = 0; i < this.columns; i++) {\n this.set(index, i, this.get(index, i) * value);\n }\n return this;\n }\n\n mulColumn(index, value) {\n checkColumnIndex(this, index);\n for (let i = 0; i < this.rows; i++) {\n this.set(i, index, this.get(i, index) * value);\n }\n return this;\n }\n\n max() {\n if (this.isEmpty()) {\n return NaN;\n }\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n maxIndex() {\n checkNonEmpty(this);\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n if (this.get(i, j) > v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n min() {\n if (this.isEmpty()) {\n return NaN;\n }\n let v = this.get(0, 0);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n }\n }\n }\n return v;\n }\n\n minIndex() {\n checkNonEmpty(this);\n let v = this.get(0, 0);\n let idx = [0, 0];\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n if (this.get(i, j) < v) {\n v = this.get(i, j);\n idx[0] = i;\n idx[1] = j;\n }\n }\n }\n return idx;\n }\n\n maxRow(row) {\n checkRowIndex(this, row);\n if (this.isEmpty()) {\n return NaN;\n }\n let v = this.get(row, 0);\n for (let i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n maxRowIndex(row) {\n checkRowIndex(this, row);\n checkNonEmpty(this);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let i = 1; i < this.columns; i++) {\n if (this.get(row, i) > v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n minRow(row) {\n checkRowIndex(this, row);\n if (this.isEmpty()) {\n return NaN;\n }\n let v = this.get(row, 0);\n for (let i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n }\n }\n return v;\n }\n\n minRowIndex(row) {\n checkRowIndex(this, row);\n checkNonEmpty(this);\n let v = this.get(row, 0);\n let idx = [row, 0];\n for (let i = 1; i < this.columns; i++) {\n if (this.get(row, i) < v) {\n v = this.get(row, i);\n idx[1] = i;\n }\n }\n return idx;\n }\n\n maxColumn(column) {\n checkColumnIndex(this, column);\n if (this.isEmpty()) {\n return NaN;\n }\n let v = this.get(0, column);\n for (let i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n maxColumnIndex(column) {\n checkColumnIndex(this, column);\n checkNonEmpty(this);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let i = 1; i < this.rows; i++) {\n if (this.get(i, column) > v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n minColumn(column) {\n checkColumnIndex(this, column);\n if (this.isEmpty()) {\n return NaN;\n }\n let v = this.get(0, column);\n for (let i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n }\n }\n return v;\n }\n\n minColumnIndex(column) {\n checkColumnIndex(this, column);\n checkNonEmpty(this);\n let v = this.get(0, column);\n let idx = [0, column];\n for (let i = 1; i < this.rows; i++) {\n if (this.get(i, column) < v) {\n v = this.get(i, column);\n idx[0] = i;\n }\n }\n return idx;\n }\n\n diag() {\n let min = Math.min(this.rows, this.columns);\n let diag = [];\n for (let i = 0; i < min; i++) {\n diag.push(this.get(i, i));\n }\n return diag;\n }\n\n norm(type = 'frobenius') {\n let result = 0;\n if (type === 'max') {\n return this.max();\n } else if (type === 'frobenius') {\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n result = result + this.get(i, j) * this.get(i, j);\n }\n }\n return Math.sqrt(result);\n } else {\n throw new RangeError(`unknown norm type: ${type}`);\n }\n }\n\n cumulativeSum() {\n let sum = 0;\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n sum += this.get(i, j);\n this.set(i, j, sum);\n }\n }\n return this;\n }\n\n dot(vector2) {\n if (AbstractMatrix.isMatrix(vector2)) vector2 = vector2.to1DArray();\n let vector1 = this.to1DArray();\n if (vector1.length !== vector2.length) {\n throw new RangeError('vectors do not have the same size');\n }\n let dot = 0;\n for (let i = 0; i < vector1.length; i++) {\n dot += vector1[i] * vector2[i];\n }\n return dot;\n }\n\n mmul(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.columns;\n\n let result = new Matrix(m, p);\n\n let Bcolj = new Float64Array(n);\n for (let j = 0; j < p; j++) {\n for (let k = 0; k < n; k++) {\n Bcolj[k] = other.get(k, j);\n }\n\n for (let i = 0; i < m; i++) {\n let s = 0;\n for (let k = 0; k < n; k++) {\n s += this.get(i, k) * Bcolj[k];\n }\n\n result.set(i, j, s);\n }\n }\n return result;\n }\n\n strassen2x2(other) {\n other = Matrix.checkMatrix(other);\n let result = new Matrix(2, 2);\n const a11 = this.get(0, 0);\n const b11 = other.get(0, 0);\n const a12 = this.get(0, 1);\n const b12 = other.get(0, 1);\n const a21 = this.get(1, 0);\n const b21 = other.get(1, 0);\n const a22 = this.get(1, 1);\n const b22 = other.get(1, 1);\n\n // Compute intermediate values.\n const m1 = (a11 + a22) * (b11 + b22);\n const m2 = (a21 + a22) * b11;\n const m3 = a11 * (b12 - b22);\n const m4 = a22 * (b21 - b11);\n const m5 = (a11 + a12) * b22;\n const m6 = (a21 - a11) * (b11 + b12);\n const m7 = (a12 - a22) * (b21 + b22);\n\n // Combine intermediate values into the output.\n const c00 = m1 + m4 - m5 + m7;\n const c01 = m3 + m5;\n const c10 = m2 + m4;\n const c11 = m1 - m2 + m3 + m6;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n return result;\n }\n\n strassen3x3(other) {\n other = Matrix.checkMatrix(other);\n let result = new Matrix(3, 3);\n\n const a00 = this.get(0, 0);\n const a01 = this.get(0, 1);\n const a02 = this.get(0, 2);\n const a10 = this.get(1, 0);\n const a11 = this.get(1, 1);\n const a12 = this.get(1, 2);\n const a20 = this.get(2, 0);\n const a21 = this.get(2, 1);\n const a22 = this.get(2, 2);\n\n const b00 = other.get(0, 0);\n const b01 = other.get(0, 1);\n const b02 = other.get(0, 2);\n const b10 = other.get(1, 0);\n const b11 = other.get(1, 1);\n const b12 = other.get(1, 2);\n const b20 = other.get(2, 0);\n const b21 = other.get(2, 1);\n const b22 = other.get(2, 2);\n\n const m1 = (a00 + a01 + a02 - a10 - a11 - a21 - a22) * b11;\n const m2 = (a00 - a10) * (-b01 + b11);\n const m3 = a11 * (-b00 + b01 + b10 - b11 - b12 - b20 + b22);\n const m4 = (-a00 + a10 + a11) * (b00 - b01 + b11);\n const m5 = (a10 + a11) * (-b00 + b01);\n const m6 = a00 * b00;\n const m7 = (-a00 + a20 + a21) * (b00 - b02 + b12);\n const m8 = (-a00 + a20) * (b02 - b12);\n const m9 = (a20 + a21) * (-b00 + b02);\n const m10 = (a00 + a01 + a02 - a11 - a12 - a20 - a21) * b12;\n const m11 = a21 * (-b00 + b02 + b10 - b11 - b12 - b20 + b21);\n const m12 = (-a02 + a21 + a22) * (b11 + b20 - b21);\n const m13 = (a02 - a22) * (b11 - b21);\n const m14 = a02 * b20;\n const m15 = (a21 + a22) * (-b20 + b21);\n const m16 = (-a02 + a11 + a12) * (b12 + b20 - b22);\n const m17 = (a02 - a12) * (b12 - b22);\n const m18 = (a11 + a12) * (-b20 + b22);\n const m19 = a01 * b10;\n const m20 = a12 * b21;\n const m21 = a10 * b02;\n const m22 = a20 * b01;\n const m23 = a22 * b22;\n\n const c00 = m6 + m14 + m19;\n const c01 = m1 + m4 + m5 + m6 + m12 + m14 + m15;\n const c02 = m6 + m7 + m9 + m10 + m14 + m16 + m18;\n const c10 = m2 + m3 + m4 + m6 + m14 + m16 + m17;\n const c11 = m2 + m4 + m5 + m6 + m20;\n const c12 = m14 + m16 + m17 + m18 + m21;\n const c20 = m6 + m7 + m8 + m11 + m12 + m13 + m14;\n const c21 = m12 + m13 + m14 + m15 + m22;\n const c22 = m6 + m7 + m8 + m9 + m23;\n\n result.set(0, 0, c00);\n result.set(0, 1, c01);\n result.set(0, 2, c02);\n result.set(1, 0, c10);\n result.set(1, 1, c11);\n result.set(1, 2, c12);\n result.set(2, 0, c20);\n result.set(2, 1, c21);\n result.set(2, 2, c22);\n return result;\n }\n\n mmulStrassen(y) {\n y = Matrix.checkMatrix(y);\n let x = this.clone();\n let r1 = x.rows;\n let c1 = x.columns;\n let r2 = y.rows;\n let c2 = y.columns;\n if (c1 !== r2) {\n // eslint-disable-next-line no-console\n console.warn(\n `Multiplying ${r1} x ${c1} and ${r2} x ${c2} matrix: dimensions do not match.`,\n );\n }\n\n // Put a matrix into the top left of a matrix of zeros.\n // `rows` and `cols` are the dimensions of the output matrix.\n function embed(mat, rows, cols) {\n let r = mat.rows;\n let c = mat.columns;\n if (r === rows && c === cols) {\n return mat;\n } else {\n let resultat = AbstractMatrix.zeros(rows, cols);\n resultat = resultat.setSubMatrix(mat, 0, 0);\n return resultat;\n }\n }\n\n // Make sure both matrices are the same size.\n // This is exclusively for simplicity:\n // this algorithm can be implemented with matrices of different sizes.\n\n let r = Math.max(r1, r2);\n let c = Math.max(c1, c2);\n x = embed(x, r, c);\n y = embed(y, r, c);\n\n // Our recursive multiplication function.\n function blockMult(a, b, rows, cols) {\n // For small matrices, resort to naive multiplication.\n if (rows <= 512 || cols <= 512) {\n return a.mmul(b); // a is equivalent to this\n }\n\n // Apply dynamic padding.\n if (rows % 2 === 1 && cols % 2 === 1) {\n a = embed(a, rows + 1, cols + 1);\n b = embed(b, rows + 1, cols + 1);\n } else if (rows % 2 === 1) {\n a = embed(a, rows + 1, cols);\n b = embed(b, rows + 1, cols);\n } else if (cols % 2 === 1) {\n a = embed(a, rows, cols + 1);\n b = embed(b, rows, cols + 1);\n }\n\n let halfRows = parseInt(a.rows / 2, 10);\n let halfCols = parseInt(a.columns / 2, 10);\n // Subdivide input matrices.\n let a11 = a.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n let b11 = b.subMatrix(0, halfRows - 1, 0, halfCols - 1);\n\n let a12 = a.subMatrix(0, halfRows - 1, halfCols, a.columns - 1);\n let b12 = b.subMatrix(0, halfRows - 1, halfCols, b.columns - 1);\n\n let a21 = a.subMatrix(halfRows, a.rows - 1, 0, halfCols - 1);\n let b21 = b.subMatrix(halfRows, b.rows - 1, 0, halfCols - 1);\n\n let a22 = a.subMatrix(halfRows, a.rows - 1, halfCols, a.columns - 1);\n let b22 = b.subMatrix(halfRows, b.rows - 1, halfCols, b.columns - 1);\n\n // Compute intermediate values.\n let m1 = blockMult(\n AbstractMatrix.add(a11, a22),\n AbstractMatrix.add(b11, b22),\n halfRows,\n halfCols,\n );\n let m2 = blockMult(AbstractMatrix.add(a21, a22), b11, halfRows, halfCols);\n let m3 = blockMult(a11, AbstractMatrix.sub(b12, b22), halfRows, halfCols);\n let m4 = blockMult(a22, AbstractMatrix.sub(b21, b11), halfRows, halfCols);\n let m5 = blockMult(AbstractMatrix.add(a11, a12), b22, halfRows, halfCols);\n let m6 = blockMult(\n AbstractMatrix.sub(a21, a11),\n AbstractMatrix.add(b11, b12),\n halfRows,\n halfCols,\n );\n let m7 = blockMult(\n AbstractMatrix.sub(a12, a22),\n AbstractMatrix.add(b21, b22),\n halfRows,\n halfCols,\n );\n\n // Combine intermediate values into the output.\n let c11 = AbstractMatrix.add(m1, m4);\n c11.sub(m5);\n c11.add(m7);\n let c12 = AbstractMatrix.add(m3, m5);\n let c21 = AbstractMatrix.add(m2, m4);\n let c22 = AbstractMatrix.sub(m1, m2);\n c22.add(m3);\n c22.add(m6);\n\n // Crop output to the desired size (undo dynamic padding).\n let resultat = AbstractMatrix.zeros(2 * c11.rows, 2 * c11.columns);\n resultat = resultat.setSubMatrix(c11, 0, 0);\n resultat = resultat.setSubMatrix(c12, c11.rows, 0);\n resultat = resultat.setSubMatrix(c21, 0, c11.columns);\n resultat = resultat.setSubMatrix(c22, c11.rows, c11.columns);\n return resultat.subMatrix(0, rows - 1, 0, cols - 1);\n }\n return blockMult(x, y, r, c);\n }\n\n scaleRows(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.rows; i++) {\n const row = this.getRow(i);\n if (row.length > 0) {\n rescale(row, { min, max, output: row });\n }\n newMatrix.setRow(i, row);\n }\n return newMatrix;\n }\n\n scaleColumns(options = {}) {\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { min = 0, max = 1 } = options;\n if (!Number.isFinite(min)) throw new TypeError('min must be a number');\n if (!Number.isFinite(max)) throw new TypeError('max must be a number');\n if (min >= max) throw new RangeError('min must be smaller than max');\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let i = 0; i < this.columns; i++) {\n const column = this.getColumn(i);\n if (column.length) {\n rescale(column, {\n min: min,\n max: max,\n output: column,\n });\n }\n newMatrix.setColumn(i, column);\n }\n return newMatrix;\n }\n\n flipRows() {\n const middle = Math.ceil(this.columns / 2);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < middle; j++) {\n let first = this.get(i, j);\n let last = this.get(i, this.columns - 1 - j);\n this.set(i, j, last);\n this.set(i, this.columns - 1 - j, first);\n }\n }\n return this;\n }\n\n flipColumns() {\n const middle = Math.ceil(this.rows / 2);\n for (let j = 0; j < this.columns; j++) {\n for (let i = 0; i < middle; i++) {\n let first = this.get(i, j);\n let last = this.get(this.rows - 1 - i, j);\n this.set(i, j, last);\n this.set(this.rows - 1 - i, j, first);\n }\n }\n return this;\n }\n\n kroneckerProduct(other) {\n other = Matrix.checkMatrix(other);\n\n let m = this.rows;\n let n = this.columns;\n let p = other.rows;\n let q = other.columns;\n\n let result = new Matrix(m * p, n * q);\n for (let i = 0; i < m; i++) {\n for (let j = 0; j < n; j++) {\n for (let k = 0; k < p; k++) {\n for (let l = 0; l < q; l++) {\n result.set(p * i + k, q * j + l, this.get(i, j) * other.get(k, l));\n }\n }\n }\n }\n return result;\n }\n\n kroneckerSum(other) {\n other = Matrix.checkMatrix(other);\n if (!this.isSquare() || !other.isSquare()) {\n throw new Error('Kronecker Sum needs two Square Matrices');\n }\n let m = this.rows;\n let n = other.rows;\n let AxI = this.kroneckerProduct(Matrix.eye(n, n));\n let IxB = Matrix.eye(m, m).kroneckerProduct(other);\n return AxI.add(IxB);\n }\n\n transpose() {\n let result = new Matrix(this.columns, this.rows);\n for (let i = 0; i < this.rows; i++) {\n for (let j = 0; j < this.columns; j++) {\n result.set(j, i, this.get(i, j));\n }\n }\n return result;\n }\n\n sortRows(compareFunction = compareNumbers) {\n for (let i = 0; i < this.rows; i++) {\n this.setRow(i, this.getRow(i).sort(compareFunction));\n }\n return this;\n }\n\n sortColumns(compareFunction = compareNumbers) {\n for (let i = 0; i < this.columns; i++) {\n this.setColumn(i, this.getColumn(i).sort(compareFunction));\n }\n return this;\n }\n\n subMatrix(startRow, endRow, startColumn, endColumn) {\n checkRange(this, startRow, endRow, startColumn, endColumn);\n let newMatrix = new Matrix(\n endRow - startRow + 1,\n endColumn - startColumn + 1,\n );\n for (let i = startRow; i <= endRow; i++) {\n for (let j = startColumn; j <= endColumn; j++) {\n newMatrix.set(i - startRow, j - startColumn, this.get(i, j));\n }\n }\n return newMatrix;\n }\n\n subMatrixRow(indices, startColumn, endColumn) {\n if (startColumn === undefined) startColumn = 0;\n if (endColumn === undefined) endColumn = this.columns - 1;\n if (\n startColumn > endColumn ||\n startColumn < 0 ||\n startColumn >= this.columns ||\n endColumn < 0 ||\n endColumn >= this.columns\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(indices.length, endColumn - startColumn + 1);\n for (let i = 0; i < indices.length; i++) {\n for (let j = startColumn; j <= endColumn; j++) {\n if (indices[i] < 0 || indices[i] >= this.rows) {\n throw new RangeError(`Row index out of range: ${indices[i]}`);\n }\n newMatrix.set(i, j - startColumn, this.get(indices[i], j));\n }\n }\n return newMatrix;\n }\n\n subMatrixColumn(indices, startRow, endRow) {\n if (startRow === undefined) startRow = 0;\n if (endRow === undefined) endRow = this.rows - 1;\n if (\n startRow > endRow ||\n startRow < 0 ||\n startRow >= this.rows ||\n endRow < 0 ||\n endRow >= this.rows\n ) {\n throw new RangeError('Argument out of range');\n }\n\n let newMatrix = new Matrix(endRow - startRow + 1, indices.length);\n for (let i = 0; i < indices.length; i++) {\n for (let j = startRow; j <= endRow; j++) {\n if (indices[i] < 0 || indices[i] >= this.columns) {\n throw new RangeError(`Column index out of range: ${indices[i]}`);\n }\n newMatrix.set(j - startRow, i, this.get(j, indices[i]));\n }\n }\n return newMatrix;\n }\n\n setSubMatrix(matrix, startRow, startColumn) {\n matrix = Matrix.checkMatrix(matrix);\n if (matrix.isEmpty()) {\n return this;\n }\n let endRow = startRow + matrix.rows - 1;\n let endColumn = startColumn + matrix.columns - 1;\n checkRange(this, startRow, endRow, startColumn, endColumn);\n for (let i = 0; i < matrix.rows; i++) {\n for (let j = 0; j < matrix.columns; j++) {\n this.set(startRow + i, startColumn + j, matrix.get(i, j));\n }\n }\n return this;\n }\n\n selection(rowIndices, columnIndices) {\n let indices = checkIndices(this, rowIndices, columnIndices);\n let newMatrix = new Matrix(rowIndices.length, columnIndices.length);\n for (let i = 0; i < indices.row.length; i++) {\n let rowIndex = indices.row[i];\n for (let j = 0; j < indices.column.length; j++) {\n let columnIndex = indices.column[j];\n newMatrix.set(i, j, this.get(rowIndex, columnIndex));\n }\n }\n return newMatrix;\n }\n\n trace() {\n let min = Math.min(this.rows, this.columns);\n let trace = 0;\n for (let i = 0; i < min; i++) {\n trace += this.get(i, i);\n }\n return trace;\n }\n\n clone() {\n let newMatrix = new Matrix(this.rows, this.columns);\n for (let row = 0; row < this.rows; row++) {\n for (let column = 0; column < this.columns; column++) {\n newMatrix.set(row, column, this.get(row, column));\n }\n }\n return newMatrix;\n }\n\n sum(by) {\n switch (by) {\n case 'row':\n return sumByRow(this);\n case 'column':\n return sumByColumn(this);\n case undefined:\n return sumAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n product(by) {\n switch (by) {\n case 'row':\n return productByRow(this);\n case 'column':\n return productByColumn(this);\n case undefined:\n return productAll(this);\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n mean(by) {\n const sum = this.sum(by);\n switch (by) {\n case 'row': {\n for (let i = 0; i < this.rows; i++) {\n sum[i] /= this.columns;\n }\n return sum;\n }\n case 'column': {\n for (let i = 0; i < this.columns; i++) {\n sum[i] /= this.rows;\n }\n return sum;\n }\n case undefined:\n return sum / this.size;\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n variance(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { unbiased = true, mean = this.mean(by) } = options;\n if (typeof unbiased !== 'boolean') {\n throw new TypeError('unbiased must be a boolean');\n }\n switch (by) {\n case 'row': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByRow(this, unbiased, mean);\n }\n case 'column': {\n if (!Array.isArray(mean)) {\n throw new TypeError('mean must be an array');\n }\n return varianceByColumn(this, unbiased, mean);\n }\n case undefined: {\n if (typeof mean !== 'number') {\n throw new TypeError('mean must be a number');\n }\n return varianceAll(this, unbiased, mean);\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n standardDeviation(by, options) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n const variance = this.variance(by, options);\n if (by === undefined) {\n return Math.sqrt(variance);\n } else {\n for (let i = 0; i < variance.length; i++) {\n variance[i] = Math.sqrt(variance[i]);\n }\n return variance;\n }\n }\n\n center(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n const { center = this.mean(by) } = options;\n switch (by) {\n case 'row': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByRow(this, center);\n return this;\n }\n case 'column': {\n if (!Array.isArray(center)) {\n throw new TypeError('center must be an array');\n }\n centerByColumn(this, center);\n return this;\n }\n case undefined: {\n if (typeof center !== 'number') {\n throw new TypeError('center must be a number');\n }\n centerAll(this, center);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n scale(by, options = {}) {\n if (typeof by === 'object') {\n options = by;\n by = undefined;\n }\n if (typeof options !== 'object') {\n throw new TypeError('options must be an object');\n }\n let scale = options.scale;\n switch (by) {\n case 'row': {\n if (scale === undefined) {\n scale = getScaleByRow(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByRow(this, scale);\n return this;\n }\n case 'column': {\n if (scale === undefined) {\n scale = getScaleByColumn(this);\n } else if (!Array.isArray(scale)) {\n throw new TypeError('scale must be an array');\n }\n scaleByColumn(this, scale);\n return this;\n }\n case undefined: {\n if (scale === undefined) {\n scale = getScaleAll(this);\n } else if (typeof scale !== 'number') {\n throw new TypeError('scale must be a number');\n }\n scaleAll(this, scale);\n return this;\n }\n default:\n throw new Error(`invalid option: ${by}`);\n }\n }\n\n toString(options) {\n return inspectMatrixWithOptions(this, options);\n }\n}\n\nAbstractMatrix.prototype.klass = 'Matrix';\nif (typeof Symbol !== 'undefined') {\n AbstractMatrix.prototype[\n Symbol.for('nodejs.util.inspect.custom')\n ] = inspectMatrix;\n}\n\nfunction compareNumbers(a, b) {\n return a - b;\n}\n\n// Synonyms\nAbstractMatrix.random = AbstractMatrix.rand;\nAbstractMatrix.randomInt = AbstractMatrix.randInt;\nAbstractMatrix.diagonal = AbstractMatrix.diag;\nAbstractMatrix.prototype.diagonal = AbstractMatrix.prototype.diag;\nAbstractMatrix.identity = AbstractMatrix.eye;\nAbstractMatrix.prototype.negate = AbstractMatrix.prototype.neg;\nAbstractMatrix.prototype.tensorProduct =\n AbstractMatrix.prototype.kroneckerProduct;\n\nexport default class Matrix extends AbstractMatrix {\n constructor(nRows, nColumns) {\n super();\n if (Matrix.isMatrix(nRows)) {\n // eslint-disable-next-line no-constructor-return\n return nRows.clone();\n } else if (Number.isInteger(nRows) && nRows >= 0) {\n // Create an empty matrix\n this.data = [];\n if (Number.isInteger(nColumns) && nColumns >= 0) {\n for (let i = 0; i < nRows; i++) {\n this.data.push(new Float64Array(nColumns));\n }\n } else {\n throw new TypeError('nColumns must be a positive integer');\n }\n } else if (Array.isArray(nRows)) {\n // Copy the values from the 2D array\n const arrayData = nRows;\n nRows = arrayData.length;\n nColumns = nRows ? arrayData[0].length : 0;\n if (typeof nColumns !== 'number') {\n throw new TypeError(\n 'Data must be a 2D array with at least one element',\n );\n }\n this.data = [];\n for (let i = 0; i < nRows; i++) {\n if (arrayData[i].length !== nColumns) {\n throw new RangeError('Inconsistent array dimensions');\n }\n this.data.push(Float64Array.from(arrayData[i]));\n }\n } else {\n throw new TypeError(\n 'First argument must be a positive number or an array',\n );\n }\n this.rows = nRows;\n this.columns = nColumns;\n }\n\n set(rowIndex, columnIndex, value) {\n this.data[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.data[rowIndex][columnIndex];\n }\n\n removeRow(index) {\n checkRowIndex(this, index);\n this.data.splice(index, 1);\n this.rows -= 1;\n return this;\n }\n\n addRow(index, array) {\n if (array === undefined) {\n array = index;\n index = this.rows;\n }\n checkRowIndex(this, index, true);\n array = Float64Array.from(checkRowVector(this, array));\n this.data.splice(index, 0, array);\n this.rows += 1;\n return this;\n }\n\n removeColumn(index) {\n checkColumnIndex(this, index);\n for (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns - 1);\n for (let j = 0; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n for (let j = index + 1; j < this.columns; j++) {\n newRow[j - 1] = this.data[i][j];\n }\n this.data[i] = newRow;\n }\n this.columns -= 1;\n return this;\n }\n\n addColumn(index, array) {\n if (typeof array === 'undefined') {\n array = index;\n index = this.columns;\n }\n checkColumnIndex(this, index, true);\n array = checkColumnVector(this, array);\n for (let i = 0; i < this.rows; i++) {\n const newRow = new Float64Array(this.columns + 1);\n let j = 0;\n for (; j < index; j++) {\n newRow[j] = this.data[i][j];\n }\n newRow[j++] = array[i];\n for (; j < this.columns + 1; j++) {\n newRow[j] = this.data[i][j - 1];\n }\n this.data[i] = newRow;\n }\n this.columns += 1;\n return this;\n }\n}\n\ninstallMathOperations(AbstractMatrix, Matrix);\n","import { AbstractMatrix } from '../matrix';\n\nexport default class BaseView extends AbstractMatrix {\n constructor(matrix, rows, columns) {\n super();\n this.matrix = matrix;\n this.rows = rows;\n this.columns = columns;\n }\n}\n","import { checkColumnIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixColumnView extends BaseView {\n constructor(matrix, column) {\n checkColumnIndex(matrix, column);\n super(matrix, matrix.rows, 1);\n this.column = column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.column, value);\n return this;\n }\n\n get(rowIndex) {\n return this.matrix.get(rowIndex, this.column);\n }\n}\n","import { checkColumnIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixColumnSelectionView extends BaseView {\n constructor(matrix, columnIndices) {\n columnIndices = checkColumnIndices(matrix, columnIndices);\n super(matrix, matrix.rows, columnIndices.length);\n this.columnIndices = columnIndices;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.columnIndices[columnIndex], value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(rowIndex, this.columnIndices[columnIndex]);\n }\n}\n","import BaseView from './base';\n\nexport default class MatrixFlipColumnView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(rowIndex, this.columns - columnIndex - 1, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(rowIndex, this.columns - columnIndex - 1);\n }\n}\n","import BaseView from './base';\n\nexport default class MatrixFlipRowView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.rows, matrix.columns);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rows - rowIndex - 1, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rows - rowIndex - 1, columnIndex);\n }\n}\n","import { checkRowIndex } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixRowView extends BaseView {\n constructor(matrix, row) {\n checkRowIndex(matrix, row);\n super(matrix, 1, matrix.columns);\n this.row = row;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.row, columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.row, columnIndex);\n }\n}\n","import { checkRowIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixRowSelectionView extends BaseView {\n constructor(matrix, rowIndices) {\n rowIndices = checkRowIndices(matrix, rowIndices);\n super(matrix, rowIndices.length, matrix.columns);\n this.rowIndices = rowIndices;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(this.rowIndices[rowIndex], columnIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(this.rowIndices[rowIndex], columnIndex);\n }\n}\n","import { checkIndices } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixSelectionView extends BaseView {\n constructor(matrix, rowIndices, columnIndices) {\n let indices = checkIndices(matrix, rowIndices, columnIndices);\n super(matrix, indices.row.length, indices.column.length);\n this.rowIndices = indices.row;\n this.columnIndices = indices.column;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(\n this.rowIndices[rowIndex],\n this.columnIndices[columnIndex],\n value,\n );\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(\n this.rowIndices[rowIndex],\n this.columnIndices[columnIndex],\n );\n }\n}\n","import { checkRange } from '../util';\n\nimport BaseView from './base';\n\nexport default class MatrixSubView extends BaseView {\n constructor(matrix, startRow, endRow, startColumn, endColumn) {\n checkRange(matrix, startRow, endRow, startColumn, endColumn);\n super(matrix, endRow - startRow + 1, endColumn - startColumn + 1);\n this.startRow = startRow;\n this.startColumn = startColumn;\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(\n this.startRow + rowIndex,\n this.startColumn + columnIndex,\n value,\n );\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(\n this.startRow + rowIndex,\n this.startColumn + columnIndex,\n );\n }\n}\n","import BaseView from './base';\n\nexport default class MatrixTransposeView extends BaseView {\n constructor(matrix) {\n super(matrix, matrix.columns, matrix.rows);\n }\n\n set(rowIndex, columnIndex, value) {\n this.matrix.set(columnIndex, rowIndex, value);\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.matrix.get(columnIndex, rowIndex);\n }\n}\n","import { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix1D extends AbstractMatrix {\n constructor(data, options = {}) {\n const { rows = 1 } = options;\n\n if (data.length % rows !== 0) {\n throw new Error('the data length is not divisible by the number of rows');\n }\n super();\n this.rows = rows;\n this.columns = data.length / rows;\n this.data = data;\n }\n\n set(rowIndex, columnIndex, value) {\n let index = this._calculateIndex(rowIndex, columnIndex);\n this.data[index] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n let index = this._calculateIndex(rowIndex, columnIndex);\n return this.data[index];\n }\n\n _calculateIndex(row, column) {\n return row * this.columns + column;\n }\n}\n","import { AbstractMatrix } from '../matrix';\n\nexport default class WrapperMatrix2D extends AbstractMatrix {\n constructor(data) {\n super();\n this.data = data;\n this.rows = data.length;\n this.columns = data[0].length;\n }\n\n set(rowIndex, columnIndex, value) {\n this.data[rowIndex][columnIndex] = value;\n return this;\n }\n\n get(rowIndex, columnIndex) {\n return this.data[rowIndex][columnIndex];\n }\n}\n","import WrapperMatrix1D from './WrapperMatrix1D';\nimport WrapperMatrix2D from './WrapperMatrix2D';\n\nexport function wrap(array, options) {\n if (Array.isArray(array)) {\n if (array[0] && Array.isArray(array[0])) {\n return new WrapperMatrix2D(array);\n } else {\n return new WrapperMatrix1D(array, options);\n }\n } else {\n throw new Error('the argument is not an array');\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class LuDecomposition {\n constructor(matrix) {\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n\n let lu = matrix.clone();\n let rows = lu.rows;\n let columns = lu.columns;\n let pivotVector = new Float64Array(rows);\n let pivotSign = 1;\n let i, j, k, p, s, t, v;\n let LUcolj, kmax;\n\n for (i = 0; i < rows; i++) {\n pivotVector[i] = i;\n }\n\n LUcolj = new Float64Array(rows);\n\n for (j = 0; j < columns; j++) {\n for (i = 0; i < rows; i++) {\n LUcolj[i] = lu.get(i, j);\n }\n\n for (i = 0; i < rows; i++) {\n kmax = Math.min(i, j);\n s = 0;\n for (k = 0; k < kmax; k++) {\n s += lu.get(i, k) * LUcolj[k];\n }\n LUcolj[i] -= s;\n lu.set(i, j, LUcolj[i]);\n }\n\n p = j;\n for (i = j + 1; i < rows; i++) {\n if (Math.abs(LUcolj[i]) > Math.abs(LUcolj[p])) {\n p = i;\n }\n }\n\n if (p !== j) {\n for (k = 0; k < columns; k++) {\n t = lu.get(p, k);\n lu.set(p, k, lu.get(j, k));\n lu.set(j, k, t);\n }\n\n v = pivotVector[p];\n pivotVector[p] = pivotVector[j];\n pivotVector[j] = v;\n\n pivotSign = -pivotSign;\n }\n\n if (j < rows && lu.get(j, j) !== 0) {\n for (i = j + 1; i < rows; i++) {\n lu.set(i, j, lu.get(i, j) / lu.get(j, j));\n }\n }\n }\n\n this.LU = lu;\n this.pivotVector = pivotVector;\n this.pivotSign = pivotSign;\n }\n\n isSingular() {\n let data = this.LU;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n if (data.get(j, j) === 0) {\n return true;\n }\n }\n return false;\n }\n\n solve(value) {\n value = Matrix.checkMatrix(value);\n\n let lu = this.LU;\n let rows = lu.rows;\n\n if (rows !== value.rows) {\n throw new Error('Invalid matrix dimensions');\n }\n if (this.isSingular()) {\n throw new Error('LU matrix is singular');\n }\n\n let count = value.columns;\n let X = value.subMatrixRow(this.pivotVector, 0, count - 1);\n let columns = lu.columns;\n let i, j, k;\n\n for (k = 0; k < columns; k++) {\n for (i = k + 1; i < columns; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n for (k = columns - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / lu.get(k, k));\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * lu.get(i, k));\n }\n }\n }\n return X;\n }\n\n get determinant() {\n let data = this.LU;\n if (!data.isSquare()) {\n throw new Error('Matrix must be square');\n }\n let determinant = this.pivotSign;\n let col = data.columns;\n for (let j = 0; j < col; j++) {\n determinant *= data.get(j, j);\n }\n return determinant;\n }\n\n get lowerTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i > j) {\n X.set(i, j, data.get(i, j));\n } else if (i === j) {\n X.set(i, j, 1);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get upperTriangularMatrix() {\n let data = this.LU;\n let rows = data.rows;\n let columns = data.columns;\n let X = new Matrix(rows, columns);\n for (let i = 0; i < rows; i++) {\n for (let j = 0; j < columns; j++) {\n if (i <= j) {\n X.set(i, j, data.get(i, j));\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get pivotPermutationVector() {\n return Array.from(this.pivotVector);\n }\n}\n","export function hypotenuse(a, b) {\n let r = 0;\n if (Math.abs(a) > Math.abs(b)) {\n r = b / a;\n return Math.abs(a) * Math.sqrt(1 + r * r);\n }\n if (b !== 0) {\n r = a / b;\n return Math.abs(b) * Math.sqrt(1 + r * r);\n }\n return 0;\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class QrDecomposition {\n constructor(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let qr = value.clone();\n let m = value.rows;\n let n = value.columns;\n let rdiag = new Float64Array(n);\n let i, j, k, s;\n\n for (k = 0; k < n; k++) {\n let nrm = 0;\n for (i = k; i < m; i++) {\n nrm = hypotenuse(nrm, qr.get(i, k));\n }\n if (nrm !== 0) {\n if (qr.get(k, k) < 0) {\n nrm = -nrm;\n }\n for (i = k; i < m; i++) {\n qr.set(i, k, qr.get(i, k) / nrm);\n }\n qr.set(k, k, qr.get(k, k) + 1);\n for (j = k + 1; j < n; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr.get(i, k) * qr.get(i, j);\n }\n s = -s / qr.get(k, k);\n for (i = k; i < m; i++) {\n qr.set(i, j, qr.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n rdiag[k] = -nrm;\n }\n\n this.QR = qr;\n this.Rdiag = rdiag;\n }\n\n solve(value) {\n value = Matrix.checkMatrix(value);\n\n let qr = this.QR;\n let m = qr.rows;\n\n if (value.rows !== m) {\n throw new Error('Matrix row dimensions must agree');\n }\n if (!this.isFullRank()) {\n throw new Error('Matrix is rank deficient');\n }\n\n let count = value.columns;\n let X = value.clone();\n let n = qr.columns;\n let i, j, k, s;\n\n for (k = 0; k < n; k++) {\n for (j = 0; j < count; j++) {\n s = 0;\n for (i = k; i < m; i++) {\n s += qr.get(i, k) * X.get(i, j);\n }\n s = -s / qr.get(k, k);\n for (i = k; i < m; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n for (k = n - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n X.set(k, j, X.get(k, j) / this.Rdiag[k]);\n }\n for (i = 0; i < k; i++) {\n for (j = 0; j < count; j++) {\n X.set(i, j, X.get(i, j) - X.get(k, j) * qr.get(i, k));\n }\n }\n }\n\n return X.subMatrix(0, n - 1, 0, count - 1);\n }\n\n isFullRank() {\n let columns = this.QR.columns;\n for (let i = 0; i < columns; i++) {\n if (this.Rdiag[i] === 0) {\n return false;\n }\n }\n return true;\n }\n\n get upperTriangularMatrix() {\n let qr = this.QR;\n let n = qr.columns;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n if (i < j) {\n X.set(i, j, qr.get(i, j));\n } else if (i === j) {\n X.set(i, j, this.Rdiag[i]);\n } else {\n X.set(i, j, 0);\n }\n }\n }\n return X;\n }\n\n get orthogonalMatrix() {\n let qr = this.QR;\n let rows = qr.rows;\n let columns = qr.columns;\n let X = new Matrix(rows, columns);\n let i, j, k, s;\n\n for (k = columns - 1; k >= 0; k--) {\n for (i = 0; i < rows; i++) {\n X.set(i, k, 0);\n }\n X.set(k, k, 1);\n for (j = k; j < columns; j++) {\n if (qr.get(k, k) !== 0) {\n s = 0;\n for (i = k; i < rows; i++) {\n s += qr.get(i, k) * X.get(i, j);\n }\n\n s = -s / qr.get(k, k);\n\n for (i = k; i < rows; i++) {\n X.set(i, j, X.get(i, j) + s * qr.get(i, k));\n }\n }\n }\n }\n return X;\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class SingularValueDecomposition {\n constructor(value, options = {}) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n if (value.isEmpty()) {\n throw new Error('Matrix must be non-empty');\n }\n\n let m = value.rows;\n let n = value.columns;\n\n const {\n computeLeftSingularVectors = true,\n computeRightSingularVectors = true,\n autoTranspose = false,\n } = options;\n\n let wantu = Boolean(computeLeftSingularVectors);\n let wantv = Boolean(computeRightSingularVectors);\n\n let swapped = false;\n let a;\n if (m < n) {\n if (!autoTranspose) {\n a = value.clone();\n // eslint-disable-next-line no-console\n console.warn(\n 'Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose',\n );\n } else {\n a = value.transpose();\n m = a.rows;\n n = a.columns;\n swapped = true;\n let aux = wantu;\n wantu = wantv;\n wantv = aux;\n }\n } else {\n a = value.clone();\n }\n\n let nu = Math.min(m, n);\n let ni = Math.min(m + 1, n);\n let s = new Float64Array(ni);\n let U = new Matrix(m, nu);\n let V = new Matrix(n, n);\n\n let e = new Float64Array(n);\n let work = new Float64Array(m);\n\n let si = new Float64Array(ni);\n for (let i = 0; i < ni; i++) si[i] = i;\n\n let nct = Math.min(m - 1, n);\n let nrt = Math.max(0, Math.min(n - 2, m));\n let mrc = Math.max(nct, nrt);\n\n for (let k = 0; k < mrc; k++) {\n if (k < nct) {\n s[k] = 0;\n for (let i = k; i < m; i++) {\n s[k] = hypotenuse(s[k], a.get(i, k));\n }\n if (s[k] !== 0) {\n if (a.get(k, k) < 0) {\n s[k] = -s[k];\n }\n for (let i = k; i < m; i++) {\n a.set(i, k, a.get(i, k) / s[k]);\n }\n a.set(k, k, a.get(k, k) + 1);\n }\n s[k] = -s[k];\n }\n\n for (let j = k + 1; j < n; j++) {\n if (k < nct && s[k] !== 0) {\n let t = 0;\n for (let i = k; i < m; i++) {\n t += a.get(i, k) * a.get(i, j);\n }\n t = -t / a.get(k, k);\n for (let i = k; i < m; i++) {\n a.set(i, j, a.get(i, j) + t * a.get(i, k));\n }\n }\n e[j] = a.get(k, j);\n }\n\n if (wantu && k < nct) {\n for (let i = k; i < m; i++) {\n U.set(i, k, a.get(i, k));\n }\n }\n\n if (k < nrt) {\n e[k] = 0;\n for (let i = k + 1; i < n; i++) {\n e[k] = hypotenuse(e[k], e[i]);\n }\n if (e[k] !== 0) {\n if (e[k + 1] < 0) {\n e[k] = 0 - e[k];\n }\n for (let i = k + 1; i < n; i++) {\n e[i] /= e[k];\n }\n e[k + 1] += 1;\n }\n e[k] = -e[k];\n if (k + 1 < m && e[k] !== 0) {\n for (let i = k + 1; i < m; i++) {\n work[i] = 0;\n }\n for (let i = k + 1; i < m; i++) {\n for (let j = k + 1; j < n; j++) {\n work[i] += e[j] * a.get(i, j);\n }\n }\n for (let j = k + 1; j < n; j++) {\n let t = -e[j] / e[k + 1];\n for (let i = k + 1; i < m; i++) {\n a.set(i, j, a.get(i, j) + t * work[i]);\n }\n }\n }\n if (wantv) {\n for (let i = k + 1; i < n; i++) {\n V.set(i, k, e[i]);\n }\n }\n }\n }\n\n let p = Math.min(n, m + 1);\n if (nct < n) {\n s[nct] = a.get(nct, nct);\n }\n if (m < p) {\n s[p - 1] = 0;\n }\n if (nrt + 1 < p) {\n e[nrt] = a.get(nrt, p - 1);\n }\n e[p - 1] = 0;\n\n if (wantu) {\n for (let j = nct; j < nu; j++) {\n for (let i = 0; i < m; i++) {\n U.set(i, j, 0);\n }\n U.set(j, j, 1);\n }\n for (let k = nct - 1; k >= 0; k--) {\n if (s[k] !== 0) {\n for (let j = k + 1; j < nu; j++) {\n let t = 0;\n for (let i = k; i < m; i++) {\n t += U.get(i, k) * U.get(i, j);\n }\n t = -t / U.get(k, k);\n for (let i = k; i < m; i++) {\n U.set(i, j, U.get(i, j) + t * U.get(i, k));\n }\n }\n for (let i = k; i < m; i++) {\n U.set(i, k, -U.get(i, k));\n }\n U.set(k, k, 1 + U.get(k, k));\n for (let i = 0; i < k - 1; i++) {\n U.set(i, k, 0);\n }\n } else {\n for (let i = 0; i < m; i++) {\n U.set(i, k, 0);\n }\n U.set(k, k, 1);\n }\n }\n }\n\n if (wantv) {\n for (let k = n - 1; k >= 0; k--) {\n if (k < nrt && e[k] !== 0) {\n for (let j = k + 1; j < n; j++) {\n let t = 0;\n for (let i = k + 1; i < n; i++) {\n t += V.get(i, k) * V.get(i, j);\n }\n t = -t / V.get(k + 1, k);\n for (let i = k + 1; i < n; i++) {\n V.set(i, j, V.get(i, j) + t * V.get(i, k));\n }\n }\n }\n for (let i = 0; i < n; i++) {\n V.set(i, k, 0);\n }\n V.set(k, k, 1);\n }\n }\n\n let pp = p - 1;\n let iter = 0;\n let eps = Number.EPSILON;\n while (p > 0) {\n let k, kase;\n for (k = p - 2; k >= -1; k--) {\n if (k === -1) {\n break;\n }\n const alpha =\n Number.MIN_VALUE + eps * Math.abs(s[k] + Math.abs(s[k + 1]));\n if (Math.abs(e[k]) <= alpha || Number.isNaN(e[k])) {\n e[k] = 0;\n break;\n }\n }\n if (k === p - 2) {\n kase = 4;\n } else {\n let ks;\n for (ks = p - 1; ks >= k; ks--) {\n if (ks === k) {\n break;\n }\n let t =\n (ks !== p ? Math.abs(e[ks]) : 0) +\n (ks !== k + 1 ? Math.abs(e[ks - 1]) : 0);\n if (Math.abs(s[ks]) <= eps * t) {\n s[ks] = 0;\n break;\n }\n }\n if (ks === k) {\n kase = 3;\n } else if (ks === p - 1) {\n kase = 1;\n } else {\n kase = 2;\n k = ks;\n }\n }\n\n k++;\n\n switch (kase) {\n case 1: {\n let f = e[p - 2];\n e[p - 2] = 0;\n for (let j = p - 2; j >= k; j--) {\n let t = hypotenuse(s[j], f);\n let cs = s[j] / t;\n let sn = f / t;\n s[j] = t;\n if (j !== k) {\n f = -sn * e[j - 1];\n e[j - 1] = cs * e[j - 1];\n }\n if (wantv) {\n for (let i = 0; i < n; i++) {\n t = cs * V.get(i, j) + sn * V.get(i, p - 1);\n V.set(i, p - 1, -sn * V.get(i, j) + cs * V.get(i, p - 1));\n V.set(i, j, t);\n }\n }\n }\n break;\n }\n case 2: {\n let f = e[k - 1];\n e[k - 1] = 0;\n for (let j = k; j < p; j++) {\n let t = hypotenuse(s[j], f);\n let cs = s[j] / t;\n let sn = f / t;\n s[j] = t;\n f = -sn * e[j];\n e[j] = cs * e[j];\n if (wantu) {\n for (let i = 0; i < m; i++) {\n t = cs * U.get(i, j) + sn * U.get(i, k - 1);\n U.set(i, k - 1, -sn * U.get(i, j) + cs * U.get(i, k - 1));\n U.set(i, j, t);\n }\n }\n }\n break;\n }\n case 3: {\n const scale = Math.max(\n Math.abs(s[p - 1]),\n Math.abs(s[p - 2]),\n Math.abs(e[p - 2]),\n Math.abs(s[k]),\n Math.abs(e[k]),\n );\n const sp = s[p - 1] / scale;\n const spm1 = s[p - 2] / scale;\n const epm1 = e[p - 2] / scale;\n const sk = s[k] / scale;\n const ek = e[k] / scale;\n const b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2;\n const c = sp * epm1 * (sp * epm1);\n let shift = 0;\n if (b !== 0 || c !== 0) {\n if (b < 0) {\n shift = 0 - Math.sqrt(b * b + c);\n } else {\n shift = Math.sqrt(b * b + c);\n }\n shift = c / (b + shift);\n }\n let f = (sk + sp) * (sk - sp) + shift;\n let g = sk * ek;\n for (let j = k; j < p - 1; j++) {\n let t = hypotenuse(f, g);\n if (t === 0) t = Number.MIN_VALUE;\n let cs = f / t;\n let sn = g / t;\n if (j !== k) {\n e[j - 1] = t;\n }\n f = cs * s[j] + sn * e[j];\n e[j] = cs * e[j] - sn * s[j];\n g = sn * s[j + 1];\n s[j + 1] = cs * s[j + 1];\n if (wantv) {\n for (let i = 0; i < n; i++) {\n t = cs * V.get(i, j) + sn * V.get(i, j + 1);\n V.set(i, j + 1, -sn * V.get(i, j) + cs * V.get(i, j + 1));\n V.set(i, j, t);\n }\n }\n t = hypotenuse(f, g);\n if (t === 0) t = Number.MIN_VALUE;\n cs = f / t;\n sn = g / t;\n s[j] = t;\n f = cs * e[j] + sn * s[j + 1];\n s[j + 1] = -sn * e[j] + cs * s[j + 1];\n g = sn * e[j + 1];\n e[j + 1] = cs * e[j + 1];\n if (wantu && j < m - 1) {\n for (let i = 0; i < m; i++) {\n t = cs * U.get(i, j) + sn * U.get(i, j + 1);\n U.set(i, j + 1, -sn * U.get(i, j) + cs * U.get(i, j + 1));\n U.set(i, j, t);\n }\n }\n }\n e[p - 2] = f;\n iter = iter + 1;\n break;\n }\n case 4: {\n if (s[k] <= 0) {\n s[k] = s[k] < 0 ? -s[k] : 0;\n if (wantv) {\n for (let i = 0; i <= pp; i++) {\n V.set(i, k, -V.get(i, k));\n }\n }\n }\n while (k < pp) {\n if (s[k] >= s[k + 1]) {\n break;\n }\n let t = s[k];\n s[k] = s[k + 1];\n s[k + 1] = t;\n if (wantv && k < n - 1) {\n for (let i = 0; i < n; i++) {\n t = V.get(i, k + 1);\n V.set(i, k + 1, V.get(i, k));\n V.set(i, k, t);\n }\n }\n if (wantu && k < m - 1) {\n for (let i = 0; i < m; i++) {\n t = U.get(i, k + 1);\n U.set(i, k + 1, U.get(i, k));\n U.set(i, k, t);\n }\n }\n k++;\n }\n iter = 0;\n p--;\n break;\n }\n // no default\n }\n }\n\n if (swapped) {\n let tmp = V;\n V = U;\n U = tmp;\n }\n\n this.m = m;\n this.n = n;\n this.s = s;\n this.U = U;\n this.V = V;\n }\n\n solve(value) {\n let Y = value;\n let e = this.threshold;\n let scols = this.s.length;\n let Ls = Matrix.zeros(scols, scols);\n\n for (let i = 0; i < scols; i++) {\n if (Math.abs(this.s[i]) <= e) {\n Ls.set(i, i, 0);\n } else {\n Ls.set(i, i, 1 / this.s[i]);\n }\n }\n\n let U = this.U;\n let V = this.rightSingularVectors;\n\n let VL = V.mmul(Ls);\n let vrows = V.rows;\n let urows = U.rows;\n let VLU = Matrix.zeros(vrows, urows);\n\n for (let i = 0; i < vrows; i++) {\n for (let j = 0; j < urows; j++) {\n let sum = 0;\n for (let k = 0; k < scols; k++) {\n sum += VL.get(i, k) * U.get(j, k);\n }\n VLU.set(i, j, sum);\n }\n }\n\n return VLU.mmul(Y);\n }\n\n solveForDiagonal(value) {\n return this.solve(Matrix.diag(value));\n }\n\n inverse() {\n let V = this.V;\n let e = this.threshold;\n let vrows = V.rows;\n let vcols = V.columns;\n let X = new Matrix(vrows, this.s.length);\n\n for (let i = 0; i < vrows; i++) {\n for (let j = 0; j < vcols; j++) {\n if (Math.abs(this.s[j]) > e) {\n X.set(i, j, V.get(i, j) / this.s[j]);\n }\n }\n }\n\n let U = this.U;\n\n let urows = U.rows;\n let ucols = U.columns;\n let Y = new Matrix(vrows, urows);\n\n for (let i = 0; i < vrows; i++) {\n for (let j = 0; j < urows; j++) {\n let sum = 0;\n for (let k = 0; k < ucols; k++) {\n sum += X.get(i, k) * U.get(j, k);\n }\n Y.set(i, j, sum);\n }\n }\n\n return Y;\n }\n\n get condition() {\n return this.s[0] / this.s[Math.min(this.m, this.n) - 1];\n }\n\n get norm2() {\n return this.s[0];\n }\n\n get rank() {\n let tol = Math.max(this.m, this.n) * this.s[0] * Number.EPSILON;\n let r = 0;\n let s = this.s;\n for (let i = 0, ii = s.length; i < ii; i++) {\n if (s[i] > tol) {\n r++;\n }\n }\n return r;\n }\n\n get diagonal() {\n return Array.from(this.s);\n }\n\n get threshold() {\n return (Number.EPSILON / 2) * Math.max(this.m, this.n) * this.s[0];\n }\n\n get leftSingularVectors() {\n return this.U;\n }\n\n get rightSingularVectors() {\n return this.V;\n }\n\n get diagonalMatrix() {\n return Matrix.diag(this.s);\n }\n}\n","import LuDecomposition from './dc/lu';\nimport QrDecomposition from './dc/qr';\nimport SingularValueDecomposition from './dc/svd';\nimport Matrix from './matrix';\nimport WrapperMatrix2D from './wrap/WrapperMatrix2D';\n\nexport function inverse(matrix, useSVD = false) {\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n if (useSVD) {\n return new SingularValueDecomposition(matrix).inverse();\n } else {\n return solve(matrix, Matrix.eye(matrix.rows));\n }\n}\n\nexport function solve(leftHandSide, rightHandSide, useSVD = false) {\n leftHandSide = WrapperMatrix2D.checkMatrix(leftHandSide);\n rightHandSide = WrapperMatrix2D.checkMatrix(rightHandSide);\n if (useSVD) {\n return new SingularValueDecomposition(leftHandSide).solve(rightHandSide);\n } else {\n return leftHandSide.isSquare()\n ? new LuDecomposition(leftHandSide).solve(rightHandSide)\n : new QrDecomposition(leftHandSide).solve(rightHandSide);\n }\n}\n","import LuDecomposition from './dc/lu';\nimport Matrix from './matrix';\nimport MatrixSelectionView from './views/selection';\n\nexport function determinant(matrix) {\n matrix = Matrix.checkMatrix(matrix);\n if (matrix.isSquare()) {\n if (matrix.columns === 0) {\n return 1;\n }\n\n let a, b, c, d;\n if (matrix.columns === 2) {\n // 2 x 2 matrix\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(1, 0);\n d = matrix.get(1, 1);\n\n return a * d - b * c;\n } else if (matrix.columns === 3) {\n // 3 x 3 matrix\n let subMatrix0, subMatrix1, subMatrix2;\n subMatrix0 = new MatrixSelectionView(matrix, [1, 2], [1, 2]);\n subMatrix1 = new MatrixSelectionView(matrix, [1, 2], [0, 2]);\n subMatrix2 = new MatrixSelectionView(matrix, [1, 2], [0, 1]);\n a = matrix.get(0, 0);\n b = matrix.get(0, 1);\n c = matrix.get(0, 2);\n\n return (\n a * determinant(subMatrix0) -\n b * determinant(subMatrix1) +\n c * determinant(subMatrix2)\n );\n } else {\n // general purpose determinant using the LU decomposition\n return new LuDecomposition(matrix).determinant;\n }\n } else {\n throw Error('determinant can only be calculated for a square matrix');\n }\n}\n","import SingularValueDecomposition from './dc/svd';\nimport Matrix from './matrix';\n\nfunction xrange(n, exception) {\n let range = [];\n for (let i = 0; i < n; i++) {\n if (i !== exception) {\n range.push(i);\n }\n }\n return range;\n}\n\nfunction dependenciesOneRow(\n error,\n matrix,\n index,\n thresholdValue = 10e-10,\n thresholdError = 10e-10,\n) {\n if (error > thresholdError) {\n return new Array(matrix.rows + 1).fill(0);\n } else {\n let returnArray = matrix.addRow(index, [0]);\n for (let i = 0; i < returnArray.rows; i++) {\n if (Math.abs(returnArray.get(i, 0)) < thresholdValue) {\n returnArray.set(i, 0, 0);\n }\n }\n return returnArray.to1DArray();\n }\n}\n\nexport function linearDependencies(matrix, options = {}) {\n const { thresholdValue = 10e-10, thresholdError = 10e-10 } = options;\n matrix = Matrix.checkMatrix(matrix);\n\n let n = matrix.rows;\n let results = new Matrix(n, n);\n\n for (let i = 0; i < n; i++) {\n let b = Matrix.columnVector(matrix.getRow(i));\n let Abis = matrix.subMatrixRow(xrange(n, i)).transpose();\n let svd = new SingularValueDecomposition(Abis);\n let x = svd.solve(b);\n let error = Matrix.sub(b, Abis.mmul(x)).abs().max();\n results.setRow(\n i,\n dependenciesOneRow(error, x, i, thresholdValue, thresholdError),\n );\n }\n return results;\n}\n","import SVD from './dc/svd';\nimport Matrix from './matrix';\n\nexport function pseudoInverse(matrix, threshold = Number.EPSILON) {\n matrix = Matrix.checkMatrix(matrix);\n if (matrix.isEmpty()) {\n // with a zero dimension, the pseudo-inverse is the transpose, since all 0xn and nx0 matrices are singular\n // (0xn)*(nx0)*(0xn) = 0xn\n // (nx0)*(0xn)*(nx0) = nx0\n return matrix.transpose();\n }\n let svdSolution = new SVD(matrix, { autoTranspose: true });\n\n let U = svdSolution.leftSingularVectors;\n let V = svdSolution.rightSingularVectors;\n let s = svdSolution.diagonal;\n\n for (let i = 0; i < s.length; i++) {\n if (Math.abs(s[i]) > threshold) {\n s[i] = 1.0 / s[i];\n } else {\n s[i] = 0.0;\n }\n }\n\n return V.mmul(Matrix.diag(s).mmul(U.transpose()));\n}\n","import Matrix from './matrix';\n\nexport function covariance(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = new Matrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = new Matrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n const { center = true } = options;\n if (center) {\n xMatrix = xMatrix.center('column');\n if (!yIsSame) {\n yMatrix = yMatrix.center('column');\n }\n }\n const cov = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < cov.rows; i++) {\n for (let j = 0; j < cov.columns; j++) {\n cov.set(i, j, cov.get(i, j) * (1 / (xMatrix.rows - 1)));\n }\n }\n return cov;\n}\n","import Matrix from './matrix';\n\nexport function correlation(xMatrix, yMatrix = xMatrix, options = {}) {\n xMatrix = new Matrix(xMatrix);\n let yIsSame = false;\n if (\n typeof yMatrix === 'object' &&\n !Matrix.isMatrix(yMatrix) &&\n !Array.isArray(yMatrix)\n ) {\n options = yMatrix;\n yMatrix = xMatrix;\n yIsSame = true;\n } else {\n yMatrix = new Matrix(yMatrix);\n }\n if (xMatrix.rows !== yMatrix.rows) {\n throw new TypeError('Both matrices must have the same number of rows');\n }\n\n const { center = true, scale = true } = options;\n if (center) {\n xMatrix.center('column');\n if (!yIsSame) {\n yMatrix.center('column');\n }\n }\n if (scale) {\n xMatrix.scale('column');\n if (!yIsSame) {\n yMatrix.scale('column');\n }\n }\n\n const sdx = xMatrix.standardDeviation('column', { unbiased: true });\n const sdy = yIsSame\n ? sdx\n : yMatrix.standardDeviation('column', { unbiased: true });\n\n const corr = xMatrix.transpose().mmul(yMatrix);\n for (let i = 0; i < corr.rows; i++) {\n for (let j = 0; j < corr.columns; j++) {\n corr.set(\n i,\n j,\n corr.get(i, j) * (1 / (sdx[i] * sdy[j])) * (1 / (xMatrix.rows - 1)),\n );\n }\n }\n return corr;\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nimport { hypotenuse } from './util';\n\nexport default class EigenvalueDecomposition {\n constructor(matrix, options = {}) {\n const { assumeSymmetric = false } = options;\n\n matrix = WrapperMatrix2D.checkMatrix(matrix);\n if (!matrix.isSquare()) {\n throw new Error('Matrix is not a square matrix');\n }\n\n if (matrix.isEmpty()) {\n throw new Error('Matrix must be non-empty');\n }\n\n let n = matrix.columns;\n let V = new Matrix(n, n);\n let d = new Float64Array(n);\n let e = new Float64Array(n);\n let value = matrix;\n let i, j;\n\n let isSymmetric = false;\n if (assumeSymmetric) {\n isSymmetric = true;\n } else {\n isSymmetric = matrix.isSymmetric();\n }\n\n if (isSymmetric) {\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V.set(i, j, value.get(i, j));\n }\n }\n tred2(n, e, d, V);\n tql2(n, e, d, V);\n } else {\n let H = new Matrix(n, n);\n let ort = new Float64Array(n);\n for (j = 0; j < n; j++) {\n for (i = 0; i < n; i++) {\n H.set(i, j, value.get(i, j));\n }\n }\n orthes(n, H, ort, V);\n hqr2(n, e, d, V, H);\n }\n\n this.n = n;\n this.e = e;\n this.d = d;\n this.V = V;\n }\n\n get realEigenvalues() {\n return Array.from(this.d);\n }\n\n get imaginaryEigenvalues() {\n return Array.from(this.e);\n }\n\n get eigenvectorMatrix() {\n return this.V;\n }\n\n get diagonalMatrix() {\n let n = this.n;\n let e = this.e;\n let d = this.d;\n let X = new Matrix(n, n);\n let i, j;\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n X.set(i, j, 0);\n }\n X.set(i, i, d[i]);\n if (e[i] > 0) {\n X.set(i, i + 1, e[i]);\n } else if (e[i] < 0) {\n X.set(i, i - 1, e[i]);\n }\n }\n return X;\n }\n}\n\nfunction tred2(n, e, d, V) {\n let f, g, h, i, j, k, hh, scale;\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(n - 1, j);\n }\n\n for (i = n - 1; i > 0; i--) {\n scale = 0;\n h = 0;\n for (k = 0; k < i; k++) {\n scale = scale + Math.abs(d[k]);\n }\n\n if (scale === 0) {\n e[i] = d[i - 1];\n for (j = 0; j < i; j++) {\n d[j] = V.get(i - 1, j);\n V.set(i, j, 0);\n V.set(j, i, 0);\n }\n } else {\n for (k = 0; k < i; k++) {\n d[k] /= scale;\n h += d[k] * d[k];\n }\n\n f = d[i - 1];\n g = Math.sqrt(h);\n if (f > 0) {\n g = -g;\n }\n\n e[i] = scale * g;\n h = h - f * g;\n d[i - 1] = f - g;\n for (j = 0; j < i; j++) {\n e[j] = 0;\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n V.set(j, i, f);\n g = e[j] + V.get(j, j) * f;\n for (k = j + 1; k <= i - 1; k++) {\n g += V.get(k, j) * d[k];\n e[k] += V.get(k, j) * f;\n }\n e[j] = g;\n }\n\n f = 0;\n for (j = 0; j < i; j++) {\n e[j] /= h;\n f += e[j] * d[j];\n }\n\n hh = f / (h + h);\n for (j = 0; j < i; j++) {\n e[j] -= hh * d[j];\n }\n\n for (j = 0; j < i; j++) {\n f = d[j];\n g = e[j];\n for (k = j; k <= i - 1; k++) {\n V.set(k, j, V.get(k, j) - (f * e[k] + g * d[k]));\n }\n d[j] = V.get(i - 1, j);\n V.set(i, j, 0);\n }\n }\n d[i] = h;\n }\n\n for (i = 0; i < n - 1; i++) {\n V.set(n - 1, i, V.get(i, i));\n V.set(i, i, 1);\n h = d[i + 1];\n if (h !== 0) {\n for (k = 0; k <= i; k++) {\n d[k] = V.get(k, i + 1) / h;\n }\n\n for (j = 0; j <= i; j++) {\n g = 0;\n for (k = 0; k <= i; k++) {\n g += V.get(k, i + 1) * V.get(k, j);\n }\n for (k = 0; k <= i; k++) {\n V.set(k, j, V.get(k, j) - g * d[k]);\n }\n }\n }\n\n for (k = 0; k <= i; k++) {\n V.set(k, i + 1, 0);\n }\n }\n\n for (j = 0; j < n; j++) {\n d[j] = V.get(n - 1, j);\n V.set(n - 1, j, 0);\n }\n\n V.set(n - 1, n - 1, 1);\n e[0] = 0;\n}\n\nfunction tql2(n, e, d, V) {\n let g, h, i, j, k, l, m, p, r, dl1, c, c2, c3, el1, s, s2, iter;\n\n for (i = 1; i < n; i++) {\n e[i - 1] = e[i];\n }\n\n e[n - 1] = 0;\n\n let f = 0;\n let tst1 = 0;\n let eps = Number.EPSILON;\n\n for (l = 0; l < n; l++) {\n tst1 = Math.max(tst1, Math.abs(d[l]) + Math.abs(e[l]));\n m = l;\n while (m < n) {\n if (Math.abs(e[m]) <= eps * tst1) {\n break;\n }\n m++;\n }\n\n if (m > l) {\n iter = 0;\n do {\n iter = iter + 1;\n\n g = d[l];\n p = (d[l + 1] - g) / (2 * e[l]);\n r = hypotenuse(p, 1);\n if (p < 0) {\n r = -r;\n }\n\n d[l] = e[l] / (p + r);\n d[l + 1] = e[l] * (p + r);\n dl1 = d[l + 1];\n h = g - d[l];\n for (i = l + 2; i < n; i++) {\n d[i] -= h;\n }\n\n f = f + h;\n\n p = d[m];\n c = 1;\n c2 = c;\n c3 = c;\n el1 = e[l + 1];\n s = 0;\n s2 = 0;\n for (i = m - 1; i >= l; i--) {\n c3 = c2;\n c2 = c;\n s2 = s;\n g = c * e[i];\n h = c * p;\n r = hypotenuse(p, e[i]);\n e[i + 1] = s * r;\n s = e[i] / r;\n c = p / r;\n p = c * d[i] - s * g;\n d[i + 1] = h + s * (c * g + s * d[i]);\n\n for (k = 0; k < n; k++) {\n h = V.get(k, i + 1);\n V.set(k, i + 1, s * V.get(k, i) + c * h);\n V.set(k, i, c * V.get(k, i) - s * h);\n }\n }\n\n p = (-s * s2 * c3 * el1 * e[l]) / dl1;\n e[l] = s * p;\n d[l] = c * p;\n } while (Math.abs(e[l]) > eps * tst1);\n }\n d[l] = d[l] + f;\n e[l] = 0;\n }\n\n for (i = 0; i < n - 1; i++) {\n k = i;\n p = d[i];\n for (j = i + 1; j < n; j++) {\n if (d[j] < p) {\n k = j;\n p = d[j];\n }\n }\n\n if (k !== i) {\n d[k] = d[i];\n d[i] = p;\n for (j = 0; j < n; j++) {\n p = V.get(j, i);\n V.set(j, i, V.get(j, k));\n V.set(j, k, p);\n }\n }\n }\n}\n\nfunction orthes(n, H, ort, V) {\n let low = 0;\n let high = n - 1;\n let f, g, h, i, j, m;\n let scale;\n\n for (m = low + 1; m <= high - 1; m++) {\n scale = 0;\n for (i = m; i <= high; i++) {\n scale = scale + Math.abs(H.get(i, m - 1));\n }\n\n if (scale !== 0) {\n h = 0;\n for (i = high; i >= m; i--) {\n ort[i] = H.get(i, m - 1) / scale;\n h += ort[i] * ort[i];\n }\n\n g = Math.sqrt(h);\n if (ort[m] > 0) {\n g = -g;\n }\n\n h = h - ort[m] * g;\n ort[m] = ort[m] - g;\n\n for (j = m; j < n; j++) {\n f = 0;\n for (i = high; i >= m; i--) {\n f += ort[i] * H.get(i, j);\n }\n\n f = f / h;\n for (i = m; i <= high; i++) {\n H.set(i, j, H.get(i, j) - f * ort[i]);\n }\n }\n\n for (i = 0; i <= high; i++) {\n f = 0;\n for (j = high; j >= m; j--) {\n f += ort[j] * H.get(i, j);\n }\n\n f = f / h;\n for (j = m; j <= high; j++) {\n H.set(i, j, H.get(i, j) - f * ort[j]);\n }\n }\n\n ort[m] = scale * ort[m];\n H.set(m, m - 1, scale * g);\n }\n }\n\n for (i = 0; i < n; i++) {\n for (j = 0; j < n; j++) {\n V.set(i, j, i === j ? 1 : 0);\n }\n }\n\n for (m = high - 1; m >= low + 1; m--) {\n if (H.get(m, m - 1) !== 0) {\n for (i = m + 1; i <= high; i++) {\n ort[i] = H.get(i, m - 1);\n }\n\n for (j = m; j <= high; j++) {\n g = 0;\n for (i = m; i <= high; i++) {\n g += ort[i] * V.get(i, j);\n }\n\n g = g / ort[m] / H.get(m, m - 1);\n for (i = m; i <= high; i++) {\n V.set(i, j, V.get(i, j) + g * ort[i]);\n }\n }\n }\n }\n}\n\nfunction hqr2(nn, e, d, V, H) {\n let n = nn - 1;\n let low = 0;\n let high = nn - 1;\n let eps = Number.EPSILON;\n let exshift = 0;\n let norm = 0;\n let p = 0;\n let q = 0;\n let r = 0;\n let s = 0;\n let z = 0;\n let iter = 0;\n let i, j, k, l, m, t, w, x, y;\n let ra, sa, vr, vi;\n let notlast, cdivres;\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n d[i] = H.get(i, i);\n e[i] = 0;\n }\n\n for (j = Math.max(i - 1, 0); j < nn; j++) {\n norm = norm + Math.abs(H.get(i, j));\n }\n }\n\n while (n >= low) {\n l = n;\n while (l > low) {\n s = Math.abs(H.get(l - 1, l - 1)) + Math.abs(H.get(l, l));\n if (s === 0) {\n s = norm;\n }\n if (Math.abs(H.get(l, l - 1)) < eps * s) {\n break;\n }\n l--;\n }\n\n if (l === n) {\n H.set(n, n, H.get(n, n) + exshift);\n d[n] = H.get(n, n);\n e[n] = 0;\n n--;\n iter = 0;\n } else if (l === n - 1) {\n w = H.get(n, n - 1) * H.get(n - 1, n);\n p = (H.get(n - 1, n - 1) - H.get(n, n)) / 2;\n q = p * p + w;\n z = Math.sqrt(Math.abs(q));\n H.set(n, n, H.get(n, n) + exshift);\n H.set(n - 1, n - 1, H.get(n - 1, n - 1) + exshift);\n x = H.get(n, n);\n\n if (q >= 0) {\n z = p >= 0 ? p + z : p - z;\n d[n - 1] = x + z;\n d[n] = d[n - 1];\n if (z !== 0) {\n d[n] = x - w / z;\n }\n e[n - 1] = 0;\n e[n] = 0;\n x = H.get(n, n - 1);\n s = Math.abs(x) + Math.abs(z);\n p = x / s;\n q = z / s;\n r = Math.sqrt(p * p + q * q);\n p = p / r;\n q = q / r;\n\n for (j = n - 1; j < nn; j++) {\n z = H.get(n - 1, j);\n H.set(n - 1, j, q * z + p * H.get(n, j));\n H.set(n, j, q * H.get(n, j) - p * z);\n }\n\n for (i = 0; i <= n; i++) {\n z = H.get(i, n - 1);\n H.set(i, n - 1, q * z + p * H.get(i, n));\n H.set(i, n, q * H.get(i, n) - p * z);\n }\n\n for (i = low; i <= high; i++) {\n z = V.get(i, n - 1);\n V.set(i, n - 1, q * z + p * V.get(i, n));\n V.set(i, n, q * V.get(i, n) - p * z);\n }\n } else {\n d[n - 1] = x + p;\n d[n] = x + p;\n e[n - 1] = z;\n e[n] = -z;\n }\n\n n = n - 2;\n iter = 0;\n } else {\n x = H.get(n, n);\n y = 0;\n w = 0;\n if (l < n) {\n y = H.get(n - 1, n - 1);\n w = H.get(n, n - 1) * H.get(n - 1, n);\n }\n\n if (iter === 10) {\n exshift += x;\n for (i = low; i <= n; i++) {\n H.set(i, i, H.get(i, i) - x);\n }\n s = Math.abs(H.get(n, n - 1)) + Math.abs(H.get(n - 1, n - 2));\n x = y = 0.75 * s;\n w = -0.4375 * s * s;\n }\n\n if (iter === 30) {\n s = (y - x) / 2;\n s = s * s + w;\n if (s > 0) {\n s = Math.sqrt(s);\n if (y < x) {\n s = -s;\n }\n s = x - w / ((y - x) / 2 + s);\n for (i = low; i <= n; i++) {\n H.set(i, i, H.get(i, i) - s);\n }\n exshift += s;\n x = y = w = 0.964;\n }\n }\n\n iter = iter + 1;\n\n m = n - 2;\n while (m >= l) {\n z = H.get(m, m);\n r = x - z;\n s = y - z;\n p = (r * s - w) / H.get(m + 1, m) + H.get(m, m + 1);\n q = H.get(m + 1, m + 1) - z - r - s;\n r = H.get(m + 2, m + 1);\n s = Math.abs(p) + Math.abs(q) + Math.abs(r);\n p = p / s;\n q = q / s;\n r = r / s;\n if (m === l) {\n break;\n }\n if (\n Math.abs(H.get(m, m - 1)) * (Math.abs(q) + Math.abs(r)) <\n eps *\n (Math.abs(p) *\n (Math.abs(H.get(m - 1, m - 1)) +\n Math.abs(z) +\n Math.abs(H.get(m + 1, m + 1))))\n ) {\n break;\n }\n m--;\n }\n\n for (i = m + 2; i <= n; i++) {\n H.set(i, i - 2, 0);\n if (i > m + 2) {\n H.set(i, i - 3, 0);\n }\n }\n\n for (k = m; k <= n - 1; k++) {\n notlast = k !== n - 1;\n if (k !== m) {\n p = H.get(k, k - 1);\n q = H.get(k + 1, k - 1);\n r = notlast ? H.get(k + 2, k - 1) : 0;\n x = Math.abs(p) + Math.abs(q) + Math.abs(r);\n if (x !== 0) {\n p = p / x;\n q = q / x;\n r = r / x;\n }\n }\n\n if (x === 0) {\n break;\n }\n\n s = Math.sqrt(p * p + q * q + r * r);\n if (p < 0) {\n s = -s;\n }\n\n if (s !== 0) {\n if (k !== m) {\n H.set(k, k - 1, -s * x);\n } else if (l !== m) {\n H.set(k, k - 1, -H.get(k, k - 1));\n }\n\n p = p + s;\n x = p / s;\n y = q / s;\n z = r / s;\n q = q / p;\n r = r / p;\n\n for (j = k; j < nn; j++) {\n p = H.get(k, j) + q * H.get(k + 1, j);\n if (notlast) {\n p = p + r * H.get(k + 2, j);\n H.set(k + 2, j, H.get(k + 2, j) - p * z);\n }\n\n H.set(k, j, H.get(k, j) - p * x);\n H.set(k + 1, j, H.get(k + 1, j) - p * y);\n }\n\n for (i = 0; i <= Math.min(n, k + 3); i++) {\n p = x * H.get(i, k) + y * H.get(i, k + 1);\n if (notlast) {\n p = p + z * H.get(i, k + 2);\n H.set(i, k + 2, H.get(i, k + 2) - p * r);\n }\n\n H.set(i, k, H.get(i, k) - p);\n H.set(i, k + 1, H.get(i, k + 1) - p * q);\n }\n\n for (i = low; i <= high; i++) {\n p = x * V.get(i, k) + y * V.get(i, k + 1);\n if (notlast) {\n p = p + z * V.get(i, k + 2);\n V.set(i, k + 2, V.get(i, k + 2) - p * r);\n }\n\n V.set(i, k, V.get(i, k) - p);\n V.set(i, k + 1, V.get(i, k + 1) - p * q);\n }\n }\n }\n }\n }\n\n if (norm === 0) {\n return;\n }\n\n for (n = nn - 1; n >= 0; n--) {\n p = d[n];\n q = e[n];\n\n if (q === 0) {\n l = n;\n H.set(n, n, 1);\n for (i = n - 1; i >= 0; i--) {\n w = H.get(i, i) - p;\n r = 0;\n for (j = l; j <= n; j++) {\n r = r + H.get(i, j) * H.get(j, n);\n }\n\n if (e[i] < 0) {\n z = w;\n s = r;\n } else {\n l = i;\n if (e[i] === 0) {\n H.set(i, n, w !== 0 ? -r / w : -r / (eps * norm));\n } else {\n x = H.get(i, i + 1);\n y = H.get(i + 1, i);\n q = (d[i] - p) * (d[i] - p) + e[i] * e[i];\n t = (x * s - z * r) / q;\n H.set(i, n, t);\n H.set(\n i + 1,\n n,\n Math.abs(x) > Math.abs(z) ? (-r - w * t) / x : (-s - y * t) / z,\n );\n }\n\n t = Math.abs(H.get(i, n));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n, H.get(j, n) / t);\n }\n }\n }\n }\n } else if (q < 0) {\n l = n - 1;\n\n if (Math.abs(H.get(n, n - 1)) > Math.abs(H.get(n - 1, n))) {\n H.set(n - 1, n - 1, q / H.get(n, n - 1));\n H.set(n - 1, n, -(H.get(n, n) - p) / H.get(n, n - 1));\n } else {\n cdivres = cdiv(0, -H.get(n - 1, n), H.get(n - 1, n - 1) - p, q);\n H.set(n - 1, n - 1, cdivres[0]);\n H.set(n - 1, n, cdivres[1]);\n }\n\n H.set(n, n - 1, 0);\n H.set(n, n, 1);\n for (i = n - 2; i >= 0; i--) {\n ra = 0;\n sa = 0;\n for (j = l; j <= n; j++) {\n ra = ra + H.get(i, j) * H.get(j, n - 1);\n sa = sa + H.get(i, j) * H.get(j, n);\n }\n\n w = H.get(i, i) - p;\n\n if (e[i] < 0) {\n z = w;\n r = ra;\n s = sa;\n } else {\n l = i;\n if (e[i] === 0) {\n cdivres = cdiv(-ra, -sa, w, q);\n H.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n } else {\n x = H.get(i, i + 1);\n y = H.get(i + 1, i);\n vr = (d[i] - p) * (d[i] - p) + e[i] * e[i] - q * q;\n vi = (d[i] - p) * 2 * q;\n if (vr === 0 && vi === 0) {\n vr =\n eps *\n norm *\n (Math.abs(w) +\n Math.abs(q) +\n Math.abs(x) +\n Math.abs(y) +\n Math.abs(z));\n }\n cdivres = cdiv(\n x * r - z * ra + q * sa,\n x * s - z * sa - q * ra,\n vr,\n vi,\n );\n H.set(i, n - 1, cdivres[0]);\n H.set(i, n, cdivres[1]);\n if (Math.abs(x) > Math.abs(z) + Math.abs(q)) {\n H.set(\n i + 1,\n n - 1,\n (-ra - w * H.get(i, n - 1) + q * H.get(i, n)) / x,\n );\n H.set(\n i + 1,\n n,\n (-sa - w * H.get(i, n) - q * H.get(i, n - 1)) / x,\n );\n } else {\n cdivres = cdiv(\n -r - y * H.get(i, n - 1),\n -s - y * H.get(i, n),\n z,\n q,\n );\n H.set(i + 1, n - 1, cdivres[0]);\n H.set(i + 1, n, cdivres[1]);\n }\n }\n\n t = Math.max(Math.abs(H.get(i, n - 1)), Math.abs(H.get(i, n)));\n if (eps * t * t > 1) {\n for (j = i; j <= n; j++) {\n H.set(j, n - 1, H.get(j, n - 1) / t);\n H.set(j, n, H.get(j, n) / t);\n }\n }\n }\n }\n }\n }\n\n for (i = 0; i < nn; i++) {\n if (i < low || i > high) {\n for (j = i; j < nn; j++) {\n V.set(i, j, H.get(i, j));\n }\n }\n }\n\n for (j = nn - 1; j >= low; j--) {\n for (i = low; i <= high; i++) {\n z = 0;\n for (k = low; k <= Math.min(j, high); k++) {\n z = z + V.get(i, k) * H.get(k, j);\n }\n V.set(i, j, z);\n }\n }\n}\n\nfunction cdiv(xr, xi, yr, yi) {\n let r, d;\n if (Math.abs(yr) > Math.abs(yi)) {\n r = yi / yr;\n d = yr + r * yi;\n return [(xr + r * xi) / d, (xi - r * xr) / d];\n } else {\n r = yr / yi;\n d = yi + r * yr;\n return [(r * xr + xi) / d, (r * xi - xr) / d];\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class CholeskyDecomposition {\n constructor(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n if (!value.isSymmetric()) {\n throw new Error('Matrix is not symmetric');\n }\n\n let a = value;\n let dimension = a.rows;\n let l = new Matrix(dimension, dimension);\n let positiveDefinite = true;\n let i, j, k;\n\n for (j = 0; j < dimension; j++) {\n let d = 0;\n for (k = 0; k < j; k++) {\n let s = 0;\n for (i = 0; i < k; i++) {\n s += l.get(k, i) * l.get(j, i);\n }\n s = (a.get(j, k) - s) / l.get(k, k);\n l.set(j, k, s);\n d = d + s * s;\n }\n\n d = a.get(j, j) - d;\n\n positiveDefinite &= d > 0;\n l.set(j, j, Math.sqrt(Math.max(d, 0)));\n for (k = j + 1; k < dimension; k++) {\n l.set(j, k, 0);\n }\n }\n\n this.L = l;\n this.positiveDefinite = Boolean(positiveDefinite);\n }\n\n isPositiveDefinite() {\n return this.positiveDefinite;\n }\n\n solve(value) {\n value = WrapperMatrix2D.checkMatrix(value);\n\n let l = this.L;\n let dimension = l.rows;\n\n if (value.rows !== dimension) {\n throw new Error('Matrix dimensions do not match');\n }\n if (this.isPositiveDefinite() === false) {\n throw new Error('Matrix is not positive definite');\n }\n\n let count = value.columns;\n let B = value.clone();\n let i, j, k;\n\n for (k = 0; k < dimension; k++) {\n for (j = 0; j < count; j++) {\n for (i = 0; i < k; i++) {\n B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(k, i));\n }\n B.set(k, j, B.get(k, j) / l.get(k, k));\n }\n }\n\n for (k = dimension - 1; k >= 0; k--) {\n for (j = 0; j < count; j++) {\n for (i = k + 1; i < dimension; i++) {\n B.set(k, j, B.get(k, j) - B.get(i, j) * l.get(i, k));\n }\n B.set(k, j, B.get(k, j) / l.get(k, k));\n }\n }\n\n return B;\n }\n\n get lowerTriangularMatrix() {\n return this.L;\n }\n}\n","import Matrix from '../matrix';\nimport WrapperMatrix2D from '../wrap/WrapperMatrix2D';\n\nexport default class nipals {\n constructor(X, options = {}) {\n X = WrapperMatrix2D.checkMatrix(X);\n let { Y } = options;\n const {\n scaleScores = false,\n maxIterations = 1000,\n terminationCriteria = 1e-10,\n } = options;\n\n let u;\n if (Y) {\n if (Array.isArray(Y) && typeof Y[0] === 'number') {\n Y = Matrix.columnVector(Y);\n } else {\n Y = WrapperMatrix2D.checkMatrix(Y);\n }\n if (Y.rows !== X.rows) {\n throw new Error('Y should have the same number of rows as X');\n }\n u = Y.getColumnVector(0);\n } else {\n u = X.getColumnVector(0);\n }\n\n let diff = 1;\n let t, q, w, tOld;\n\n for (\n let counter = 0;\n counter < maxIterations && diff > terminationCriteria;\n counter++\n ) {\n w = X.transpose().mmul(u).div(u.transpose().mmul(u).get(0, 0));\n w = w.div(w.norm());\n\n t = X.mmul(w).div(w.transpose().mmul(w).get(0, 0));\n\n if (counter > 0) {\n diff = t.clone().sub(tOld).pow(2).sum();\n }\n tOld = t.clone();\n\n if (Y) {\n q = Y.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n q = q.div(q.norm());\n\n u = Y.mmul(q).div(q.transpose().mmul(q).get(0, 0));\n } else {\n u = t;\n }\n }\n\n if (Y) {\n let p = X.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n p = p.div(p.norm());\n let xResidual = X.clone().sub(t.clone().mmul(p.transpose()));\n let residual = u.transpose().mmul(t).div(t.transpose().mmul(t).get(0, 0));\n let yResidual = Y.clone().sub(\n t.clone().mulS(residual.get(0, 0)).mmul(q.transpose()),\n );\n\n this.t = t;\n this.p = p.transpose();\n this.w = w.transpose();\n this.q = q;\n this.u = u;\n this.s = t.transpose().mmul(t);\n this.xResidual = xResidual;\n this.yResidual = yResidual;\n this.betas = residual;\n } else {\n this.w = w.transpose();\n this.s = t.transpose().mmul(t).sqrt();\n if (scaleScores) {\n this.t = t.clone().div(this.s.get(0, 0));\n } else {\n this.t = t;\n }\n this.xResidual = X.sub(t.mmul(w.transpose()));\n }\n }\n}\n","import { SVD } from 'ml-matrix';\n\nexport default function getSeparatedKernel(kernel) {\n const svd = new SVD(kernel, { autoTranspose: true });\n if (svd.rank !== 1) return null;\n const s = Math.sqrt(svd.s[0]);\n const v = svd.U.to2DArray().map((v) => v[0] * s);\n const h = svd.V.to2DArray().map((h) => h[0] * s);\n return [v, h];\n}\n","import { direct, fft } from 'ml-matrix-convolution';\n\nimport { validateArrayOfChannels } from '../../util/channel';\nimport { validateKernel } from '../../util/kernel';\nimport Image from '../Image';\nimport { clamp } from '../internal/clamp';\n\nimport convolutionSeparable from './convolutionSeparable';\nimport getSeparatedKernel from './getSeparatedKernel';\n\n/**\n * @memberof Image\n * @instance\n * @param {Array>} kernel\n * @param {object} [options] - options\n * @param {Array} [options.channels] - Array of channels to treat. Defaults to all channels\n * @param {number} [options.bitDepth=this.bitDepth] - A new bit depth can be specified. This allows to use 32 bits to avoid clamping of floating-point numbers.\n * @param {boolean} [options.normalize=false]\n * @param {number} [options.divisor=1]\n * @param {string} [options.border='copy']\n * @param {string} [options.algorithm='auto'] - Either 'auto', 'direct', 'fft' or 'separable'. fft is much faster for large kernel.\n * If the separable algorithm is used, one must provide as kernel an array of two 1D kernels.\n * The 'auto' option will try to separate the kernel if that is possible.\n * @return {Image}\n */\nexport default function convolution(kernel, options = {}) {\n let {\n channels,\n bitDepth,\n normalize = false,\n divisor = 1,\n border = 'copy',\n algorithm = 'auto',\n } = options;\n let createOptions = {};\n if (bitDepth) createOptions.bitDepth = bitDepth;\n let newImage = Image.createFrom(this, createOptions);\n\n channels = validateArrayOfChannels(this, channels, true);\n\n if (algorithm !== 'separable') {\n ({ kernel } = validateKernel(kernel));\n } else if (!Array.isArray(kernel) || kernel.length !== 2) {\n throw new RangeError(\n 'separable convolution requires two arrays of numbers to represent the kernel',\n );\n }\n\n if (algorithm === 'auto') {\n let separatedKernel = getSeparatedKernel(kernel);\n if (separatedKernel !== null) {\n algorithm = 'separable';\n kernel = separatedKernel;\n } else if (\n (kernel.length > 9 || kernel[0].length > 9) &&\n this.width <= 4096 &&\n this.height <= 4096\n ) {\n algorithm = 'fft';\n } else {\n algorithm = 'direct';\n }\n }\n\n let halfHeight, halfWidth;\n if (algorithm === 'separable') {\n halfHeight = Math.floor(kernel[0].length / 2);\n halfWidth = Math.floor(kernel[1].length / 2);\n } else {\n halfHeight = Math.floor(kernel.length / 2);\n halfWidth = Math.floor(kernel[0].length / 2);\n }\n let clamped = newImage.isClamped;\n\n let tmpData = new Array(this.height * this.width);\n let index, x, y, channel, c, tmpResult;\n for (channel = 0; channel < channels.length; channel++) {\n c = channels[channel];\n // Copy the channel in a single array\n for (y = 0; y < this.height; y++) {\n for (x = 0; x < this.width; x++) {\n index = y * this.width + x;\n tmpData[index] = this.data[index * this.channels + c];\n }\n }\n if (algorithm === 'direct') {\n tmpResult = direct(tmpData, kernel, {\n rows: this.height,\n cols: this.width,\n normalize: normalize,\n divisor: divisor,\n });\n } else if (algorithm === 'separable') {\n tmpResult = convolutionSeparable(\n tmpData,\n kernel,\n this.width,\n this.height,\n );\n if (normalize) {\n divisor = 0;\n for (let i = 0; i < kernel[0].length; i++) {\n for (let j = 0; j < kernel[1].length; j++) {\n divisor += kernel[0][i] * kernel[1][j];\n }\n }\n }\n if (divisor !== 1) {\n for (let i = 0; i < tmpResult.length; i++) {\n tmpResult[i] /= divisor;\n }\n }\n } else {\n tmpResult = fft(tmpData, kernel, {\n rows: this.height,\n cols: this.width,\n normalize: normalize,\n divisor: divisor,\n });\n }\n\n // Copy the result to the output image\n for (y = 0; y < this.height; y++) {\n for (x = 0; x < this.width; x++) {\n index = y * this.width + x;\n if (clamped) {\n newImage.data[index * this.channels + c] = clamp(\n tmpResult[index],\n newImage,\n );\n } else {\n newImage.data[index * this.channels + c] = tmpResult[index];\n }\n }\n }\n }\n // if the kernel was not applied on the alpha channel we just copy it\n // TODO: in general we should copy the channels that where not changed\n // TODO: probably we should just copy the image at the beginning ?\n if (this.alpha && !channels.includes(this.channels)) {\n for (x = this.components; x < this.data.length; x = x + this.channels) {\n newImage.data[x] = this.data[x];\n }\n }\n\n // I only can have 3 types of borders:\n // 1. Considering the image as periodic: periodic\n // 2. Extend the interior borders: copy\n // 3. fill with a color: set\n if (border !== 'periodic') {\n newImage.setBorder({ size: [halfWidth, halfHeight], algorithm: border });\n }\n\n return newImage;\n}\n","import convolution from '../operator/convolution';\n\n/**\n * Direction of a gradient filter\n * @typedef {('x'|'y'|'xy')} GradientDirection\n */\n\n/**\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {GradientDirection} [options.direction]\n * @param {Array>} [options.kernelX]\n * @param {Array>} [options.kernelY]\n * @param {string} [options.border='copy']\n * @param {*} [options.channels]\n * @param {number} [options.bitDepth=this.bitDepth] Specify the bitDepth of the resulting image\n * @return {Image}\n */\nexport default function gradientFilter(options = {}) {\n let {\n direction = 'xy',\n border = 'copy',\n kernelX,\n kernelY,\n channels,\n bitDepth = this.bitDepth,\n } = options;\n\n this.checkProcessable('gradientFilter', {\n bitDepth: [8, 16],\n });\n\n switch (direction) {\n case 'x':\n if (!kernelX) throw new Error('kernelX option is missing');\n return convolution.call(this, kernelX, {\n channels: channels,\n border: border,\n bitDepth,\n });\n case 'y':\n if (!kernelY) throw new Error('kernelY option is missing');\n return convolution.call(this, kernelY, {\n channels: channels,\n border: border,\n bitDepth,\n });\n case 'xy': {\n if (!kernelX) throw new Error('kernelX option is missing');\n if (!kernelY) throw new Error('kernelY option is missing');\n const gX = convolution.call(this, kernelX, {\n channels: channels,\n border: border,\n bitDepth: 32,\n });\n const gY = convolution.call(this, kernelY, {\n channels: channels,\n border: border,\n bitDepth: 32,\n });\n return gX.hypotenuse(gY, { bitDepth, channels: channels });\n }\n default:\n throw new Error(`Unknown parameter direction: ${direction}`);\n }\n}\n","import { SOBEL_X, SOBEL_Y } from '../../util/kernels';\n\nimport gradientFilter from './gradientFilter';\n\n/**\n * Applies the Sobel operator.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {GradientDirection} [options.direction]\n * @param {string} [options.border='copy']\n * @param {*} [options.channels]\n * @param {number} [options.bitDepth=this.bitDepth] Specify the bitDepth of the resulting image\n * @return {Image}\n * @see {@link https://en.wikipedia.org/wiki/Sobel_operator}\n */\nexport default function sobelFilter(options) {\n return gradientFilter.call(\n this,\n Object.assign({}, options, {\n kernelX: SOBEL_X,\n kernelY: SOBEL_Y,\n }),\n );\n}\n","import { SCHARR_X, SCHARR_Y } from '../../util/kernels';\n\nimport gradientFilter from './gradientFilter';\n\n/**\n * Applies the Scharr operator.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {GradientDirection} [options.direction]\n * @param {string} [options.border='copy']\n * @param {*} [options.channels]\n * @param {number} [options.bitDepth=this.bitDepth] Specify the bitDepth of the resulting image\n * @return {Image}\n * @see {@link https://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators}\n */\nexport default function scharrFilter(options) {\n return gradientFilter.call(\n this,\n Object.assign({}, options, {\n kernelX: SCHARR_X,\n kernelY: SCHARR_Y,\n }),\n );\n}\n","module.exports = newArray\n\nfunction newArray (n, value) {\n n = n || 0\n var array = new Array(n)\n for (var i = 0; i < n; i++) {\n array[i] = value\n }\n return array\n}\n","import newArray from 'new-array';\n\nimport { validateArrayOfChannels } from '../../util/channel';\n\n/**\n * Level the image for by default have the minimal and maximal values.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {string} [options.algorithm='range']\n * @param {SelectedChannels} [options.channels] Specify which channels should be processed\n * @param {number} [options.min=this.min] minimal value after levelling\n * @param {number} [options.max=this.max] maximal value after levelling\n * @return {this}\n */\nexport default function level(options = {}) {\n let {\n algorithm = 'range',\n channels,\n min = this.min,\n max = this.max,\n } = options;\n\n this.checkProcessable('level', {\n bitDepth: [8, 16, 32],\n });\n\n channels = validateArrayOfChannels(this, { channels: channels });\n\n if (channels.length !== this.channel) {\n // if we process only part of the channels and the min or max length corresponds to the number of channels\n // we need to take the corresponding values\n if (Array.isArray(min) && min.length === this.channels) {\n min = min.filter((a, index) => channels.includes(index));\n }\n if (Array.isArray(max) && max.length === this.channels) {\n max = max.filter((a, index) => channels.includes(index));\n }\n }\n\n switch (algorithm) {\n case 'range':\n if (min < 0) {\n min = 0;\n }\n if (max > this.maxValue) {\n max = this.maxValue;\n }\n\n if (!Array.isArray(min)) {\n min = newArray(channels.length, min);\n }\n if (!Array.isArray(max)) {\n max = newArray(channels.length, max);\n }\n\n processImage(this, min, max, channels);\n break;\n\n default:\n throw new Error(`level: algorithm not implement: ${algorithm}`);\n }\n\n return this;\n}\n\nfunction processImage(image, min, max, channels) {\n let delta = 1e-5; // sorry no better value that this \"best guess\"\n let factor = new Array(channels.length);\n\n for (let i = 0; i < channels.length; i++) {\n if (min[i] === 0 && max[i] === image.maxValue) {\n factor[i] = 0;\n } else if (max[i] === min[i]) {\n factor[i] = 0;\n } else {\n factor[i] = (image.maxValue + 1 - delta) / (max[i] - min[i]);\n }\n min[i] += (0.5 - delta / 2) / factor[i];\n }\n\n /*\n Note on border effect\n For 8 bits images we should calculate for the space between -0.5 and 255.5\n so that after ronding the first and last points still have the same population\n But doing this we need to deal with Math.round that gives 256 if the value is 255.5\n */\n\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n if (factor[j] !== 0) {\n for (let i = 0; i < image.data.length; i += image.channels) {\n image.data[i + c] = Math.min(\n Math.max(0, ((image.data[i + c] - min[j]) * factor[j] + 0.5) | 0),\n image.maxValue,\n );\n }\n }\n }\n}\n","'use strict';\n\nvar toString = Object.prototype.toString;\n\nmodule.exports = function isArrayType(value) {\n return toString.call(value).substr(-6, 5) === 'Array';\n};\n","import isArray from 'is-array-type';\n\nimport Image from '../image/Image';\n\nexport function checkNumberArray(value) {\n if (!isNaN(value)) {\n if (value <= 0) {\n throw new Error('checkNumberArray: the value must be greater than 0');\n }\n return value;\n } else {\n if (value instanceof Image) {\n return value.data;\n }\n if (!isArray(value)) {\n throw new Error(\n 'checkNumberArray: the value should be either a number, array or Image',\n );\n }\n return value;\n }\n}\n","import { validateArrayOfChannels } from '../../util/channel';\nimport { checkNumberArray } from '../../util/value';\n\n/**\n * Add a specific integer on the specified points of the specified channels\n * @memberof Image\n * @instance\n * @param {*} value\n * @param {object} [options]\n * @return {this} Modified current image\n */\nexport default function add(value, options = {}) {\n let { channels } = options;\n this.checkProcessable('add', {\n bitDepth: [8, 16],\n });\n\n channels = validateArrayOfChannels(this, { channels: channels });\n value = checkNumberArray(value);\n\n // we allow 3 cases, the value may be an array (1D), an image or a single value\n if (!isNaN(value)) {\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = 0; i < this.data.length; i += this.channels) {\n this.data[i + c] = Math.min(\n this.maxValue,\n (this.data[i + c] + value) >> 0,\n );\n }\n }\n } else {\n if (this.data.length !== value.length) {\n throw new Error('add: the data size is different');\n }\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = 0; i < this.data.length; i += this.channels) {\n this.data[i + c] = Math.max(\n 0,\n Math.min(this.maxValue, (this.data[i + c] + value[i + c]) >> 0),\n );\n }\n }\n }\n\n return this;\n}\n","import { validateArrayOfChannels } from '../../util/channel';\nimport { checkNumberArray } from '../../util/value';\n\n/**\n * @memberof Image\n * @instance\n * @param {*} value\n * @param {object} [options]\n * @return {this}\n */\nexport default function subtract(value, options = {}) {\n let { channels } = options;\n this.checkProcessable('subtract', {\n bitDepth: [8, 16],\n });\n\n channels = validateArrayOfChannels(this, { channels: channels });\n value = checkNumberArray(value);\n\n if (!isNaN(value)) {\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = 0; i < this.data.length; i += this.channels) {\n this.data[i + c] = Math.max(0, (this.data[i + c] - value) >> 0);\n }\n }\n } else {\n if (this.data.length !== value.length) {\n throw new Error('subtract: the data size is different');\n }\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = 0; i < this.data.length; i += this.channels) {\n this.data[i + c] = Math.max(\n 0,\n Math.min(this.maxValue, (this.data[i + c] - value[i + c]) >> 0),\n );\n }\n }\n }\n\n return this;\n}\n","import { validateArrayOfChannels } from '../../util/channel';\n\n/**\n * Calculate a new image that is the subtraction between the current image and the otherImage.\n * @memberof Image\n * @instance\n * @param {Image} otherImage\n * @param {object} [options={}]\n * @param {number[]|string[]} [options.channels] : to which channel to apply the filter. By default all but alpha.\n * @param {number[]|string[]} [options.absolute=false] :.take the absolute value of the difference (default minimum=0)\n * @return {Image}\n */\nexport default function subtractImage(otherImage, options = {}) {\n let { channels, absolute = false } = options;\n this.checkProcessable('subtractImage', {\n bitDepth: [8, 16],\n });\n if (this.width !== otherImage.width || this.height !== otherImage.height) {\n throw new Error('subtractImage: both images must have the same size');\n }\n if (\n this.alpha !== otherImage.alpha ||\n this.bitDepth !== otherImage.bitDepth\n ) {\n throw new Error(\n 'subtractImage: both images must have the same alpha and bitDepth',\n );\n }\n if (this.channels !== otherImage.channels) {\n throw new Error(\n 'subtractImage: both images must have the same number of channels',\n );\n }\n\n let newImage = this.clone();\n\n channels = validateArrayOfChannels(this, { channels: channels });\n\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = c; i < this.data.length; i += this.channels) {\n let value = this.data[i] - otherImage.data[i];\n if (absolute) {\n newImage.data[i] = Math.abs(value);\n } else {\n newImage.data[i] = Math.max(value, 0);\n }\n }\n }\n\n return newImage;\n}\n","import { validateArrayOfChannels } from '../../util/channel';\nimport Image from '../Image';\n\n/**\n * Calculate a new image that is the hypotenuse between the current image and the otherImage.\n * @memberof Image\n * @instance\n * @param {Image} otherImage\n * @param {object} [options={}]\n * @param {number} [options.bitDepth=this.bitDepth]\n * @param {number[]|string[]} [options.channels] : to which channel to apply the filter. By default all but alpha.\n * @return {Image}\n */\nexport default function hypotenuse(otherImage, options = {}) {\n let { bitDepth = this.bitDepth, channels } = options;\n this.checkProcessable('hypotenuse', {\n bitDepth: [8, 16, 32],\n });\n if (this.width !== otherImage.width || this.height !== otherImage.height) {\n throw new Error('hypotenuse: both images must have the same size');\n }\n if (\n this.alpha !== otherImage.alpha ||\n this.bitDepth !== otherImage.bitDepth\n ) {\n throw new Error(\n 'hypotenuse: both images must have the same alpha and bitDepth',\n );\n }\n if (this.channels !== otherImage.channels) {\n throw new Error(\n 'hypotenuse: both images must have the same number of channels',\n );\n }\n\n let newImage = Image.createFrom(this, { bitDepth: bitDepth });\n\n channels = validateArrayOfChannels(this, { channels: channels });\n\n let clamped = newImage.isClamped;\n\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = c; i < this.data.length; i += this.channels) {\n let value = Math.hypot(this.data[i], otherImage.data[i]);\n if (clamped) {\n // we calculate the clamped result\n newImage.data[i] = Math.min(\n Math.max(Math.round(value), 0),\n newImage.maxValue,\n );\n } else {\n newImage.data[i] = value;\n }\n }\n }\n\n return newImage;\n}\n","import { validateArrayOfChannels } from '../../util/channel';\nimport { checkNumberArray } from '../../util/value';\n\n/**\n * @memberof Image\n * @instance\n * @param {*} value\n * @param {object} [options]\n * @return {this}\n */\nexport default function multiply(value, options = {}) {\n let { channels } = options;\n this.checkProcessable('multiply', {\n bitDepth: [8, 16],\n });\n if (value <= 0) {\n throw new Error('multiply: the value must be greater than 0');\n }\n\n channels = validateArrayOfChannels(this, { channels: channels });\n value = checkNumberArray(value);\n\n if (!isNaN(value)) {\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = 0; i < this.data.length; i += this.channels) {\n this.data[i + c] = Math.min(\n this.maxValue,\n (this.data[i + c] * value) >> 0,\n );\n }\n }\n } else {\n if (this.data.length !== value.length) {\n throw new Error('multiply: the data size is different');\n }\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = 0; i < this.data.length; i += this.channels) {\n this.data[i + c] = Math.max(\n 0,\n Math.min(this.maxValue, (this.data[i + c] * value[i + c]) >> 0),\n );\n }\n }\n }\n\n return this;\n}\n","import { validateArrayOfChannels } from '../../util/channel';\nimport { checkNumberArray } from '../../util/value';\n\n/**\n * @memberof Image\n * @instance\n * @param {*} value\n * @param {object} [options]\n * @return {this}\n */\nexport default function divide(value, options = {}) {\n let { channels } = options;\n this.checkProcessable('divide', {\n bitDepth: [8, 16],\n });\n\n channels = validateArrayOfChannels(this, { channels: channels });\n value = checkNumberArray(value);\n\n if (!isNaN(value)) {\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = 0; i < this.data.length; i += this.channels) {\n this.data[i + c] = Math.min(\n this.maxValue,\n (this.data[i + c] / value) >> 0,\n );\n }\n }\n } else {\n if (this.data.length !== value.length) {\n throw new Error('divide: the: the data size is different');\n }\n for (let j = 0; j < channels.length; j++) {\n let c = channels[j];\n for (let i = 0; i < this.data.length; i += this.channels) {\n this.data[i + c] = Math.max(\n 0,\n Math.min(this.maxValue, (this.data[i + c] / value[i + c]) >> 0),\n );\n }\n }\n }\n\n return this;\n}\n","import isAnyArray from 'is-any-array';\n\nexport { default as maybeToPrecision } from './maybeToPrecision';\nexport { default as checkArrayLength } from './checkArrayLength';\nexport default class BaseRegression {\n constructor() {\n if (new.target === BaseRegression) {\n throw new Error('BaseRegression must be subclassed');\n }\n }\n\n predict(x) {\n if (typeof x === 'number') {\n return this._predict(x);\n } else if (isAnyArray(x)) {\n const y = [];\n for (let i = 0; i < x.length; i++) {\n y.push(this._predict(x[i]));\n }\n return y;\n } else {\n throw new TypeError('x must be a number or array');\n }\n }\n\n _predict() {\n throw new Error('_predict must be implemented');\n }\n\n train() {\n // Do nothing for this package\n }\n\n toString() {\n return '';\n }\n\n toLaTeX() {\n return '';\n }\n\n /**\n * Return the correlation coefficient of determination (r) and chi-square.\n * @param {Array} x\n * @param {Array} y\n * @return {object}\n */\n score(x, y) {\n if (!isAnyArray(x) || !isAnyArray(y) || x.length !== y.length) {\n throw new Error('x and y must be arrays of the same length');\n }\n\n const n = x.length;\n const y2 = new Array(n);\n for (let i = 0; i < n; i++) {\n y2[i] = this._predict(x[i]);\n }\n\n let xSum = 0;\n let ySum = 0;\n let chi2 = 0;\n let rmsd = 0;\n let xSquared = 0;\n let ySquared = 0;\n let xY = 0;\n for (let i = 0; i < n; i++) {\n xSum += y2[i];\n ySum += y[i];\n xSquared += y2[i] * y2[i];\n ySquared += y[i] * y[i];\n xY += y2[i] * y[i];\n if (y[i] !== 0) {\n chi2 += ((y[i] - y2[i]) * (y[i] - y2[i])) / y[i];\n }\n rmsd += (y[i] - y2[i]) * (y[i] - y2[i]);\n }\n\n const r =\n (n * xY - xSum * ySum) /\n Math.sqrt((n * xSquared - xSum * xSum) * (n * ySquared - ySum * ySum));\n\n return {\n r: r,\n r2: r * r,\n chi2: chi2,\n rmsd: Math.sqrt(rmsd / n),\n };\n }\n}\n","export function squaredEuclidean(p, q) {\r\n let d = 0;\r\n for (let i = 0; i < p.length; i++) {\r\n d += (p[i] - q[i]) * (p[i] - q[i]);\r\n }\r\n return d;\r\n}\r\nexport function euclidean(p, q) {\r\n return Math.sqrt(squaredEuclidean(p, q));\r\n}\r\n","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass GaussianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = GaussianKernel;\n","'use strict';\n\nconst defaultOptions = {\n degree: 1,\n constant: 1,\n scale: 1\n};\n\nclass PolynomialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n\n this.degree = options.degree;\n this.constant = options.constant;\n this.scale = options.scale;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.pow(this.scale * sum + this.constant, this.degree);\n }\n}\n\nmodule.exports = PolynomialKernel;\n","'use strict';\n\nconst defaultOptions = {\n alpha: 0.01,\n constant: -Math.E\n};\n\nclass SigmoidKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.alpha = options.alpha;\n this.constant = options.constant;\n }\n\n compute(x, y) {\n var sum = 0;\n for (var i = 0; i < x.length; i++) {\n sum += x[i] * y[i];\n }\n return Math.tanh(this.alpha * sum + this.constant);\n }\n}\n\nmodule.exports = SigmoidKernel;\n","'use strict';\n\nconst defaultOptions = {\n sigma: 1,\n degree: 1\n};\n\nclass ANOVAKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.degree = options.degree;\n }\n\n compute(x, y) {\n var sum = 0;\n var len = Math.min(x.length, y.length);\n for (var i = 1; i <= len; ++i) {\n sum += Math.pow(\n Math.exp(\n -this.sigma *\n Math.pow(Math.pow(x[i - 1], i) - Math.pow(y[i - 1], i), 2)\n ),\n this.degree\n );\n }\n return sum;\n }\n}\n\nmodule.exports = ANOVAKernel;\n","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass CauchyKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n return 1 / (1 + squaredEuclidean(x, y) / (this.sigma * this.sigma));\n }\n}\n\nmodule.exports = CauchyKernel;\n","'use strict';\n\nconst { euclidean } = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass ExponentialKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n this.divisor = 2 * options.sigma * options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.divisor);\n }\n}\n\nmodule.exports = ExponentialKernel;\n","'use strict';\n\nclass HistogramIntersectionKernel {\n compute(x, y) {\n var min = Math.min(x.length, y.length);\n var sum = 0;\n for (var i = 0; i < min; ++i) {\n sum += Math.min(x[i], y[i]);\n }\n\n return sum;\n }\n}\n\nmodule.exports = HistogramIntersectionKernel;\n","'use strict';\n\nconst { euclidean } = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n sigma: 1\n};\n\nclass LaplacianKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.sigma = options.sigma;\n }\n\n compute(x, y) {\n const distance = euclidean(x, y);\n return Math.exp(-distance / this.sigma);\n }\n}\n\nmodule.exports = LaplacianKernel;\n","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass MultiquadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n return Math.sqrt(squaredEuclidean(x, y) + this.constant * this.constant);\n }\n}\n\nmodule.exports = MultiquadraticKernel;\n","'use strict';\n\nconst { squaredEuclidean } = require('ml-distance-euclidean');\n\nconst defaultOptions = {\n constant: 1\n};\n\nclass RationalQuadraticKernel {\n constructor(options) {\n options = Object.assign({}, defaultOptions, options);\n this.constant = options.constant;\n }\n\n compute(x, y) {\n const distance = squaredEuclidean(x, y);\n return 1 - distance / (distance + this.constant);\n }\n}\n\nmodule.exports = RationalQuadraticKernel;\n","'use strict';\n\nconst { Matrix, MatrixTransposeView } = require('ml-matrix');\nconst GaussianKernel = require('ml-kernel-gaussian');\nconst PolynomialKernel = require('ml-kernel-polynomial');\nconst SigmoidKernel = require('ml-kernel-sigmoid');\n\nconst ANOVAKernel = require('./kernels/anova-kernel');\nconst CauchyKernel = require('./kernels/cauchy-kernel');\nconst ExponentialKernel = require('./kernels/exponential-kernel');\nconst HistogramKernel = require('./kernels/histogram-intersection-kernel');\nconst LaplacianKernel = require('./kernels/laplacian-kernel');\nconst MultiquadraticKernel = require('./kernels/multiquadratic-kernel');\nconst RationalKernel = require('./kernels/rational-quadratic-kernel');\n\nconst kernelType = {\n gaussian: GaussianKernel,\n rbf: GaussianKernel,\n polynomial: PolynomialKernel,\n poly: PolynomialKernel,\n anova: ANOVAKernel,\n cauchy: CauchyKernel,\n exponential: ExponentialKernel,\n histogram: HistogramKernel,\n min: HistogramKernel,\n laplacian: LaplacianKernel,\n multiquadratic: MultiquadraticKernel,\n rational: RationalKernel,\n sigmoid: SigmoidKernel,\n mlp: SigmoidKernel\n};\n\nclass Kernel {\n constructor(type, options) {\n this.kernelType = type;\n if (type === 'linear') return;\n\n if (typeof type === 'string') {\n type = type.toLowerCase();\n\n var KernelConstructor = kernelType[type];\n if (KernelConstructor) {\n this.kernelFunction = new KernelConstructor(options);\n } else {\n throw new Error(`unsupported kernel type: ${type}`);\n }\n } else if (typeof type === 'object' && typeof type.compute === 'function') {\n this.kernelFunction = type;\n } else {\n throw new TypeError(\n 'first argument must be a valid kernel type or instance'\n );\n }\n }\n\n compute(inputs, landmarks) {\n inputs = Matrix.checkMatrix(inputs);\n if (landmarks === undefined) {\n landmarks = inputs;\n } else {\n landmarks = Matrix.checkMatrix(landmarks);\n }\n if (this.kernelType === 'linear') {\n return inputs.mmul(new MatrixTransposeView(landmarks));\n }\n\n const kernelMatrix = new Matrix(inputs.rows, landmarks.rows);\n if (inputs === landmarks) {\n // fast path, matrix is symmetric\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = i; j < inputs.rows; j++) {\n const value = this.kernelFunction.compute(\n inputs.getRow(i),\n inputs.getRow(j)\n );\n kernelMatrix.set(i, j, value);\n kernelMatrix.set(j, i, value);\n }\n }\n } else {\n for (let i = 0; i < inputs.rows; i++) {\n for (let j = 0; j < landmarks.rows; j++) {\n kernelMatrix.set(\n i,\n j,\n this.kernelFunction.compute(inputs.getRow(i), landmarks.getRow(j))\n );\n }\n }\n }\n return kernelMatrix;\n }\n}\n\nmodule.exports = Kernel;\n","import { Matrix, solve } from 'ml-matrix';\nimport Kernel from 'ml-kernel';\nimport BaseRegression from 'ml-regression-base';\n\nconst defaultOptions = {\n lambda: 0.1,\n kernelType: 'gaussian',\n kernelOptions: {},\n computeCoefficient: false\n};\n\n// Implements the Kernel ridge regression algorithm.\n// http://www.ics.uci.edu/~welling/classnotes/papers_class/Kernel-Ridge.pdf\nexport default class KernelRidgeRegression extends BaseRegression {\n constructor(inputs, outputs, options) {\n super();\n if (inputs === true) {\n // reloading model\n this.alpha = outputs.alpha;\n this.inputs = outputs.inputs;\n this.kernelType = outputs.kernelType;\n this.kernelOptions = outputs.kernelOptions;\n this.kernel = new Kernel(outputs.kernelType, outputs.kernelOptions);\n } else {\n inputs = Matrix.checkMatrix(inputs);\n options = Object.assign({}, defaultOptions, options);\n\n const kernelFunction = new Kernel(\n options.kernelType,\n options.kernelOptions\n );\n const K = kernelFunction.compute(inputs);\n const n = inputs.rows;\n K.add(Matrix.eye(n, n).mul(options.lambda));\n\n this.alpha = solve(K, outputs);\n this.inputs = inputs;\n this.kernelType = options.kernelType;\n this.kernelOptions = options.kernelOptions;\n this.kernel = kernelFunction;\n }\n }\n\n _predict(newInputs) {\n return this.kernel\n .compute([newInputs], this.inputs)\n .mmul(this.alpha)\n .getRow(0);\n }\n\n toJSON() {\n return {\n name: 'kernelRidgeRegression',\n alpha: this.alpha,\n inputs: this.inputs,\n kernelType: this.kernelType,\n kernelOptions: this.kernelOptions\n };\n }\n\n static load(json) {\n if (json.name !== 'kernelRidgeRegression') {\n throw new TypeError('not a KRR model');\n }\n return new KernelRidgeRegression(true, json);\n }\n}\n","import { KernelRidgeRegression } from 'ml-regression';\n\nimport Image from '../Image';\n\n/**\n * @memberof Image\n * @instance\n * @param {Array>} coordinates\n * @param {Array>} values;\n * @param {object} [options]\n * @return {Image}\n */\nexport default function background(coordinates, values, options) {\n const model = new KernelRidgeRegression(coordinates, values, options);\n const allCoordinates = new Array(this.size);\n for (let i = 0; i < this.width; i++) {\n for (let j = 0; j < this.height; j++) {\n allCoordinates[j * this.width + i] = [i, j];\n }\n }\n const result = model.predict(allCoordinates);\n const background = Image.createFrom(this);\n for (let i = 0; i < this.size; i++) {\n background.data[i] = Math.min(this.maxValue, Math.max(0, result[i][0]));\n }\n return background;\n}\n","import Image from '../Image';\n\n/**\n * Dilatation is one of two fundamental operations (with erosion) in morphological\n * image processing from which all other morphological operations are based (from Wikipedia).\n * Replaces each value with it's local maximum among the pixels with a kernel value of 1.\n * http://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html\n * https://en.wikipedia.org/wiki/Dilation_(morphology)\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Array>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]\n * @param {number} [options.iterations=1] - The number of successive erosions\n * @return {Image}\n */\nexport default function dilate(options = {}) {\n let {\n kernel = [\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n ],\n iterations = 1,\n } = options;\n\n this.checkProcessable('dilate', {\n bitDepth: [1, 8, 16],\n components: 1,\n alpha: 0,\n });\n if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {\n throw new TypeError(\n 'dilate: The number of rows and columns of the kernel must be odd',\n );\n }\n\n let onlyOnes = true;\n outer: for (const row of kernel) {\n for (const value of row) {\n if (value !== 1) {\n onlyOnes = false;\n break outer;\n }\n }\n }\n\n let result = this;\n for (let i = 0; i < iterations; i++) {\n if (this.bitDepth === 1) {\n if (onlyOnes) {\n const newImage = result.clone();\n result = dilateOnceBinaryOnlyOnes(\n result,\n newImage,\n kernel.length,\n kernel[0].length,\n );\n } else {\n const newImage = Image.createFrom(result);\n result = dilateOnceBinary(result, newImage, kernel);\n }\n } else if (onlyOnes) {\n const newImage = Image.createFrom(result);\n result = dilateOnceGreyOnlyOnes(\n result,\n newImage,\n kernel.length,\n kernel[0].length,\n );\n } else {\n const newImage = Image.createFrom(result);\n result = dilateOnceGrey(result, newImage, kernel);\n }\n }\n return result;\n}\n\nfunction dilateOnceGrey(img, newImage, kernel) {\n const kernelWidth = kernel.length;\n const kernelHeight = kernel[0].length;\n let radiusX = (kernelWidth - 1) / 2;\n let radiusY = (kernelHeight - 1) / 2;\n for (let y = 0; y < img.height; y++) {\n for (let x = 0; x < img.width; x++) {\n let max = 0;\n for (let jj = 0; jj < kernelHeight; jj++) {\n for (let ii = 0; ii < kernelWidth; ii++) {\n if (kernel[ii][jj] !== 1) continue;\n let i = ii - radiusX + x;\n let j = jj - radiusY + y;\n if (i < 0 || j < 0 || i >= img.width || j >= img.height) continue;\n const value = img.getValueXY(i, j, 0);\n if (value > max) max = value;\n }\n }\n newImage.setValueXY(x, y, 0, max);\n }\n }\n return newImage;\n}\n\nfunction dilateOnceGreyOnlyOnes(img, newImage, kernelWidth, kernelHeight) {\n const radiusX = (kernelWidth - 1) / 2;\n const radiusY = (kernelHeight - 1) / 2;\n\n const maxList = [];\n for (let x = 0; x < img.width; x++) {\n maxList.push(0);\n }\n\n for (let y = 0; y < img.height; y++) {\n for (let x = 0; x < img.width; x++) {\n let max = 0;\n for (\n let h = Math.max(0, y - radiusY);\n h < Math.min(img.height, y + radiusY + 1);\n h++\n ) {\n const value = img.getValueXY(x, h, 0);\n if (value > max) {\n max = value;\n }\n }\n maxList[x] = max;\n }\n\n for (let x = 0; x < img.width; x++) {\n let max = 0;\n for (\n let i = Math.max(0, x - radiusX);\n i < Math.min(img.width, x + radiusX + 1);\n i++\n ) {\n if (maxList[i] > max) {\n max = maxList[i];\n }\n }\n newImage.setValueXY(x, y, 0, max);\n }\n }\n return newImage;\n}\n\nfunction dilateOnceBinary(img, newImage, kernel) {\n const kernelWidth = kernel.length;\n const kernelHeight = kernel[0].length;\n let radiusX = (kernelWidth - 1) / 2;\n let radiusY = (kernelHeight - 1) / 2;\n for (let y = 0; y < img.height; y++) {\n for (let x = 0; x < img.width; x++) {\n let max = 0;\n intLoop: for (let jj = 0; jj < kernelHeight; jj++) {\n for (let ii = 0; ii < kernelWidth; ii++) {\n if (kernel[ii][jj] !== 1) continue;\n let i = ii - radiusX + x;\n let j = jj - radiusY + y;\n if (j < 0 || i < 0 || i >= img.width || j >= img.height) continue;\n const value = img.getBitXY(i, j);\n if (value === 1) {\n max = 1;\n break intLoop;\n }\n }\n }\n if (max === 1) {\n newImage.setBitXY(x, y);\n }\n }\n }\n return newImage;\n}\n\nfunction dilateOnceBinaryOnlyOnes(img, newImage, kernelWidth, kernelHeight) {\n const radiusX = (kernelWidth - 1) / 2;\n const radiusY = (kernelHeight - 1) / 2;\n\n const maxList = [];\n for (let x = 0; x < img.width; x++) {\n maxList.push(1);\n }\n\n for (let y = 0; y < img.height; y++) {\n for (let x = 0; x < img.width; x++) {\n maxList[x] = 0;\n for (\n let h = Math.max(0, y - radiusY);\n h < Math.min(img.height, y + radiusY + 1);\n h++\n ) {\n if (img.getBitXY(x, h) === 1) {\n maxList[x] = 1;\n break;\n }\n }\n }\n\n for (let x = 0; x < img.width; x++) {\n if (newImage.getBitXY(x, y) === 1) continue;\n for (\n let i = Math.max(0, x - radiusX);\n i < Math.min(img.width, x + radiusX + 1);\n i++\n ) {\n if (maxList[i] === 1) {\n newImage.setBitXY(x, y);\n break;\n }\n }\n }\n }\n return newImage;\n}\n","import Image from '../Image';\n\n/**\n * Erosion is one of two fundamental operations (with dilatation) in morphological\n * image processing from which all other morphological operations are based (from Wikipedia).\n * Replaces each value with it's local minimum among the pixels with a kernel value of 1.\n * http://docs.opencv.org/2.4/doc/tutorials/imgproc/erosion_dilatation/erosion_dilatation.html\n * https://en.wikipedia.org/wiki/Erosion_(morphology)\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Array>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]\n * @param {number} [options.iterations=1] - The number of successive erosions\n * @return {Image}\n */\nexport default function erode(options = {}) {\n let {\n kernel = [\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n ],\n iterations = 1,\n } = options;\n\n this.checkProcessable('erode', {\n bitDepth: [1, 8, 16],\n components: 1,\n alpha: 0,\n });\n if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {\n throw new TypeError(\n 'erode: The number of rows and columns of the kernel must be odd',\n );\n }\n\n let onlyOnes = true;\n outer: for (const row of kernel) {\n for (const value of row) {\n if (value !== 1) {\n onlyOnes = false;\n break outer;\n }\n }\n }\n\n let result = this;\n for (let i = 0; i < iterations; i++) {\n if (this.bitDepth === 1) {\n if (onlyOnes) {\n const newImage = result.clone();\n result = erodeOnceBinaryOnlyOnes(\n result,\n newImage,\n kernel.length,\n kernel[0].length,\n );\n } else {\n const newImage = Image.createFrom(result);\n result = erodeOnceBinary(result, newImage, kernel);\n }\n } else if (onlyOnes) {\n const newImage = Image.createFrom(result);\n result = erodeOnceGreyOnlyOnes(\n result,\n newImage,\n kernel.length,\n kernel[0].length,\n );\n } else {\n const newImage = Image.createFrom(result);\n result = erodeOnceGrey(result, newImage, kernel);\n }\n }\n return result;\n}\n\nfunction erodeOnceGrey(img, newImage, kernel) {\n const kernelWidth = kernel.length;\n const kernelHeight = kernel[0].length;\n let radiusX = (kernelWidth - 1) / 2;\n let radiusY = (kernelHeight - 1) / 2;\n for (let y = 0; y < img.height; y++) {\n for (let x = 0; x < img.width; x++) {\n let min = img.maxValue;\n for (let jj = 0; jj < kernelHeight; jj++) {\n for (let ii = 0; ii < kernelWidth; ii++) {\n if (kernel[ii][jj] !== 1) continue;\n let i = ii - radiusX + x;\n let j = jj - radiusY + y;\n if (i < 0 || j < 0 || i >= img.width || j >= img.height) continue;\n const value = img.getValueXY(i, j, 0);\n if (value < min) min = value;\n }\n }\n newImage.setValueXY(x, y, 0, min);\n }\n }\n return newImage;\n}\n\nfunction erodeOnceGreyOnlyOnes(img, newImage, kernelWidth, kernelHeight) {\n const radiusX = (kernelWidth - 1) / 2;\n const radiusY = (kernelHeight - 1) / 2;\n\n const minList = [];\n for (let x = 0; x < img.width; x++) {\n minList.push(0);\n }\n\n for (let y = 0; y < img.height; y++) {\n for (let x = 0; x < img.width; x++) {\n let min = img.maxValue;\n for (\n let h = Math.max(0, y - radiusY);\n h < Math.min(img.height, y + radiusY + 1);\n h++\n ) {\n const value = img.getValueXY(x, h, 0);\n if (value < min) {\n min = value;\n }\n }\n minList[x] = min;\n }\n\n for (let x = 0; x < img.width; x++) {\n let min = img.maxValue;\n for (\n let i = Math.max(0, x - radiusX);\n i < Math.min(img.width, x + radiusX + 1);\n i++\n ) {\n if (minList[i] < min) {\n min = minList[i];\n }\n }\n newImage.setValueXY(x, y, 0, min);\n }\n }\n return newImage;\n}\n\nfunction erodeOnceBinary(img, newImage, kernel) {\n const kernelWidth = kernel.length;\n const kernelHeight = kernel[0].length;\n let radiusX = (kernelWidth - 1) / 2;\n let radiusY = (kernelHeight - 1) / 2;\n for (let y = 0; y < img.height; y++) {\n for (let x = 0; x < img.width; x++) {\n let min = 1;\n intLoop: for (let jj = 0; jj < kernelHeight; jj++) {\n for (let ii = 0; ii < kernelWidth; ii++) {\n if (kernel[ii][jj] !== 1) continue;\n let i = ii - radiusX + x;\n let j = jj - radiusY + y;\n if (j < 0 || i < 0 || i >= img.width || j >= img.height) continue;\n const value = img.getBitXY(i, j);\n if (value === 0) {\n min = 0;\n break intLoop;\n }\n }\n }\n if (min === 1) {\n newImage.setBitXY(x, y);\n }\n }\n }\n return newImage;\n}\n\nfunction erodeOnceBinaryOnlyOnes(img, newImage, kernelWidth, kernelHeight) {\n const radiusX = (kernelWidth - 1) / 2;\n const radiusY = (kernelHeight - 1) / 2;\n\n const minList = [];\n for (let x = 0; x < img.width; x++) {\n minList.push(0);\n }\n\n for (let y = 0; y < img.height; y++) {\n for (let x = 0; x < img.width; x++) {\n minList[x] = 1;\n for (\n let h = Math.max(0, y - radiusY);\n h < Math.min(img.height, y + radiusY + 1);\n h++\n ) {\n if (img.getBitXY(x, h) === 0) {\n minList[x] = 0;\n break;\n }\n }\n }\n\n for (let x = 0; x < img.width; x++) {\n if (newImage.getBitXY(x, y) === 0) continue;\n for (\n let i = Math.max(0, x - radiusX);\n i < Math.min(img.width, x + radiusX + 1);\n i++\n ) {\n if (minList[i] === 0) {\n newImage.clearBitXY(x, y);\n break;\n }\n }\n }\n }\n return newImage;\n}\n","/**\n * In mathematical morphology, opening is the dilation of the erosion of a set A by a structuring element B.\n * Together with closing, the opening serves in computer vision and image processing as a basic workhorse of morphological noise removal.\n * Opening removes small objects from the foreground (usually taken as the bright pixels) of an image,\n * placing them in the background, while closing removes small holes in the foreground, changing small islands of background into foreground. (Wikipedia)\n * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Array>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]\n * @param {number} [options.iterations=1] - Number of iterations of the morphological transform\n * @return {Image}\n */\nexport default function open(options = {}) {\n let {\n kernel = [\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n ],\n iterations = 1,\n } = options;\n\n this.checkProcessable('open', {\n bitDepth: [8, 16],\n components: 1,\n alpha: 0,\n });\n if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {\n throw new TypeError(\n 'open: The number of rows and columns of the kernel must be odd',\n );\n }\n\n let newImage = this;\n for (let i = 0; i < iterations; i++) {\n newImage = newImage.erode({ kernel });\n newImage = newImage.dilate({ kernel });\n }\n return newImage;\n}\n","/**\n * In mathematical morphology, the closing of a set A by a structuring element B is the erosion of the dilation of that set (Wikipedia).\n * In image processing, closing is, together with opening, the basic workhorse of morphological noise removal.\n * Opening removes small objects, while closing removes small holes.\n * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Array>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]\n * @param {number} [options.iterations=1] - Number of iterations of the morphological transform\n * @return {Image}\n */\nexport default function close(options = {}) {\n let {\n kernel = [\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n ],\n iterations = 1,\n } = options;\n\n this.checkProcessable('close', {\n bitDepth: [1, 8, 16],\n components: 1,\n alpha: 0,\n });\n if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {\n throw new TypeError(\n 'close: The number of rows and columns of the kernel must be odd',\n );\n }\n\n let newImage = this;\n for (let i = 0; i < iterations; i++) {\n newImage = newImage.dilate({ kernel }).erode({ kernel });\n }\n return newImage;\n}\n","/**\n * This function is the white top hat (also called top hat). In mathematical morphology and digital image processing,\n * top-hat transform is an operation that extracts small elements and details from given images.\n * The white top-hat transform is defined as the difference between the input image and its opening by some structuring element.\n * Top-hat transforms are used for various image processing tasks, such as feature extraction, background equalization, image enhancement, and others. (Wikipedia)\n * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Array>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]\n * @param {number} [options.iterations=1] - Number of iterations of the morphological transform\n * @return {Image}\n */\nexport default function topHat(options = {}) {\n let {\n kernel = [\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n ],\n iterations = 1,\n } = options;\n\n this.checkProcessable('topHat', {\n bitDepth: [8, 16],\n components: 1,\n alpha: 0,\n });\n if (kernel.length % 2 === 0 || kernel[0].length % 2 === 0) {\n throw new TypeError(\n 'topHat: The number of rows and columns of the kernel must be odd',\n );\n }\n\n let newImage = this;\n for (let i = 0; i < iterations; i++) {\n let openImage = newImage.open({ kernel });\n newImage = openImage.subtractImage(newImage, { absolute: true });\n }\n return newImage;\n}\n","/**\n * This function is the black top hat (also called black hat).\n * In mathematical morphology and digital image processing,\n * top-hat transform is an operation that extracts small elements and details from given images.\n * The black top-hat transform is defined dually as the difference between the closed and the input image.\n * Top-hat transforms are used for various image processing tasks, such as feature extraction, background equalization,\n * image enhancement, and others. (Wikipedia)\n * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Array>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]\n * @param {number} [options.iterations=1] - Number of iterations of the morphological transform\n * @return {Image}\n */\nexport default function blackHat(options = {}) {\n let {\n kernel = [\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n ],\n iterations = 1,\n } = options;\n\n this.checkProcessable('blackHat', {\n bitDepth: [8, 16],\n components: 1,\n alpha: 0,\n });\n if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {\n throw new TypeError(\n 'blackHat: The number of rows and columns of the kernel must be odd',\n );\n }\n\n let newImage = this;\n for (let i = 0; i < iterations; i++) {\n const closeImage = newImage.close({ kernel });\n newImage = closeImage.subtractImage(newImage, { absolute: true });\n }\n return newImage;\n}\n","/**\n * In mathematical morphology and digital image processing, a morphological gradient is the difference between the dilation and the erosion of a given image. It is an image where each pixel value (typically non-negative) indicates the contrast intensity in the close neighborhood of that pixel. It is useful for edge detection and segmentation applications.\n * http://docs.opencv.org/2.4/doc/tutorials/imgproc/opening_closing_hats/opening_closing_hats.html\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Array>} [options.kernel] - The kernel can only have ones and zeros. Default: [[1, 1, 1], [1, 1, 1], [1, 1, 1]]\n * @param {number} [options.iterations=1] - Number of iterations of the morphological transform\n * @return {Image}\n */\nexport default function morphologicalGradient(options = {}) {\n let {\n kernel = [\n [1, 1, 1],\n [1, 1, 1],\n [1, 1, 1],\n ],\n iterations = 1,\n } = options;\n\n this.checkProcessable('morphologicalGradient', {\n bitDepth: [8, 16],\n components: 1,\n alpha: 0,\n });\n if (kernel.columns % 2 === 0 || kernel.rows % 2 === 0) {\n throw new TypeError(\n 'morphologicalGradient: The number of rows and columns of the kernel must be odd',\n );\n }\n\n let newImage = this;\n for (let i = 0; i < iterations; i++) {\n let dilatedImage = newImage.dilate({ kernel });\n let erodedImage = newImage.erode({ kernel });\n newImage = dilatedImage.subtractImage(erodedImage, { absolute: true });\n }\n\n return newImage;\n}\n","// REFERENCES :\n// https://stackoverflow.com/questions/38285229/calculating-aspect-ratio-of-perspective-transform-destination-image/38402378#38402378\n// http://www.corrmap.com/features/homography_transformation.php\n// https://ags.cs.uni-kl.de/fileadmin/inf_ags/3dcv-ws11-12/3DCV_WS11-12_lec04.pdf\n// http://graphics.cs.cmu.edu/courses/15-463/2011_fall/Lectures/morphing.pdf\n\nimport { Matrix, inverse, SingularValueDecomposition } from 'ml-matrix';\n\nimport Image from '../Image';\n\nfunction order4Points(pts) {\n let tl = 0;\n let tr = 0;\n let br = 0;\n let bl = 0;\n\n let minX = pts[0][0];\n let indexMinX = 0;\n\n for (let i = 1; i < pts.length; i++) {\n if (pts[i][0] < minX) {\n minX = pts[i][0];\n indexMinX = i;\n }\n }\n\n let minX2 = pts[(indexMinX + 1) % pts.length][0];\n let indexMinX2 = (indexMinX + 1) % pts.length;\n\n for (let i = 1; i < pts.length; i++) {\n if (pts[i][0] < minX2 && i !== indexMinX) {\n minX2 = pts[i][0];\n indexMinX2 = i;\n }\n }\n\n if (pts[indexMinX2][1] < pts[indexMinX][1]) {\n tl = pts[indexMinX2];\n bl = pts[indexMinX];\n if (indexMinX !== (indexMinX2 + 1) % 4) {\n tr = pts[(indexMinX2 + 1) % 4];\n br = pts[(indexMinX2 + 2) % 4];\n } else {\n tr = pts[(indexMinX2 + 2) % 4];\n br = pts[(indexMinX2 + 3) % 4];\n }\n } else {\n bl = pts[indexMinX2];\n tl = pts[indexMinX];\n if (indexMinX2 !== (indexMinX + 1) % 4) {\n tr = pts[(indexMinX + 1) % 4];\n br = pts[(indexMinX + 2) % 4];\n } else {\n tr = pts[(indexMinX + 2) % 4];\n br = pts[(indexMinX + 3) % 4];\n }\n }\n\n return [tl, tr, br, bl];\n}\n\nfunction distance2Points(p1, p2) {\n return Math.sqrt(Math.pow(p1[0] - p2[0], 2) + Math.pow(p1[1] - p2[1], 2));\n}\n\nfunction crossVect(u, v) {\n let result = [\n u[1] * v[2] - u[2] * v[1],\n u[2] * v[0] - u[0] * v[2],\n u[0] * v[1] - u[1] * v[0],\n ];\n return result;\n}\n\nfunction dotVect(u, v) {\n let result = u[0] * v[0] + u[1] * v[1] + u[2] * v[2];\n return result;\n}\n\nfunction computeWidthAndHeigth(tl, tr, br, bl, widthImage, heightImage) {\n let w = Math.max(distance2Points(tl, tr), distance2Points(bl, br));\n let h = Math.max(distance2Points(tl, bl), distance2Points(tr, br));\n let finalW = 0;\n let finalH = 0;\n let u0 = Math.ceil(widthImage / 2);\n let v0 = Math.ceil(heightImage / 2);\n let arVis = w / h;\n\n let m1 = [tl[0], tl[1], 1];\n let m2 = [tr[0], tr[1], 1];\n let m3 = [bl[0], bl[1], 1];\n let m4 = [br[0], br[1], 1];\n\n let k2 = dotVect(crossVect(m1, m4), m3) / dotVect(crossVect(m2, m4), m3);\n let k3 = dotVect(crossVect(m1, m4), m2) / dotVect(crossVect(m3, m4), m2);\n\n let n2 = [k2 * m2[0] - m1[0], k2 * m2[1] - m1[1], k2 * m2[2] - m1[2]];\n let n3 = [k3 * m3[0] - m1[0], k3 * m3[1] - m1[1], k3 * m3[2] - m1[2]];\n\n let n21 = n2[0];\n let n22 = n2[1];\n let n23 = n2[2];\n\n let n31 = n3[0];\n let n32 = n3[1];\n let n33 = n3[2];\n\n let f =\n (1.0 / (n23 * n33)) *\n (n21 * n31 -\n (n21 * n33 + n23 * n31) * u0 +\n n23 * n33 * u0 * u0 +\n (n22 * n32 - (n22 * n33 + n23 * n32) * v0 + n23 * n33 * v0 * v0));\n if (f >= 0) {\n f = Math.sqrt(f);\n } else {\n f = Math.sqrt(-f);\n }\n\n let A = new Matrix([\n [f, 0, u0],\n [0, f, v0],\n [0, 0, 1],\n ]);\n let At = A.transpose();\n let Ati = inverse(At);\n let Ai = inverse(A);\n\n let n2R = Matrix.rowVector(n2);\n let n3R = Matrix.rowVector(n3);\n\n let arReal = Math.sqrt(\n dotVect(n2R.mmul(Ati).mmul(Ai).to1DArray(), n2) /\n dotVect(n3R.mmul(Ati).mmul(Ai).to1DArray(), n3),\n );\n\n if (arReal === 0 || arVis === 0) {\n finalW = Math.ceil(w);\n finalH = Math.ceil(h);\n } else if (arReal < arVis) {\n finalW = Math.ceil(w);\n finalH = Math.ceil(finalW / arReal);\n } else {\n finalH = Math.ceil(h);\n finalW = Math.ceil(arReal * finalH);\n }\n return [finalW, finalH];\n}\n\nfunction projectionPoint(x, y, a, b, c, d, e, f, g, h, image, channel) {\n let [newX, newY] = [\n (a * x + b * y + c) / (g * x + h * y + 1),\n (d * x + e * y + f) / (g * x + h * y + 1),\n ];\n return image.getValueXY(Math.floor(newX), Math.floor(newY), channel);\n}\n\n/**\n * Transform a quadrilateral into a rectangle\n * @memberof Image\n * @instance\n * @param {Array>} [pts] - Array of the four corners.\n * @param {object} [options]\n * @param {boolean} [options.calculateRatio=true] - true if you want to calculate the aspect ratio \"width x height\" by taking the perspectiv into consideration.\n * @return {Image} The new image, which is a rectangle\n * @example\n * var cropped = image.warpingFourPoints({\n * pts: [[0,0], [100, 0], [80, 50], [10, 50]]\n * });\n */\n\nexport default function warpingFourPoints(pts, options = {}) {\n let { calculateRatio = true } = options;\n\n if (pts.length !== 4) {\n throw new Error(\n `The array pts must have four elements, which are the four corners. Currently, pts have ${pts.length} elements`,\n );\n }\n\n let [pt1, pt2, pt3, pt4] = pts;\n\n let quadrilaterial = [pt1, pt2, pt3, pt4];\n let [tl, tr, br, bl] = order4Points(quadrilaterial);\n let widthRect;\n let heightRect;\n if (calculateRatio) {\n [widthRect, heightRect] = computeWidthAndHeigth(\n tl,\n tr,\n br,\n bl,\n this.width,\n this.height,\n );\n } else {\n widthRect = Math.ceil(\n Math.max(distance2Points(tl, tr), distance2Points(bl, br)),\n );\n heightRect = Math.ceil(\n Math.max(distance2Points(tl, bl), distance2Points(tr, br)),\n );\n }\n let newImage = Image.createFrom(this, {\n width: widthRect,\n height: heightRect,\n });\n\n let [X1, Y1] = tl;\n let [X2, Y2] = tr;\n let [X3, Y3] = br;\n let [X4, Y4] = bl;\n let [x1, y1] = [0, 0];\n let [x2, y2] = [0, widthRect - 1];\n let [x3, y3] = [heightRect - 1, widthRect - 1];\n let [x4, y4] = [heightRect - 1, 0];\n\n let S = new Matrix([\n [x1, y1, 1, 0, 0, 0, -x1 * X1, -y1 * X1],\n [x2, y2, 1, 0, 0, 0, -x2 * X2, -y2 * X2],\n [x3, y3, 1, 0, 0, 0, -x3 * X3, -y1 * X3],\n [x4, y4, 1, 0, 0, 0, -x4 * X4, -y4 * X4],\n [0, 0, 0, x1, y1, 1, -x1 * Y1, -y1 * Y1],\n [0, 0, 0, x2, y2, 1, -x2 * Y2, -y2 * Y2],\n [0, 0, 0, x3, y3, 1, -x3 * Y3, -y3 * Y3],\n [0, 0, 0, x4, y4, 1, -x4 * Y4, -y4 * Y4],\n ]);\n\n let D = Matrix.columnVector([X1, X2, X3, X4, Y1, Y2, Y3, Y4]);\n\n let svd = new SingularValueDecomposition(S);\n let T = svd.solve(D); // solve S*T = D\n let [a, b, c, d, e, f, g, h] = T.to1DArray();\n\n let Xt = new Matrix(heightRect, widthRect);\n\n for (let channel = 0; channel < this.channels; channel++) {\n for (let i = 0; i < heightRect; i++) {\n for (let j = 0; j < widthRect; j++) {\n Xt.set(\n i,\n j,\n projectionPoint(i, j, a, b, c, d, e, f, g, h, this, channel),\n );\n }\n }\n newImage.setMatrix(Xt, { channel: channel });\n }\n\n return newImage;\n}\n","import Image from '../Image';\n\n/**\n * Crops the image\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.x=0] - x coordinate to place the zero of the new image\n * @param {number} [options.y=0] - y coordinate to place the zero of the new image\n * @param {number} [options.width=this.width-x] - width of the new image\n * @param {number} [options.height=this.height-y] - height of the new image\n * @return {Image} The new cropped image\n * @example\n * var cropped = image.crop({\n * x:0,\n * y:0\n * });\n */\nexport default function crop(options = {}) {\n let {\n x = 0,\n y = 0,\n width = this.width - x,\n height = this.height - y,\n } = options;\n\n this.checkProcessable('max', {\n bitDepth: [8, 16],\n });\n\n x = Math.round(x);\n y = Math.round(y);\n width = Math.round(width);\n height = Math.round(height);\n\n if (x > this.width - 1 || y > this.height - 1) {\n throw new RangeError(\n `crop: origin (x:${x}, y:${y}) out of range (${this.width - 1}; ${\n this.height - 1\n })`,\n );\n }\n if (width <= 0 || height <= 0) {\n throw new RangeError(\n `crop: width and height (width:${width}; height:${height}) must be positive numbers`,\n );\n }\n if (x < 0 || y < 0) {\n throw new RangeError(\n `crop: x and y (x:${x}, y:${y}) must be positive numbers`,\n );\n }\n if (width > this.width - x || height > this.height - y) {\n throw new RangeError(\n `crop: (x: ${x}, y:${y}, width:${width}, height:${height}) size is out of range`,\n );\n }\n\n let newImage = Image.createFrom(this, { width, height, position: [x, y] });\n\n let xWidth = width * this.channels;\n let y1 = y + height;\n\n let ptr = 0; // pointer for new array\n\n let jLeft = x * this.channels;\n\n for (let i = y; i < y1; i++) {\n let j = i * this.width * this.channels + jLeft;\n let jL = j + xWidth;\n for (; j < jL; j++) {\n newImage.data[ptr++] = this.data[j];\n }\n }\n\n return newImage;\n}\n","/**\n * Crops the image based on the alpha channel\n * This removes lines and columns where the alpha channel is lower than a threshold value.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.threshold=this.maxValue]\n * @return {Image}\n */\nexport default function cropAlpha(options = {}) {\n this.checkProcessable('cropAlpha', {\n alpha: 1,\n });\n\n const { threshold = this.maxValue } = options;\n\n let left = findLeft(this, threshold, this.components);\n\n if (left === -1) {\n throw new Error(\n 'Could not find new dimensions. Threshold may be too high.',\n );\n }\n\n let top = findTop(this, threshold, this.components, left);\n let bottom = findBottom(this, threshold, this.components, left);\n let right = findRight(this, threshold, this.components, left, top, bottom);\n\n return this.crop({\n x: left,\n y: top,\n width: right - left + 1,\n height: bottom - top + 1,\n });\n}\n\nfunction findLeft(image, threshold, channel) {\n for (let x = 0; x < image.width; x++) {\n for (let y = 0; y < image.height; y++) {\n if (image.getValueXY(x, y, channel) >= threshold) {\n return x;\n }\n }\n }\n return -1;\n}\n\nfunction findTop(image, threshold, channel, left) {\n for (let y = 0; y < image.height; y++) {\n for (let x = left; x < image.width; x++) {\n if (image.getValueXY(x, y, channel) >= threshold) {\n return y;\n }\n }\n }\n return -1;\n}\n\nfunction findBottom(image, threshold, channel, left) {\n for (let y = image.height - 1; y >= 0; y--) {\n for (let x = left; x < image.width; x++) {\n if (image.getValueXY(x, y, channel) >= threshold) {\n return y;\n }\n }\n }\n return -1;\n}\n\nfunction findRight(image, threshold, channel, left, top, bottom) {\n for (let x = image.width - 1; x >= left; x--) {\n for (let y = top; y <= bottom; y++) {\n if (image.getValueXY(x, y, channel) >= threshold) {\n return x;\n }\n }\n }\n return -1;\n}\n","/**\n * Converts a factor value to a number between 0 and 1\n * @private\n * @param {string|number} value\n * @return {number}\n */\nexport function getFactor(value) {\n if (typeof value === 'string') {\n const last = value[value.length - 1];\n value = parseFloat(value);\n if (last === '%') {\n value /= 100;\n }\n }\n return value;\n}\n\n/**\n * We can specify a threshold as \"0.4\", \"40%\" or 123\n * @private\n * @param {string|number} value\n * @param {number} maxValue\n * @return {number}\n */\nexport function getThreshold(value, maxValue) {\n if (!maxValue) {\n throw Error('getThreshold : the maxValue should be specified');\n }\n if (typeof value === 'string') {\n let last = value[value.length - 1];\n if (last !== '%') {\n throw Error(\n 'getThreshold : if the value is a string it must finish by %',\n );\n }\n return (parseFloat(value) / 100) * maxValue;\n } else if (typeof value === 'number') {\n if (value < 1) {\n return value * maxValue;\n }\n return value;\n } else {\n throw Error('getThreshold : the value is not valid');\n }\n}\n\nexport function factorDimensions(factor, width, height) {\n factor = getFactor(factor);\n let newWidth = Math.round(factor * width);\n let newHeight = Math.round(factor * height);\n\n if (newWidth <= 0) {\n newWidth = 1;\n }\n if (newHeight <= 0) {\n newHeight = 1;\n }\n return {\n width: newWidth,\n height: newHeight,\n };\n}\n","export function checkRow(image, row) {\n if (row < 0 || row >= image.height) {\n throw new RangeError(\n `row must be included between 0 and ${\n image.height - 1\n }. Current value: ${row}`,\n );\n }\n}\n\nexport function checkColumn(image, column) {\n if (column < 0 || column >= image.width) {\n throw new RangeError(\n `column must be included between 0 and ${\n image.width - 1\n }. Current value: ${column}`,\n );\n }\n}\n\nexport function checkChannel(image, channel) {\n if (channel < 0 || channel >= image.channels) {\n throw new RangeError(\n `channel must be included between 0 and ${\n image.channels - 1\n }. Current value: ${channel}`,\n );\n }\n}\n\n/**\n * @typedef {('nearestNeighbor'|'bilinear')} InterpolationAlgorithm\n */\nexport const validInterpolations = {\n nearestneighbor: 'nearestNeighbor',\n nearestneighbour: 'nearestNeighbor',\n bilinear: 'bilinear',\n};\n\nexport function checkInterpolation(interpolation) {\n if (typeof interpolation !== 'string') {\n throw new TypeError('interpolation must be a string');\n }\n interpolation = interpolation.toLowerCase();\n if (!validInterpolations[interpolation]) {\n throw new RangeError(`invalid interpolation algorithm: ${interpolation}`);\n }\n return validInterpolations[interpolation];\n}\n","/**\n * Nearest neighbor resizing algorithm\n * @private\n * @param {Image} newImage\n * @param {number} newWidth\n * @param {number} newHeight\n */\nexport default function nearestNeighbor(newImage, newWidth, newHeight) {\n const wRatio = this.width / newWidth;\n const hRatio = this.height / newHeight;\n\n if (this.bitDepth > 1) {\n for (let i = 0; i < newWidth; i++) {\n const w = Math.floor((i + 0.5) * wRatio);\n for (let j = 0; j < newHeight; j++) {\n const h = Math.floor((j + 0.5) * hRatio);\n for (let c = 0; c < this.channels; c++) {\n newImage.setValueXY(i, j, c, this.getValueXY(w, h, c));\n }\n }\n }\n } else {\n for (let i = 0; i < newWidth; i++) {\n const w = Math.floor((i + 0.5) * wRatio);\n for (let j = 0; j < newHeight; j++) {\n const h = Math.floor((j + 0.5) * hRatio);\n if (this.getBitXY(w, h)) {\n newImage.setBitXY(i, j);\n }\n }\n }\n }\n}\n","import { factorDimensions } from '../../../util/converter';\nimport Image from '../../Image';\nimport { validInterpolations, checkInterpolation } from '../../internal/checks';\n\nimport nearestNeighbor from './nearestNeighbor';\n\n/**\n * Resize an image\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.width=this.width] - new width\n * @param {number} [options.height=this.height] - new height\n * @param {number} [options.factor=1] - scaling factor (applied to the new width and height values)\n * @param {InterpolationAlgorithm} [options.interpolation='nearestNeighbor']\n * @param {boolean} [options.preserveAspectRatio=true] - preserve width/height ratio if only one of them is defined\n * @return {Image}\n */\nexport default function resize(options = {}) {\n const {\n factor = 1,\n interpolation = validInterpolations.nearestneighbor,\n preserveAspectRatio = true,\n } = options;\n\n const interpolationToUse = checkInterpolation(interpolation);\n\n let width = options.width;\n let height = options.height;\n\n if (!width) {\n if (height && preserveAspectRatio) {\n width = Math.round(height * (this.width / this.height));\n } else {\n width = this.width;\n }\n }\n if (!height) {\n if (preserveAspectRatio) {\n height = Math.round(width * (this.height / this.width));\n } else {\n height = this.height;\n }\n }\n\n ({ width, height } = factorDimensions(factor, width, height));\n\n if (width === this.width && height === this.height) {\n const newImage = this.clone();\n newImage.position = [0, 0];\n return newImage;\n }\n\n let shiftX = Math.round((this.width - width) / 2);\n let shiftY = Math.round((this.height - height) / 2);\n const newImage = Image.createFrom(this, {\n width,\n height,\n position: [shiftX, shiftY],\n });\n\n switch (interpolationToUse) {\n case validInterpolations.nearestneighbor:\n nearestNeighbor.call(this, newImage, width, height);\n break;\n default:\n throw new Error(\n `unsupported resize interpolation: ${interpolationToUse}`,\n );\n }\n\n return newImage;\n}\n","// based on https://bgrins.github.io/TinyColor/docs/tinycolor.html\n\nimport Image from '../Image';\nimport { RGB, HSV } from '../model/model';\n\n/**\n * Make a copy of the current image and convert the color model to HSV\n * The source image has to be RGB !\n * @memberof Image\n * @instance\n * @return {Image} - New image in HSV color model\n * @example\n * var hsvImage = image.hsv();\n * // we can create one image per channel\n * var channels = hsvImage.split();\n */\nexport default function hsv() {\n this.checkProcessable('hsv', {\n bitDepth: [8, 16],\n alpha: [0, 1],\n colorModel: [RGB],\n });\n\n let newImage = Image.createFrom(this, {\n colorModel: HSV,\n });\n\n let ptr = 0;\n let data = this.data;\n for (let i = 0; i < data.length; i += this.channels) {\n let red = data[i];\n let green = data[i + 1];\n let blue = data[i + 2];\n\n let min = Math.min(red, green, blue);\n let max = Math.max(red, green, blue);\n let delta = max - min;\n let hue = 0;\n let saturation = max === 0 ? 0 : delta / max;\n let value = max;\n\n if (max !== min) {\n switch (max) {\n case red:\n hue = (green - blue) / delta + (green < blue ? 6 : 0);\n break;\n case green:\n hue = (blue - red) / delta + 2;\n break;\n case blue:\n hue = (red - green) / delta + 4;\n break;\n default:\n throw new Error('unreachable');\n }\n hue /= 6;\n }\n\n newImage.data[ptr++] = hue * this.maxValue;\n newImage.data[ptr++] = saturation * this.maxValue;\n newImage.data[ptr++] = value;\n if (this.alpha) {\n newImage.data[ptr++] = data[i + 3];\n }\n }\n\n return newImage;\n}\n","// http://www.easyrgb.com/index.php?X=MATH&H=18#text18\n// check rgbToHsl : https://bgrins.github.io/TinyColor/docs/tinycolor.html\n\nimport Image from '../Image';\nimport { RGB, HSL } from '../model/model';\n\n/**\n * Make a copy of the current image and convert the color model to HSL\n * The source image has to be RGB !\n * @memberof Image\n * @instance\n * @return {Image} - New image in HSL color model\n * @example\n * var hslImage = image.hsl();\n * // we can create one image per channel\n * var channels = hslImage.split();\n */\nexport default function hsl() {\n this.checkProcessable('hsl', {\n bitDepth: [8, 16],\n alpha: [0, 1],\n colorModel: [RGB],\n });\n\n let newImage = Image.createFrom(this, {\n colorModel: HSL,\n });\n\n let threshold = Math.floor(this.maxValue / 2);\n let ptr = 0;\n let data = this.data;\n for (let i = 0; i < data.length; i += this.channels) {\n let red = data[i];\n let green = data[i + 1];\n let blue = data[i + 2];\n\n let max = Math.max(red, green, blue);\n let min = Math.min(red, green, blue);\n let hue = 0;\n let saturation = 0;\n let luminance = (max + min) / 2;\n if (max !== min) {\n let delta = max - min;\n saturation =\n luminance > threshold ? delta / (2 - max - min) : delta / (max + min);\n switch (max) {\n case red:\n hue = (green - blue) / delta + (green < blue ? 6 : 0);\n break;\n case green:\n hue = (blue - red) / delta + 2;\n break;\n case blue:\n hue = (red - green) / delta + 4;\n break;\n default:\n throw new Error('unreachable');\n }\n hue /= 6;\n }\n\n newImage.data[ptr++] = hue * this.maxValue;\n newImage.data[ptr++] = saturation * this.maxValue;\n newImage.data[ptr++] = luminance;\n if (this.alpha) {\n newImage.data[ptr++] = data[i + 3];\n }\n }\n\n return newImage;\n}\n","// http://www.easyrgb.com/index.php?X=MATH&H=18#text18\n// check rgbToHsl : https://bgrins.github.io/TinyColor/docs/tinycolor.html\n\nimport Image from '../Image';\nimport { RGB, CMYK } from '../model/model';\n\n/**\n * Make a copy of the current image and convert the color model to CMYK\n * The source image has to be RGB !\n * @memberof Image\n * @instance\n * @return {Image} - New image in CMYK color model\n * @example\n * var cmykImage = image.cmyk();\n * // we can create one image per channel\n * var channels = cmykImage.split();\n */\nexport default function cmyk() {\n this.checkProcessable('cmyk', {\n bitDepth: [8, 16],\n alpha: [0, 1],\n colorModel: [RGB],\n });\n\n let newImage = Image.createFrom(this, {\n components: 4,\n colorModel: CMYK,\n });\n\n let ptr = 0;\n let data = this.data;\n for (let i = 0; i < data.length; i += this.channels) {\n let red = data[i];\n let green = data[i + 1];\n let blue = data[i + 2];\n\n let black = Math.min(\n this.maxValue - red,\n this.maxValue - green,\n this.maxValue - blue,\n );\n let cyan = (this.maxValue - red - black) / (1 - black / this.maxValue);\n let magenta = (this.maxValue - green - black) / (1 - black / this.maxValue);\n let yellow = (this.maxValue - blue - black) / (1 - black / this.maxValue);\n\n newImage.data[ptr++] = Math.round(cyan);\n newImage.data[ptr++] = Math.round(magenta);\n newImage.data[ptr++] = Math.round(yellow);\n newImage.data[ptr++] = Math.round(black);\n if (this.alpha) {\n newImage.data[ptr++] = data[i + 3];\n }\n }\n\n return newImage;\n}\n","import Image from '../Image';\n\n/**\n * Make a copy of the current image and convert to RGBA 8 bits\n * Those images are the one that are displayed in a canvas.\n * RGB model in 8 bits per channel and containing as well an alpha channel.\n * The source image may be:\n * * a mask (binary image)\n * * a grey image (8, 16 or 32 bits) with or without alpha channel\n * * a color image (8, 16 or 32 bits) with or without alpha channel in with RGB model\n * * when the image is 32 bits, a rescaling is performed from the min and max values\n * * to map values from 0 to 255\n * The conversion is based on {@link Image#getRGBAData}.\n * @memberof Image\n * @instance\n * @return {Image} - New image in RGB color model with alpha channel\n * @example\n * var rgbaImage = image.rgba8();\n */\nexport default function rgba8() {\n return new Image(this.width, this.height, this.getRGBAData(), {\n kind: 'RGBA',\n parent: this,\n });\n}\n","/**\n * @typedef {('luma709'|'luma601'|'maximum'|'minimum'|'average'|'minmax'|'red'|'green'|'blue'|'cyan'|'magenta'|'yellow'|'black'|'hue'|'saturation'|'lightness')} GreyAlgorithm\n */\n\nexport const methods = {\n luma709(red, green, blue) {\n // sRGB\n // return red * 0.2126 + green * 0.7152 + blue * 0.0722;\n // Let's do a little trick ... in order not convert the integer to a double we do\n // the multiplication with integer to reach a total of 32768 and then shift the bits\n // of 15 to the right\n // This does a Math.floor and may lead to small (max 1) difference\n // Same result, > 10% faster on the full grey conversion\n return (red * 6966 + green * 23436 + blue * 2366) >> 15;\n },\n luma601(red, green, blue) {\n // NTSC\n // return this.red * 0.299 + green * 0.587 + blue * 0.114;\n return (red * 9798 + green * 19235 + blue * 3735) >> 15;\n },\n maximum(red, green, blue) {\n return Math.max(red, green, blue);\n },\n minimum(red, green, blue) {\n return Math.min(red, green, blue);\n },\n average(red, green, blue) {\n return ((red + green + blue) / 3) >> 0;\n },\n minmax(red, green, blue) {\n return (Math.max(red, green, blue) + Math.min(red, green, blue)) / 2;\n },\n red(red) {\n return red;\n },\n green(red, green) {\n return green;\n },\n blue(red, green, blue) {\n return blue;\n },\n cyan(red, green, blue, image) {\n let black = methods.black(red, green, blue, image);\n return ((image.maxValue - red - black) / (1 - black / image.maxValue)) >> 0;\n },\n magenta(red, green, blue, image) {\n let black = methods.black(red, green, blue, image);\n return (\n ((image.maxValue - green - black) / (1 - black / image.maxValue)) >> 0\n );\n },\n yellow(red, green, blue, image) {\n let black = methods.black(red, green, blue, image);\n return (\n ((image.maxValue - blue - black) / (1 - black / image.maxValue)) >> 0\n );\n },\n black(red, green, blue, image) {\n return Math.min(\n image.maxValue - red,\n image.maxValue - green,\n image.maxValue - blue,\n );\n },\n hue(red, green, blue, image) {\n let min = methods.min(red, green, blue);\n let max = methods.max(red, green, blue);\n if (max === min) {\n return 0;\n }\n let hue = 0;\n let delta = max - min;\n\n switch (max) {\n case red:\n hue = (green - blue) / delta + (green < blue ? 6 : 0);\n break;\n case green:\n hue = (blue - red) / delta + 2;\n break;\n case blue:\n hue = (red - green) / delta + 4;\n break;\n default:\n throw new Error('unreachable');\n }\n return ((hue / 6) * image.maxValue) >> 0;\n },\n saturation(red, green, blue, image) {\n // from HSV model\n let min = methods.min(red, green, blue);\n let max = methods.max(red, green, blue);\n let delta = max - min;\n return max === 0 ? 0 : (delta / max) * image.maxValue;\n },\n lightness(red, green, blue) {\n let min = methods.min(red, green, blue);\n let max = methods.max(red, green, blue);\n return (max + min) / 2;\n },\n};\n\nObject.defineProperty(methods, 'luminosity', {\n enumerable: false,\n value: methods.lightness,\n});\nObject.defineProperty(methods, 'luminance', {\n enumerable: false,\n value: methods.lightness,\n});\nObject.defineProperty(methods, 'min', {\n enumerable: false,\n value: methods.minimum,\n});\nObject.defineProperty(methods, 'max', {\n enumerable: false,\n value: methods.maximum,\n});\nObject.defineProperty(methods, 'brightness', {\n enumerable: false,\n value: methods.maximum,\n});\n\nexport const names = {};\nObject.keys(methods).forEach((name) => {\n names[name] = name;\n});\n","import { clamp } from '../internal/clamp';\nimport { getOutputImage } from '../internal/getOutputImage';\nimport { GREY } from '../model/model';\n\nimport { methods } from './greyAlgorithms';\n\n/**\n * Call back that converts the RGB channels to grey. It will be clamped after.\n * @callback GreyAlgorithmCallback\n * @param {number} red - value of the red channel\n * @param {number} green - value of the green channel\n * @param {number} blue - value of the blue channel\n * @return {number} value of the grey channel\n */\n\n/**\n * Converts the current image to greyscale.\n * The source image has to be RGB.\n * If there is an alpha channel we need to decide what to do:\n * * keepAlpha : we will keep the alpha channel and you will get a GREY / A image\n * * mergeAlpha : we will multiply each pixel of the image by the alpha\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {GreyAlgorithm|GreyAlgorithmCallback} [options.algorithm='luma709'] - Algorithm to get the grey value from RGB values\n * @param {boolean} [options.keepAlpha=false] - If true, the RGB values are treated\n * separately from the alpha channel and the method returns a GREYA image.\n * @param {boolean} [options.mergeAlpha=true] - If true, the alpha channel will be used to scale the grey pixel.\n * @param {Image} [options.out]\n * @return {Image}\n */\nexport default function grey(options = {}) {\n let { algorithm = 'luma709', keepAlpha = false, mergeAlpha = true } = options;\n\n if (typeof algorithm !== 'string' && typeof algorithm !== 'function') {\n throw new TypeError('algorithm must be a string or a function');\n }\n\n this.checkProcessable('grey', {\n bitDepth: [8, 16],\n alpha: [0, 1],\n });\n\n if (this.components === 1) {\n algorithm = 'red'; // actually we just take the first channel if it is a grey image\n }\n\n keepAlpha &= this.alpha;\n mergeAlpha &= this.alpha;\n if (keepAlpha) {\n mergeAlpha = false;\n }\n\n let newImage = getOutputImage(this, options, {\n components: 1,\n alpha: keepAlpha,\n colorModel: GREY,\n });\n\n let method;\n if (typeof algorithm === 'function') {\n method = algorithm;\n } else {\n method = methods[algorithm.toLowerCase()];\n if (!method) {\n throw new Error(`unsupported grey algorithm: ${algorithm}`);\n }\n }\n\n let ptr = 0;\n for (let i = 0; i < this.data.length; i += this.channels) {\n if (mergeAlpha) {\n newImage.data[ptr++] = clamp(\n (method(this.data[i], this.data[i + 1], this.data[i + 2], this) *\n this.data[i + this.components]) /\n this.maxValue,\n this,\n );\n } else {\n newImage.data[ptr++] = clamp(\n method(this.data[i], this.data[i + 1], this.data[i + 2], this),\n this,\n );\n if (newImage.alpha) {\n newImage.data[ptr++] = this.data[i + this.components];\n }\n }\n }\n\n return newImage;\n}\n","/*\n *\n * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html.\n * Huang: Implements Huang's fuzzy thresholding method: Huang, L-K & Wang, M-J J (1995),\n * \"Image thresholding by minimizing the measure of fuzziness\", Pattern Recognition 28(1): 41-51\n *\n */\n\nexport default function huang(histogram) {\n /* Determine the first non-zero bin */\n let firstBin = 0;\n for (let ih = 0; ih < histogram.length; ih++) {\n if (histogram[ih] !== 0) {\n firstBin = ih;\n break;\n }\n }\n\n /* Determine the last non-zero bin */\n let lastBin = histogram.length - 1;\n for (let ih = histogram.length - 1; ih >= firstBin; ih--) {\n if (histogram[ih] !== 0) {\n lastBin = ih;\n break;\n }\n }\n\n let term = 1.0 / (lastBin - firstBin);\n let mu0 = new Array(histogram.length);\n let sumPix = 0;\n let numPix = 0;\n for (let ih = firstBin; ih < histogram.length; ih++) {\n sumPix += ih * histogram[ih];\n numPix += histogram[ih];\n mu0[ih] = sumPix / numPix;\n }\n\n let mu1 = new Array(histogram.length);\n sumPix = numPix = 0;\n for (let ih = lastBin; ih > 0; ih--) {\n sumPix += ih * histogram[ih];\n numPix += histogram[ih];\n mu1[ih - 1] = sumPix / numPix;\n }\n\n /* Determine the threshold that minimizes the fuzzy entropy*/\n let threshold = -1;\n let minEnt = Number.MAX_VALUE;\n for (let it = 0; it < histogram.length; it++) {\n let ent = 0;\n let muX;\n for (let ih = 0; ih <= it; ih++) {\n /* Equation (4) in Ref. 1 */\n muX = 1 / (1 + term * Math.abs(ih - mu0[it]));\n if (!(muX < 1e-6 || muX > 0.999999)) {\n /* Equation (6) & (8) in Ref. 1 */\n ent +=\n histogram[ih] *\n (-muX * Math.log(muX) - (1 - muX) * Math.log(1 - muX));\n }\n }\n\n for (let ih = it + 1; ih < histogram.length; ih++) {\n /* Equation (4) in Ref. 1 */\n muX = 1 / (1 + term * Math.abs(ih - mu1[it]));\n if (!(muX < 1e-6 || muX > 0.999999)) {\n /* Equation (6) & (8) in Ref. 1 */\n ent +=\n histogram[ih] *\n (-muX * Math.log(muX) - (1 - muX) * Math.log(1 - muX));\n }\n }\n\n if (ent < minEnt) {\n minEnt = ent;\n threshold = it;\n }\n }\n return threshold;\n}\n","/*\n *\n * see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java\n * Intermodes: This assumes a bimodal histogram. Implements the thresholding Prewitt, JMS & Mendelsohn, ML (1966),\n * \"The analysis of cell images\", Annals of the NewYork Academy of Sciences 128: 1035-1053\n *\n */\n\nexport default function intermodes(histogram) {\n let iHisto = histogram.slice();\n let iter = 0;\n while (!bimodalTest(iHisto)) {\n // smooth with a 3 point running mean filter\n let previous = 0;\n let current = 0;\n let next = iHisto[0];\n for (let i = 0; i < histogram.length - 1; i++) {\n previous = current;\n current = next;\n next = iHisto[i + 1];\n iHisto[i] = (previous + current + next) / 3;\n }\n iHisto[histogram.length - 1] = (current + next) / 3;\n iter++;\n if (iter > 10000) {\n throw new Error('Intermodes Threshold not found after 10000 iterations');\n }\n }\n\n // The threshold is the mean between the two peaks.\n let tt = 0;\n for (let i = 1; i < histogram.length - 1; i++) {\n if (iHisto[i - 1] < iHisto[i] && iHisto[i + 1] < iHisto[i]) {\n tt += i;\n }\n }\n return Math.floor(tt / 2.0);\n}\n\nfunction bimodalTest(iHisto) {\n let b = false;\n let modes = 0;\n\n for (let k = 1; k < iHisto.length - 1; k++) {\n if (iHisto[k - 1] < iHisto[k] && iHisto[k + 1] < iHisto[k]) {\n modes++;\n if (modes > 2) {\n return false;\n }\n }\n }\n if (modes === 2) {\n b = true;\n }\n return b;\n}\n","/*\n * see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java\n * Isodata: Ridler, TW & Calvard, S (1978), \"Picture thresholding using an iterative selection method\"\n * IEEE Transactions on Systems, Man and Cybernetics 8: 630-632.\n *\n */\nexport default function isodata(histogram) {\n let l; // the average grey value of pixels with intensities < g\n let toth; // the the average grey value of pixels with intensities > g\n let totl; // the total the average grey value of pixels with intensities < g\n let h; // the average grey value of pixels with intensities > g\n let g = 0; // threshold value\n\n for (let i = 1; i < histogram.length; i++) {\n if (histogram[i] > 0) {\n g = i + 1;\n break;\n }\n }\n\n while (true) {\n l = 0;\n totl = 0;\n for (let i = 0; i < g; i++) {\n totl = totl + histogram[i];\n l = l + histogram[i] * i;\n }\n h = 0;\n toth = 0;\n for (let i = g + 1; i < histogram.length; i++) {\n toth += histogram[i];\n h += histogram[i] * i;\n }\n if (totl > 0 && toth > 0) {\n l /= totl;\n h /= toth;\n if (g === Math.round((l + h) / 2.0)) {\n break;\n }\n }\n g++;\n if (g > histogram.length - 2) {\n throw new Error('Threshold not found');\n }\n }\n return g;\n}\n","/*\n * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html\n * The method is present in: Implements Li's Minimum Cross Entropy thresholding method\n * This implementation is based on the iterative version (Ref. 2nd reference below) of the algorithm.\n * 1) Li, CH & Lee, CK (1993), \"Minimum Cross Entropy Thresholding\", Pattern Recognition 26(4): 61 625\n * 2) Li, CH & Tam, PKS (1998), \"An Iterative Algorithm for Minimum Cross Entropy Thresholding\",\n * Pattern Recognition Letters 18(8): 771-776\n * 3) Sezgin, M & Sankur, B (2004), \"Survey over Image Thresholding Techniques and Quantitative Performance\n * Evaluation\",Journal of Electronic Imaging 13(1): 146-165\n * @param histogram - the histogram of the image\n * @param total - the number of pixels in the image\n * @returns {number} - the threshold\n */\n\nexport default function li(histogram, total) {\n let threshold;\n let sumBack; /* sum of the background pixels at a given threshold */\n let sumObj; /* sum of the object pixels at a given threshold */\n let numBack; /* number of background pixels at a given threshold */\n let numObj; /* number of object pixels at a given threshold */\n let oldThresh;\n let newThresh;\n let meanBack; /* mean of the background pixels at a given threshold */\n let meanObj; /* mean of the object pixels at a given threshold */\n let mean; /* mean gray-level in the image */\n let tolerance; /* threshold tolerance */\n let temp;\n tolerance = 0.5;\n\n /* Calculate the mean gray-level */\n mean = 0.0;\n for (let ih = 0; ih < histogram.length; ih++) {\n mean += ih * histogram[ih];\n }\n\n mean /= total;\n /* Initial estimate */\n newThresh = mean;\n\n do {\n oldThresh = newThresh;\n threshold = (oldThresh + 0.5) | 0; /* range */\n\n /* Calculate the means of background and object pixels */\n /* Background */\n sumBack = 0;\n numBack = 0;\n\n for (let ih = 0; ih <= threshold; ih++) {\n sumBack += ih * histogram[ih];\n numBack += histogram[ih];\n }\n meanBack = numBack === 0 ? 0.0 : sumBack / numBack;\n\n /* Object */\n sumObj = 0;\n numObj = 0;\n for (let ih = threshold + 1; ih < histogram.length; ih++) {\n sumObj += ih * histogram[ih];\n numObj += histogram[ih];\n }\n meanObj = numObj === 0 ? 0.0 : sumObj / numObj;\n temp = (meanBack - meanObj) / (Math.log(meanBack) - Math.log(meanObj));\n\n if (temp < -Number.EPSILON) {\n newThresh = (temp - 0.5) | 0;\n } else {\n newThresh = (temp + 0.5) | 0;\n }\n /* Stop the iterations when the difference between the\n new and old threshold values is less than the tolerance */\n } while (Math.abs(newThresh - oldThresh) > tolerance);\n\n return threshold;\n}\n","/*\n * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html\n * The method is present in: Implements Kapur-Sahoo-Wong (Maximum Entropy) thresholding method:\n * Kapur, JN; Sahoo, PK & Wong, ACK (1985), \"A New Method for Gray-Level Picture Thresholding Using the Entropy of the Histogram\",\n * Graphical Models and Image Processing 29(3): 273-285\n * @param histogram - the histogram of the image\n * total - the number of pixels in the image\n * @returns {number} - the threshold\n */\n\nexport default function maxEntropy(histogram, total) {\n let normHisto = new Array(histogram.length); // normalized histogram\n for (let ih = 0; ih < histogram.length; ih++) {\n normHisto[ih] = histogram[ih] / total;\n }\n\n let P1 = new Array(histogram.length); // cumulative normalized histogram\n let P2 = new Array(histogram.length);\n P1[0] = normHisto[0];\n P2[0] = 1.0 - P1[0];\n\n for (let ih = 1; ih < histogram.length; ih++) {\n P1[ih] = P1[ih - 1] + normHisto[ih];\n P2[ih] = 1.0 - P1[ih];\n }\n\n /* Determine the first non-zero bin */\n let firstBin = 0;\n for (let ih = 0; ih < histogram.length; ih++) {\n if (Math.abs(P1[ih]) >= Number.EPSILON) {\n firstBin = ih;\n break;\n }\n }\n\n /* Determine the last non-zero bin */\n let lastBin = histogram.length - 1;\n for (let ih = histogram.length - 1; ih >= firstBin; ih--) {\n if (Math.abs(P2[ih]) >= Number.EPSILON) {\n lastBin = ih;\n break;\n }\n }\n\n // Calculate the total entropy each gray-level\n // and find the threshold that maximizes it\n let threshold = -1;\n let totEnt; // total entropy\n let maxEnt = Number.MIN_VALUE; // max entropy\n let entBack; // entropy of the background pixels at a given threshold\n let entObj; // entropy of the object pixels at a given threshold\n\n for (let it = firstBin; it <= lastBin; it++) {\n /* Entropy of the background pixels */\n entBack = 0.0;\n for (let ih = 0; ih <= it; ih++) {\n if (histogram[ih] !== 0) {\n entBack -= (normHisto[ih] / P1[it]) * Math.log(normHisto[ih] / P1[it]);\n }\n }\n\n /* Entropy of the object pixels */\n entObj = 0.0;\n for (let ih = it + 1; ih < histogram.length; ih++) {\n if (histogram[ih] !== 0) {\n entObj -= (normHisto[ih] / P2[it]) * Math.log(normHisto[ih] / P2[it]);\n }\n }\n\n /* Total entropy */\n totEnt = entBack + entObj;\n\n if (maxEnt < totEnt) {\n maxEnt = totEnt;\n threshold = it;\n }\n }\n return threshold;\n}\n","/*\n * The method is present in: Uses the mean of grey levels as the threshold. It is described in:\n * Glasbey, CA (1993), \"An analysis of histogram-based thresholding algorithms\",\n * CVGIP: Graphical Models and Image Processing 55: 532-537\n * @param histogram - the histogram of the image\n * @param total - the number of pixels in the image\n * @returns {number} - the threshold\n */\n\nexport default function mean(histogram, total) {\n let sum = 0;\n for (let i = 0; i < histogram.length; i++) {\n sum += i * histogram[i];\n }\n return Math.floor(sum / total);\n}\n","/*\n * see http://rsb.info.nih.gov/ij/developer/source/ij/process/AutoThresholder.java.html\n * The method is present in: An iterative implementation of Kittler and Illingworth's Minimum Error\n * thresholding:Kittler, J & Illingworth, J (1986), \"Minimum error thresholding\", Pattern Recognition 19: 41-47\n * @param histogram - the histogram of the image\n * @param total - the number of pixels in the image\n * @returns {number} - the threshold\n */\n\nexport default function minError(histogram, total) {\n let threshold;\n let Tprev = -2;\n let mu, nu, p, q, sigma2, tau2, w0, w1, w2, sqterm, temp;\n\n /* Calculate the mean gray-level */\n let mean = 0.0;\n for (let ih = 0; ih < histogram.length; ih++) {\n mean += ih * histogram[ih];\n }\n\n mean /= total;\n\n threshold = mean;\n\n while (threshold !== Tprev) {\n // Calculate some statistics.\n let sumA1 = sumA(histogram, threshold);\n let sumA2 = sumA(histogram, histogram.length - 1);\n let sumB1 = sumB(histogram, threshold);\n let sumB2 = sumB(histogram, histogram.length - 1);\n let sumC1 = sumC(histogram, threshold);\n let sumC2 = sumC(histogram, histogram.length - 1);\n\n mu = sumB1 / sumA1;\n nu = (sumB2 - sumB1) / (sumA2 - sumA1);\n p = sumA1 / sumA2;\n q = (sumA2 - sumA1) / sumA2;\n sigma2 = sumC1 / sumA1 - mu * mu;\n tau2 = (sumC2 - sumC1) / (sumA2 - sumA1) - nu * nu;\n\n // The terms of the quadratic equation to be solved.\n w0 = 1.0 / sigma2 - 1.0 / tau2;\n w1 = mu / sigma2 - nu / tau2;\n w2 =\n (mu * mu) / sigma2 -\n (nu * nu) / tau2 +\n Math.log10((sigma2 * (q * q)) / (tau2 * (p * p)));\n\n // If the next threshold would be imaginary, return with the current one.\n sqterm = w1 * w1 - w0 * w2;\n if (sqterm < 0) {\n return threshold;\n }\n\n // The updated threshold is the integer part of the solution of the quadratic equation.\n Tprev = threshold;\n temp = (w1 + Math.sqrt(sqterm)) / w0;\n\n if (isNaN(temp)) {\n threshold = Tprev;\n } else {\n threshold = Math.floor(temp);\n }\n }\n return threshold;\n}\n\n// aux func\n\nfunction sumA(y, j) {\n let x = 0;\n for (let i = 0; i <= j; i++) {\n x += y[i];\n }\n return x;\n}\n\nfunction sumB(y, j) {\n let x = 0;\n for (let i = 0; i <= j; i++) {\n x += i * y[i];\n }\n return x;\n}\n\nfunction sumC(y, j) {\n let x = 0;\n for (let i = 0; i <= j; i++) {\n x += i * i * y[i];\n }\n return x;\n}\n","// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java\n// J. M. S. Prewitt and M. L. Mendelsohn, \"The analysis of cell images,\" in\n// Annals of the New York Academy of Sciences, vol. 128, pp. 1035-1053, 1966.\n// ported to ImageJ plugin by G.Landini from Antti Niemisto's Matlab code (GPL)\n// Original Matlab code Copyright (C) 2004 Antti Niemisto\n// See http://www.cs.tut.fi/~ant/histthresh/ for an excellent slide presentation\n// and the original Matlab code\nexport default function minimum(histogram) {\n if (histogram.length < 2) {\n // validate that the histogram has at least two color values\n return 0;\n }\n let iterations = 0; // number of iterations of the smoothing process\n let threshold = -1;\n let max = -1; // maximum color value with a greater number of pixels to 0\n let histogramCopy = new Array(histogram.length); // a copy of the histogram\n for (let i = 0; i < histogram.length; i++) {\n histogramCopy[i] = histogram[i];\n if (histogram[i] > 0) {\n max = i;\n }\n }\n while (!bimodalTest(histogramCopy)) {\n histogramCopy = smoothed(histogramCopy);\n iterations++;\n if (iterations > 10000) {\n // if they occur more than 10000 iterations it returns -1\n return threshold;\n }\n }\n threshold = minimumBetweenPeeks(histogramCopy, max);\n return threshold;\n}\nfunction smoothed(histogram) {\n // Smooth with a 3 point running mean filter\n let auHistogram = new Array(histogram.length); // a copy of the histograma for the smoothing process\n for (let i = 1; i < histogram.length - 1; i++) {\n auHistogram[i] = (histogram[i - 1] + histogram[i] + histogram[i + 1]) / 3;\n }\n auHistogram[0] = (histogram[0] + histogram[1]) / 3;\n auHistogram[histogram.length - 1] =\n (histogram[histogram.length - 2] + histogram[histogram.length - 1]) / 3;\n return auHistogram;\n}\nfunction minimumBetweenPeeks(histogramBimodal, max) {\n let threshold;\n for (let i = 1; i < max; i++) {\n if (\n histogramBimodal[i - 1] > histogramBimodal[i] &&\n histogramBimodal[i + 1] >= histogramBimodal[i]\n ) {\n threshold = i;\n break;\n }\n }\n return threshold;\n}\nfunction bimodalTest(histogram) {\n // It is responsible for determining if a histogram is bimodal\n let len = histogram.length;\n let isBimodal = false;\n let peaks = 0;\n for (let k = 1; k < len - 1; k++) {\n if (histogram[k - 1] < histogram[k] && histogram[k + 1] < histogram[k]) {\n peaks++;\n if (peaks > 2) {\n return false;\n }\n }\n }\n if (peaks === 2) {\n isBimodal = true;\n }\n return isBimodal;\n}\n","// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java\n// W. Tsai, \"Moment-preserving thresholding: a new approach,\" Computer Vision,\n// Graphics, and Image Processing, vol. 29, pp. 377-393, 1985.\n// Ported to ImageJ plugin by G.Landini from the the open source project FOURIER 0.8\n// by M. Emre Celebi , Department of Computer Science, Louisiana State University in Shreveport\n// Shreveport, LA 71115, USA\n// http://sourceforge.net/projects/fourier-ipal\n// http://www.lsus.edu/faculty/~ecelebi/fourier.htm\nexport default function moments(histogram, total) {\n // moments\n let m0 = 1.0;\n let m1 = 0.0;\n let m2 = 0.0;\n let m3 = 0.0;\n let sum = 0.0;\n let p0;\n let cd, c0, c1, z0, z1; /* auxiliary variables */\n let threshold = -1;\n let histogramLength = histogram.length;\n let normalizedHistogram = new Array(histogramLength);\n for (let i = 0; i < histogramLength; i++) {\n normalizedHistogram[i] = histogram[i] / total;\n }\n /* Calculate the first, second, and third order moments */\n for (let i = 0; i < histogramLength; i++) {\n m1 += i * normalizedHistogram[i];\n m2 += i * i * normalizedHistogram[i];\n m3 += i * i * i * normalizedHistogram[i];\n }\n /*\n First 4 moments of the gray-level image should match the first 4 moments\n of the target binary image. This leads to 4 equalities whose solutions\n are given in the Appendix of Ref. 1\n */\n cd = m0 * m2 - m1 * m1; // determinant of the matriz of hankel for moments 2x2\n c0 = (-m2 * m2 + m1 * m3) / cd;\n c1 = (m0 * -m3 + m2 * m1) / cd;\n // new two gray values where z0 p0) {\n threshold = i;\n break;\n }\n }\n return threshold;\n}\n","/*\n * The method is present in: Otsu, N (1979), \"A threshold selection method from gray-level histograms\", IEEE Trans. Sys., Man., Cyber. 9: 62-66\n * The Otsu implementation is based on: https://en.wikipedia.org/wiki/Otsu's_method\n * @param histogram - the histogram of the image\n * @returns {number} - the threshold\n */\n\nexport default function otsu(histogramCounts, total) {\n let sumB = 0;\n let wB = 0;\n let maximum = 0;\n let level = 0;\n\n let sum1 = 0;\n for (let i = 0; i < histogramCounts.length; i++) {\n sum1 += i * histogramCounts[i];\n }\n\n for (let ii = 0; ii < histogramCounts.length; ii++) {\n wB = wB + histogramCounts[ii];\n const wF = total - wB;\n if (wB === 0 || wF === 0) {\n continue;\n }\n sumB = sumB + ii * histogramCounts[ii];\n const mF = (sum1 - sumB) / wF;\n const between = wB * wF * (sumB / wB - mF) * (sumB / wB - mF);\n if (between >= maximum) {\n level = ii;\n maximum = between;\n }\n }\n\n return level;\n}\n","// See http://imagej.nih.gov/ij/download/tools/source/ij/process/AutoThresholder.java\n// W. Doyle, \"Operation useful for similarity-invariant pattern recognition,\"\n// Journal of the Association for Computing Machinery, vol. 9,pp. 259-267, 1962.\n// ported to ImageJ plugin by G.Landini from Antti Niemisto's Matlab code (GPL)\n// Original Matlab code Copyright (C) 2004 Antti Niemisto\n// See http://www.cs.tut.fi/~ant/histthresh/ for an excellent slide presentation\n// and the original Matlab code.\nexport default function percentile(histogram) {\n let threshold = -1;\n let percentile = 0.5; // default fraction of foreground pixels\n let avec = new Array(histogram.length);\n\n let total = partialSum(histogram, histogram.length - 1);\n let temp = 1.0;\n\n for (let i = 0; i < histogram.length; i++) {\n avec[i] = Math.abs(partialSum(histogram, i) / total - percentile);\n if (avec[i] < temp) {\n temp = avec[i];\n threshold = i;\n }\n }\n\n return threshold;\n}\n\nfunction partialSum(histogram, endIndex) {\n let x = 0;\n for (let i = 0; i <= endIndex; i++) {\n x += histogram[i];\n }\n return x;\n}\n","// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java\n// Kapur J.N., Sahoo P.K., and Wong A.K.C. (1985) \"A New Method for\n// Gray-Level Picture Thresholding Using the Entropy of the Histogram\"\n// Graphical Models and Image Processing, 29(3): 273-285\n// M. Emre Celebi\n// 06.15.2007\n// Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines\nexport default function renyiEntropy(histogram, total) {\n let optThreshold; // Optimal threshold\n let firstBin; // First non-zero bin\n let lastBin; // last non-zero bin\n\n let normHisto = new Array(histogram.length); // normalized histogram\n let P1 = new Array(histogram.length); // acumulative normalized histogram\n let P2 = new Array(histogram.length); // acumulative normalized histogram\n\n // Entropy Variables\n let threshold1 = 0;\n let threshold2 = 0;\n let threshold3 = 0;\n let maxEnt1 = 0.0;\n let maxEnt2 = 0.0;\n let maxEnt3 = 0.0;\n let alpha2 = 0.5;\n let term2 = 1.0 / (1.0 - alpha2);\n let alpha3 = 2.0;\n let term3 = 1.0 / (1.0 - alpha3);\n\n for (let ih = 0; ih < histogram.length; ih++) {\n normHisto[ih] = histogram[ih] / total;\n }\n\n P1[0] = normHisto[0];\n P2[0] = 1.0 - P1[0];\n for (let ih = 1; ih < histogram.length; ih++) {\n P1[ih] = P1[ih - 1] + normHisto[ih];\n P2[ih] = 1.0 - P1[ih];\n }\n\n /* Determine the first non-zero bin */\n firstBin = 0;\n for (let ih = 0; ih < histogram.length; ih++) {\n if (Math.abs(P1[ih]) >= Number.EPSILON) {\n firstBin = ih;\n break;\n }\n }\n\n /* Determine the last non-zero bin */\n lastBin = histogram.length - 1;\n for (let ih = histogram.length - 1; ih >= firstBin; ih--) {\n if (Math.abs(P2[ih]) >= Number.EPSILON) {\n lastBin = ih;\n break;\n }\n }\n\n /* Maximum Entropy Thresholding - BEGIN */\n /* ALPHA = 1.0 */\n /* Calculate the total entropy each gray-level\n and find the threshold that maximizes it\n */\n for (let it = firstBin; it <= lastBin; it++) {\n /* Entropy of the background pixels */\n let entBack1 = 0.0;\n let entBack2 = 0.0;\n let entBack3 = 0.0;\n for (let ih = 0; ih <= it; ih++) {\n if (histogram[ih] !== 0) {\n entBack1 -= (normHisto[ih] / P1[it]) * Math.log(normHisto[ih] / P1[it]);\n }\n entBack2 += Math.sqrt(normHisto[ih] / P1[it]);\n entBack3 += (normHisto[ih] * normHisto[ih]) / (P1[it] * P1[it]);\n }\n\n /* Entropy of the object pixels */\n let entObj1 = 0.0;\n let entObj2 = 0.0;\n let entObj3 = 0.0;\n for (let ih = it + 1; ih < histogram.length; ih++) {\n if (histogram[ih] !== 0) {\n entObj1 -= (normHisto[ih] / P2[it]) * Math.log(normHisto[ih] / P2[it]);\n }\n entObj2 += Math.sqrt(normHisto[ih] / P2[it]);\n entObj3 += (normHisto[ih] * normHisto[ih]) / (P2[it] * P2[it]);\n }\n\n /* Total entropy */\n let totEnt1 = entBack1 + entObj1;\n let totEnt2 =\n term2 * (entBack2 * entObj2 > 0.0 ? Math.log(entBack2 * entObj2) : 0.0);\n let totEnt3 =\n term3 * (entBack3 * entObj3 > 0.0 ? Math.log(entBack3 * entObj3) : 0.0);\n\n if (totEnt1 > maxEnt1) {\n maxEnt1 = totEnt1;\n threshold1 = it;\n }\n\n if (totEnt2 > maxEnt2) {\n maxEnt2 = totEnt2;\n threshold2 = it;\n }\n\n if (totEnt3 > maxEnt3) {\n maxEnt3 = totEnt3;\n threshold3 = it;\n }\n }\n /* End Maximum Entropy Thresholding */\n\n let tStars = [threshold1, threshold2, threshold3];\n tStars.sort((a, b) => a - b);\n\n let betas;\n\n /* Adjust beta values */\n if (Math.abs(tStars[0] - tStars[1]) <= 5) {\n if (Math.abs(tStars[1] - tStars[2]) <= 5) {\n betas = [1, 2, 1];\n } else {\n betas = [0, 1, 3];\n }\n } else {\n if (Math.abs(tStars[1] - tStars[2]) <= 5) {\n betas = [3, 1, 0];\n } else {\n betas = [1, 2, 1];\n }\n }\n\n /* Determine the optimal threshold value */\n let omega = P1[tStars[2]] - P1[tStars[0]];\n optThreshold = Math.round(\n tStars[0] * (P1[tStars[0]] + 0.25 * omega * betas[0]) +\n 0.25 * tStars[1] * omega * betas[1] +\n tStars[2] * (P2[tStars[2]] + 0.25 * omega * betas[2]),\n );\n\n return optThreshold;\n}\n","// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java\n// Shanhbag A.G. (1994) \"Utilization of Information Measure as a Means of\n// Image Thresholding\" Graphical Models and Image Processing, 56(5): 414-419\n// Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines\n\nexport default function shanbhag(histogram, total) {\n let normHisto = new Array(histogram.length); // normalized histogram\n for (let ih = 0; ih < histogram.length; ih++) {\n normHisto[ih] = histogram[ih] / total;\n }\n\n let P1 = new Array(histogram.length); // cumulative normalized histogram\n let P2 = new Array(histogram.length);\n P1[0] = normHisto[0];\n P2[0] = 1.0 - P1[0];\n for (let ih = 1; ih < histogram.length; ih++) {\n P1[ih] = P1[ih - 1] + normHisto[ih];\n P2[ih] = 1.0 - P1[ih];\n }\n\n /* Determine the first non-zero bin */\n let firstBin = 0;\n for (let ih = 0; ih < histogram.length; ih++) {\n if (Math.abs(P1[ih]) >= Number.EPSILON) {\n firstBin = ih;\n break;\n }\n }\n\n /* Determine the last non-zero bin */\n let lastBin = histogram.length - 1;\n for (let ih = histogram.length - 1; ih >= firstBin; ih--) {\n if (Math.abs(P2[ih]) >= Number.EPSILON) {\n lastBin = ih;\n break;\n }\n }\n\n // Calculate the total entropy each gray-level\n // and find the threshold that maximizes it\n let threshold = -1;\n let minEnt = Number.MAX_VALUE; // min entropy\n\n let term;\n let totEnt; // total entropy\n let entBack; // entropy of the background pixels at a given threshold\n let entObj; // entropy of the object pixels at a given threshold\n for (let it = firstBin; it <= lastBin; it++) {\n /* Entropy of the background pixels */\n entBack = 0.0;\n term = 0.5 / P1[it];\n for (let ih = 1; ih <= it; ih++) {\n entBack -= normHisto[ih] * Math.log(1.0 - term * P1[ih - 1]);\n }\n entBack *= term;\n\n /* Entropy of the object pixels */\n entObj = 0.0;\n term = 0.5 / P2[it];\n for (let ih = it + 1; ih < histogram.length; ih++) {\n entObj -= normHisto[ih] * Math.log(1.0 - term * P2[ih]);\n }\n entObj *= term;\n\n /* Total entropy */\n totEnt = Math.abs(entBack - entObj);\n\n if (totEnt < minEnt) {\n minEnt = totEnt;\n threshold = it;\n }\n }\n return threshold;\n}\n","// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java\n// Zack, G. W., Rogers, W. E. and Latt, S. A., 1977,\n// Automatic Measurement of Sister Chromatid Exchange Frequency,\n// Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753\n//\n// modified from Johannes Schindelin plugin\nexport default function triangle(histogram) {\n // find min and max\n let min = 0;\n let dmax = 0;\n let max = 0;\n let min2 = 0;\n for (let i = 0; i < histogram.length; i++) {\n if (histogram[i] > 0) {\n min = i;\n break;\n }\n }\n if (min > 0) {\n // line to the (p==0) point, not to histogram[min]\n min--;\n }\n\n // The Triangle algorithm cannot tell whether the data is skewed to one side or another.\n // This causes a problem as there are 2 possible thresholds between the max and the 2 extremes\n // of the histogram.\n // Here I propose to find out to which side of the max point the data is furthest, and use that as\n // the other extreme.\n for (let i = histogram.length - 1; i > 0; i--) {\n if (histogram[i] > 0) {\n min2 = i;\n break;\n }\n }\n if (min2 < histogram.length - 1) {\n // line to the (p==0) point, not to data[min]\n min2++;\n }\n\n for (let i = 0; i < histogram.length; i++) {\n if (histogram[i] > dmax) {\n max = i;\n dmax = histogram[i];\n }\n }\n\n // find which is the furthest side\n let inverted = false;\n if (max - min < min2 - max) {\n // reverse the histogram\n inverted = true;\n let left = 0; // index of leftmost element\n let right = histogram.length - 1; // index of rightmost element\n while (left < right) {\n // exchange the left and right elements\n let temp = histogram[left];\n histogram[left] = histogram[right];\n histogram[right] = temp;\n // move the bounds toward the center\n left++;\n right--;\n }\n min = histogram.length - 1 - min2;\n max = histogram.length - 1 - max;\n }\n\n if (min === max) {\n return min;\n }\n\n // describe line by nx * x + ny * y - d = 0\n let nx, ny, d;\n // nx is just the max frequency as the other point has freq=0\n nx = histogram[max]; // -min; // data[min]; // lowest value bmin = (p=0)% in the image\n ny = min - max;\n d = Math.sqrt(nx * nx + ny * ny);\n nx /= d;\n ny /= d;\n d = nx * min + ny * histogram[min];\n\n // find split point\n let split = min;\n let splitDistance = 0;\n for (let i = min + 1; i <= max; i++) {\n let newDistance = nx * i + ny * histogram[i] - d;\n if (newDistance > splitDistance) {\n split = i;\n splitDistance = newDistance;\n }\n }\n split--;\n\n if (inverted) {\n // The histogram might be used for something else, so let's reverse it back\n let left = 0;\n let right = histogram.length - 1;\n while (left < right) {\n let temp = histogram[left];\n histogram[left] = histogram[right];\n histogram[right] = temp;\n left++;\n right--;\n }\n return histogram.length - 1 - split;\n } else {\n return split;\n }\n}\n","// see https://github.com/fiji/Auto_Threshold/blob/master/src/main/java/fiji/threshold/Auto_Threshold.java\n// Implements Yen thresholding method\n// 1) Yen J.C., Chang F.J., and Chang S. (1995) \"A New Criterion\n// for Automatic Multilevel Thresholding\" IEEE Trans. on Image\n// Processing, 4(3): 370-378\n// 2) Sezgin M. and Sankur B. (2004) \"Survey over Image Thresholding\n// Techniques and Quantitative Performance Evaluation\" Journal of\n// Electronic Imaging, 13(1): 146-165\n// http://citeseer.ist.psu.edu/sezgin04survey.html\n//\n// M. Emre Celebi\n// 06.15.2007\n// Ported to ImageJ plugin by G.Landini from E Celebi's fourier_0.8 routines\n\nexport default function yen(histogram, total) {\n let normHisto = new Array(histogram.length); // normalized histogram\n for (let ih = 0; ih < histogram.length; ih++) {\n normHisto[ih] = histogram[ih] / total;\n }\n\n let P1 = new Array(histogram.length); // cumulative normalized histogram\n P1[0] = normHisto[0];\n for (let ih = 1; ih < histogram.length; ih++) {\n P1[ih] = P1[ih - 1] + normHisto[ih];\n }\n\n let P1Sq = new Array(histogram.length);\n P1Sq[0] = normHisto[0] * normHisto[0];\n for (let ih = 1; ih < histogram.length; ih++) {\n P1Sq[ih] = P1Sq[ih - 1] + normHisto[ih] * normHisto[ih];\n }\n\n let P2Sq = new Array(histogram.length);\n P2Sq[histogram.length - 1] = 0.0;\n for (let ih = histogram.length - 2; ih >= 0; ih--) {\n P2Sq[ih] = P2Sq[ih + 1] + normHisto[ih + 1] * normHisto[ih + 1];\n }\n\n /* Find the threshold that maximizes the criterion */\n let threshold = -1;\n let maxCrit = Number.MIN_VALUE;\n let crit;\n for (let it = 0; it < histogram.length; it++) {\n crit =\n -1.0 * (P1Sq[it] * P2Sq[it] > 0.0 ? Math.log(P1Sq[it] * P2Sq[it]) : 0.0) +\n 2 *\n (P1[it] * (1.0 - P1[it]) > 0.0\n ? Math.log(P1[it] * (1.0 - P1[it]))\n : 0.0);\n if (crit > maxCrit) {\n maxCrit = crit;\n threshold = it;\n }\n }\n return threshold;\n}\n","import huang from './huang';\nimport intermodes from './intermodes';\nimport isodata from './isodata';\nimport li from './li';\nimport maxEntropy from './maxEntropy';\nimport mean from './mean';\nimport minError from './minError';\nimport minimum from './minimum';\nimport moments from './moments';\nimport otsu from './otsu';\nimport percentile from './percentile';\nimport renyiEntropy from './renyiEntropy.js';\nimport shanbhag from './shanbhag';\nimport triangle from './triangle';\nimport yen from './yen';\n\n/**\n * @typedef {('huang'|'intermodes'|'isodata'|'li'|'maxentropy'|'mean'|'minerror'|'minimum'|'moments'|'otsu'|'percentile'|'renyientropy'|'shanbhag'|'triangle'|'yen')} ThresholdAlgorithm\n */\n\nexport const methods = {\n huang,\n intermodes,\n isodata,\n li,\n maxentropy: maxEntropy,\n mean,\n minerror: minError,\n minimum,\n moments,\n otsu,\n percentile,\n renyientropy: renyiEntropy,\n shanbhag,\n triangle,\n yen,\n};\n\nexport const names = {};\nObject.keys(methods).forEach((name) => {\n names[name] = name;\n});\n","import { methods, names } from '../transform/mask/thresholdAlgorithms';\n\n/**\n * Returns a threshold for the creation of a binary mask with the `mask()` method.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {ThresholdAlgorithm} [options.algorithm='otsu']\n * @return {number}\n */\nexport default function getThreshold(options = {}) {\n let { algorithm = names.otsu } = options;\n\n this.checkProcessable('getThreshold', {\n components: 1,\n bitDepth: [8, 16],\n });\n\n let method = methods[algorithm.toLowerCase()];\n if (method) {\n let histogram = this.getHistogram();\n return method(histogram, this.size);\n } else {\n throw new Error(`unknown thresholding algorithm: ${algorithm}`);\n }\n}\n","import { getThreshold as convertThreshold } from '../../../util/converter';\nimport Image from '../../Image';\nimport getThreshold from '../../utility/getThreshold';\n\nconst THRESHOLD = 'threshold';\n\n/**\n * Creation of binary mask is based on the determination of a threshold\n * You may either choose among the provided algorithm or just specify a threshold value\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {ThresholdAlgorithm|'threshold'} [options.algorithm='threshold']\n * @param {number} [options.threshold=0.5] - If the algorithm is 'threshold' specify here the value (0 to 1).\n * @param {boolean} [options.useAlpha=true] - Apply the alpha channel to determine the intensity of the pixel.\n * @param {boolean} [options.invert=false] - Invert the resulting image\n * @return {Image} - Binary image containing the mask\n */\nexport default function mask(options = {}) {\n let {\n algorithm = THRESHOLD,\n threshold = 0.5,\n useAlpha = true,\n invert = false,\n } = options;\n\n this.checkProcessable('mask', {\n components: 1,\n bitDepth: [8, 16],\n });\n\n if (algorithm === THRESHOLD) {\n threshold = convertThreshold(threshold, this.maxValue);\n } else {\n threshold = getThreshold.call(this, options);\n }\n\n let newImage = new Image(this.width, this.height, {\n kind: 'BINARY',\n parent: this,\n });\n\n let ptr = 0;\n if (this.alpha && useAlpha) {\n for (let i = 0; i < this.data.length; i += this.channels) {\n let value =\n this.data[i] +\n ((this.maxValue - this.data[i]) * (this.maxValue - this.data[i + 1])) /\n this.maxValue;\n if ((invert && value <= threshold) || (!invert && value >= threshold)) {\n newImage.setBit(ptr);\n }\n ptr++;\n }\n } else {\n for (let i = 0; i < this.data.length; i += this.channels) {\n if (\n (invert && this.data[i] <= threshold) ||\n (!invert && this.data[i] >= threshold)\n ) {\n newImage.setBit(ptr);\n }\n ptr++;\n }\n }\n\n return newImage;\n}\n","/**\n * Make a copy of the current image\n * @memberof Image\n * @instance\n * @param {Image} fromImage\n * @param {Image} toImage\n * @param {number} x\n * @param {number} y\n */\nexport default function copyImage(fromImage, toImage, x, y) {\n let fromWidth = fromImage.width;\n let fromHeight = fromImage.height;\n let toWidth = toImage.width;\n let channels = fromImage.channels;\n for (let i = 0; i < fromWidth; i++) {\n for (let j = 0; j < fromHeight; j++) {\n for (let k = 0; k < channels; k++) {\n let source = (j * fromWidth + i) * channels + k;\n let target = ((y + j) * toWidth + x + i) * channels + k;\n toImage.data[target] = fromImage.data[source];\n }\n }\n }\n}\n","import array from 'new-array';\n\nimport Image from '../Image';\nimport copy from '../internal/copy';\n\n/**\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.size=0]\n * @param {string} [options.algorithm='copy']\n * @param {array} [options.color]\n * @return {Image}\n */\nexport default function pad(options = {}) {\n let { size = 0, algorithm = 'copy', color } = options;\n\n this.checkProcessable('pad', {\n bitDepth: [8, 16],\n });\n\n if (algorithm === 'set') {\n if (color.length !== this.channels) {\n throw new Error(\n `pad: the color array must have the same length as the number of channels. Here: ${this.channels}`,\n );\n }\n for (let i = 0; i < color.length; i++) {\n if (color[i] === 0) {\n color[i] = 0.001;\n }\n }\n } else {\n color = array(this.channels, null);\n }\n\n if (!Array.isArray(size)) {\n size = [size, size];\n }\n\n let newWidth = this.width + size[0] * 2;\n let newHeight = this.height + size[1] * 2;\n let channels = this.channels;\n\n let newImage = Image.createFrom(this, { width: newWidth, height: newHeight });\n\n copy(this, newImage, size[0], size[1]);\n\n for (let i = size[0]; i < newWidth - size[0]; i++) {\n for (let k = 0; k < channels; k++) {\n let value =\n color[k] || newImage.data[(size[1] * newWidth + i) * channels + k];\n for (let j = 0; j < size[1]; j++) {\n newImage.data[(j * newWidth + i) * channels + k] = value;\n }\n value =\n color[k] ||\n newImage.data[\n ((newHeight - size[1] - 1) * newWidth + i) * channels + k\n ];\n for (let j = newHeight - size[1]; j < newHeight; j++) {\n newImage.data[(j * newWidth + i) * channels + k] = value;\n }\n }\n }\n\n for (let j = 0; j < newHeight; j++) {\n for (let k = 0; k < channels; k++) {\n let value =\n color[k] || newImage.data[(j * newWidth + size[0]) * channels + k];\n for (let i = 0; i < size[0]; i++) {\n newImage.data[(j * newWidth + i) * channels + k] = value;\n }\n value =\n color[k] ||\n newImage.data[(j * newWidth + newWidth - size[0] - 1) * channels + k];\n for (let i = newWidth - size[0]; i < newWidth; i++) {\n newImage.data[(j * newWidth + i) * channels + k] = value;\n }\n }\n }\n\n return newImage;\n}\n","import Image from '../Image';\n\n/**\n * Change the image color depth.\n * The color depth is the number of bits that is assigned to each point of a channel.\n * For normal images it is 8 bits meaning the value is between 0 and 255.\n * Currently only conversion from 1, 8 or 16 bits towards 8 or 16 bits are allowed.\n * @memberof Image\n * @instance\n * @param {number} [newColorDepth=8]\n * @return {Image} The new image\n * @example\n * var newImage = image.colorDepth(8);\n */\nexport default function colorDepth(newColorDepth = 8) {\n this.checkProcessable('colorDepth', {\n bitDepth: [1, 8, 16],\n });\n\n if (![8, 16].includes(newColorDepth)) {\n throw Error('You need to specify the new colorDepth as 8 or 16');\n }\n\n if (this.bitDepth === newColorDepth) {\n return this.clone();\n }\n\n let newImage = Image.createFrom(this, { bitDepth: newColorDepth });\n\n switch (newColorDepth) {\n case 8:\n if (this.bitDepth === 1) {\n for (let i = 0; i < this.size; i++) {\n if (this.getBit(i)) {\n newImage.data[i] = 255;\n }\n }\n } else {\n for (let i = 0; i < this.data.length; i++) {\n newImage.data[i] = this.data[i] >> 8;\n }\n }\n break;\n case 16:\n if (this.bitDepth === 1) {\n for (let i = 0; i < this.size; i++) {\n if (this.getBit(i)) {\n newImage.data[i] = 65535;\n }\n }\n } else {\n for (let i = 0; i < this.data.length; i++) {\n newImage.data[i] = (this.data[i] << 8) | this.data[i];\n }\n }\n break;\n default:\n throw new Error('colorDepth conversion unexpected case');\n }\n return newImage;\n}\n","import Image from '../Image';\nimport { validInterpolations, checkInterpolation } from '../internal/checks';\n\nexport default function rotateFree(degrees, options = {}) {\n const {\n interpolation = validInterpolations.nearestneighbor,\n width = this.width,\n height = this.height,\n } = options;\n\n if (typeof degrees !== 'number') {\n throw new TypeError('degrees must be a number');\n }\n const interpolationToUse = checkInterpolation(interpolation);\n\n const radians = (degrees * Math.PI) / 180;\n const newWidth = Math.floor(\n Math.abs(width * Math.cos(radians)) + Math.abs(height * Math.sin(radians)),\n );\n const newHeight = Math.floor(\n Math.abs(height * Math.cos(radians)) + Math.abs(width * Math.sin(radians)),\n );\n const newImage = Image.createFrom(this, {\n width: newWidth,\n height: newHeight,\n });\n const cos = Math.cos(-radians);\n const sin = Math.sin(-radians);\n\n let x0 = newWidth / 2;\n let y0 = newHeight / 2;\n if (newWidth % 2 === 0) {\n x0 = x0 - 0.5;\n if (newHeight % 2 === 0) {\n y0 = y0 - 0.5;\n } else {\n y0 = Math.floor(y0);\n }\n } else {\n x0 = Math.floor(x0);\n if (newHeight % 2 === 0) {\n y0 = y0 - 0.5;\n } else {\n y0 = Math.floor(y0);\n }\n }\n\n const incrementX = Math.floor(width / 2 - x0);\n const incrementY = Math.floor(height / 2 - y0);\n\n switch (interpolationToUse) {\n case validInterpolations.nearestneighbor:\n return rotateNearestNeighbor(\n this,\n newImage,\n incrementX,\n incrementY,\n x0,\n y0,\n cos,\n sin,\n );\n case validInterpolations.bilinear:\n return rotateBilinear(\n this,\n newImage,\n incrementX,\n incrementY,\n x0,\n y0,\n cos,\n sin,\n );\n default:\n throw new Error(\n `unsupported rotate interpolation: ${interpolationToUse}`,\n );\n }\n}\n\nfunction rotateNearestNeighbor(\n thisImage,\n newImage,\n incrementX,\n incrementY,\n x0,\n y0,\n cos,\n sin,\n) {\n for (let i = 0; i < newImage.width; i += 1) {\n for (let j = 0; j < newImage.height; j += 1) {\n for (let c = 0; c < thisImage.channels; c++) {\n let x = Math.round((i - x0) * cos - (j - y0) * sin + x0) + incrementX;\n let y = Math.round((j - y0) * cos + (i - x0) * sin + y0) + incrementY;\n\n if (x < 0 || x >= thisImage.width || y < 0 || y >= thisImage.height) {\n if (thisImage.alpha === 1 && c === thisImage.channels - 1) {\n newImage.setValueXY(i, j, c, 0);\n } else {\n newImage.setValueXY(i, j, c, thisImage.maxValue);\n }\n } else {\n newImage.setValueXY(i, j, c, thisImage.getValueXY(x, y, c));\n }\n }\n }\n }\n return newImage;\n}\n\nfunction rotateBilinear(\n thisImage,\n newImage,\n incrementX,\n incrementY,\n x0,\n y0,\n cos,\n sin,\n) {\n let stride = thisImage.width * thisImage.channels;\n for (let j = 0; j < newImage.height; j++) {\n for (let i = 0; i < newImage.width; i++) {\n let x = (i - x0) * cos - (j - y0) * sin + x0 + incrementX;\n let y = (j - y0) * cos + (i - x0) * sin + y0 + incrementY;\n let x1 = x | 0;\n let y1 = y | 0;\n let xDiff = x - x1;\n let yDiff = y - y1;\n for (let c = 0; c < thisImage.channels; c++) {\n if (x < 0 || x >= thisImage.width || y < 0 || y >= thisImage.height) {\n if (thisImage.alpha === 1 && c === thisImage.channels - 1) {\n newImage.setValueXY(i, j, c, 0);\n } else {\n newImage.setValueXY(i, j, c, thisImage.maxValue);\n }\n } else {\n let index = (y1 * thisImage.width + x1) * thisImage.channels + c;\n\n let A = thisImage.data[index];\n let B = thisImage.data[index + thisImage.channels];\n let C = thisImage.data[index + stride];\n let D = thisImage.data[index + stride + thisImage.channels];\n\n let result =\n (A +\n xDiff * (B - A) +\n yDiff * (C - A) +\n xDiff * yDiff * (A - B - C + D)) |\n 0;\n\n newImage.setValueXY(i, j, c, result);\n }\n }\n }\n }\n return newImage;\n}\n","import Image from '../Image';\n\nimport rotateFree from './rotateFree';\n\n/**\n * Rotates an image.\n * @memberof Image\n * @instance\n * @param {number} angle - Angle of the rotation in degrees\n * @param {object} [options]\n * @param {InterpolationAlgorithm} [options.interpolation='nearestNeighbor'] - Interpolation algorithm to use if `angle` is not a multiple of 90\n * @return {Image} The new rotated image\n */\nexport function rotate(angle, options) {\n if (typeof angle !== 'number') {\n throw new TypeError('angle must be a number');\n }\n\n if (angle < 0) {\n angle = Math.ceil(-angle / 360) * 360 + angle;\n }\n\n switch (angle % 360) {\n case 0:\n return this.clone();\n case 90:\n return rotateRight.call(this);\n case 180:\n return rotate180.call(this);\n case 270:\n return rotateLeft.call(this);\n default:\n return rotateFree.call(this, angle, options);\n }\n}\n\n/**\n * Rotates an image counter-clockwise\n * @memberof Image\n * @instance\n * @return {Image} The new rotated image\n */\nexport function rotateLeft() {\n const newImage = Image.createFrom(this, {\n width: this.height,\n height: this.width,\n });\n const newMaxHeight = newImage.height - 1;\n for (let i = 0; i < this.height; i++) {\n for (let j = 0; j < this.width; j++) {\n for (let k = 0; k < this.channels; k++) {\n newImage.setValueXY(i, newMaxHeight - j, k, this.getValueXY(j, i, k));\n }\n }\n }\n return newImage;\n}\n\n/**\n * Rotates an image clockwise\n * @memberof Image\n * @instance\n * @return {Image} The new rotated image\n */\n\nexport function rotateRight() {\n const newImage = Image.createFrom(this, {\n width: this.height,\n height: this.width,\n });\n const newMaxWidth = newImage.width - 1;\n for (let i = 0; i < this.height; i++) {\n for (let j = 0; j < this.width; j++) {\n for (let k = 0; k < this.channels; k++) {\n newImage.setValueXY(newMaxWidth - i, j, k, this.getValueXY(j, i, k));\n }\n }\n }\n return newImage;\n}\n\nfunction rotate180() {\n const newImage = Image.createFrom(this);\n const newMaxWidth = newImage.width - 1;\n const newMaxHeight = newImage.height - 1;\n for (let i = 0; i < this.height; i++) {\n for (let j = 0; j < this.width; j++) {\n for (let k = 0; k < this.channels; k++) {\n newImage.setValueXY(\n newMaxWidth - j,\n newMaxHeight - i,\n k,\n this.getValueXY(j, i, k),\n );\n }\n }\n }\n return newImage;\n}\n","import getImageParameters from '../internal/getImageParameters';\nimport { getOutputImageOrInPlace } from '../internal/getOutputImage';\n\n/**\n * Inserts an image within another image.\n * @memberof Image\n * @instance\n * @param {Image} toInsert The image to insert. Out of boundary pixel will be ignored.\n * @param {object} [options]\n * @param {number} [options.x=0] x offset\n * @param {number} [options.y=0] y offset\n * @param {boolean} [options.inPlace=false] - If true modifies the image. If false the insertion is performed on a copy of the image.\n * @return {Image} The modified image or the new image.\n */\nexport default function insert(toInsert, options = {}) {\n const parameters = getImageParameters(toInsert);\n this.checkProcessable('insert', parameters);\n let { x = 0, y = 0 } = options;\n\n const out = getOutputImageOrInPlace(this, options, { copy: true });\n const maxY = Math.min(out.height, y + toInsert.height);\n const maxX = Math.min(out.width, x + toInsert.width);\n if (out.bitDepth === 1) {\n for (let j = y; j < maxY; j++) {\n for (let i = x; i < maxX; i++) {\n const val = toInsert.getBitXY(i - x, j - y);\n if (val) out.setBitXY(i, j);\n else out.clearBitXY(i, j);\n }\n }\n } else {\n for (let j = y; j < maxY; j++) {\n for (let i = x; i < maxX; i++) {\n out.setPixelXY(i, j, toInsert.getPixelXY(i - x, j - y));\n }\n }\n }\n\n return out;\n}\n","import array from 'new-array';\n\n/**\n * This method will change the border\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.size=0]\n * @param {string} [options.algorithm='copy']\n * @param {number[]} [options.color]\n * @return {this}\n */\nexport default function setBorder(options = {}) {\n let { size = 0, algorithm = 'copy', color } = options;\n\n this.checkProcessable('setBorder', {\n bitDepth: [8, 16, 32, 64],\n });\n\n if (algorithm === 'set') {\n if (color.length !== this.channels) {\n throw new Error(\n `setBorder: the color array must have the same length as the number of channels. Here: ${this.channels}`,\n );\n }\n for (let i = 0; i < color.length; i++) {\n if (color[i] === 0) {\n color[i] = 0.001;\n }\n }\n } else {\n color = array(this.channels, null);\n }\n\n if (!Array.isArray(size)) {\n size = [size, size];\n }\n\n let leftRightSize = size[0];\n let topBottomSize = size[1];\n let channels = this.channels;\n\n for (let i = leftRightSize; i < this.width - leftRightSize; i++) {\n for (let k = 0; k < channels; k++) {\n let value =\n color[k] || this.data[(i + this.width * topBottomSize) * channels + k];\n for (let j = 0; j < topBottomSize; j++) {\n this.data[(j * this.width + i) * channels + k] = value;\n }\n value =\n color[k] ||\n this.data[\n (i + this.width * (this.height - topBottomSize - 1)) * channels + k\n ];\n for (let j = this.height - topBottomSize; j < this.height; j++) {\n this.data[(j * this.width + i) * channels + k] = value;\n }\n }\n }\n\n for (let j = 0; j < this.height; j++) {\n for (let k = 0; k < channels; k++) {\n let value =\n color[k] || this.data[(j * this.width + leftRightSize) * channels + k];\n for (let i = 0; i < leftRightSize; i++) {\n this.data[(j * this.width + i) * channels + k] = value;\n }\n value =\n color[k] ||\n this.data[\n (j * this.width + this.width - leftRightSize - 1) * channels + k\n ];\n for (let i = this.width - leftRightSize; i < this.width; i++) {\n this.data[(j * this.width + i) * channels + k] = value;\n }\n }\n }\n\n return this;\n}\n","import Stack from '../../stack/Stack';\nimport Image from '../Image';\nimport { GREY } from '../model/model';\n\n/**\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {boolean} [options.preserveAlpha=true]\n * @return {Stack}\n */\nexport default function split(options = {}) {\n let { preserveAlpha = true } = options;\n\n this.checkProcessable('split', {\n bitDepth: [8, 16],\n });\n\n // split will always return a stack of images\n if (this.components === 1) {\n return new Stack([this.clone()]);\n }\n\n let images = new Stack();\n\n let data = this.data;\n if (this.alpha && preserveAlpha) {\n for (let i = 0; i < this.components; i++) {\n let newImage = Image.createFrom(this, {\n components: 1,\n alpha: true,\n colorModel: GREY,\n });\n let ptr = 0;\n for (let j = 0; j < data.length; j += this.channels) {\n newImage.data[ptr++] = data[j + i];\n newImage.data[ptr++] = data[j + this.components];\n }\n images.push(newImage);\n }\n } else {\n for (let i = 0; i < this.channels; i++) {\n let newImage = Image.createFrom(this, {\n components: 1,\n alpha: false,\n colorModel: GREY,\n });\n let ptr = 0;\n for (let j = 0; j < data.length; j += this.channels) {\n newImage.data[ptr++] = data[j + i];\n }\n images.push(newImage);\n }\n }\n\n return images;\n}\n","import { validateChannel } from '../../util/channel';\nimport Image from '../Image';\nimport { GREY } from '../model/model';\n\n/**\n * Create a grey image based on the selected channel\n * @memberof Image\n * @instance\n * @param {number|string} channel\n * @param {object} [options]\n * @param {boolean} [options.keepAlpha]\n * @param {boolean} [options.mergeAlpha]\n * @return {Image} A grey image with the extracted channel\n */\nexport default function getChannel(channel, options = {}) {\n let { keepAlpha = false, mergeAlpha = false } = options;\n\n keepAlpha &= this.alpha;\n mergeAlpha &= this.alpha;\n\n this.checkProcessable('getChannel', {\n bitDepth: [8, 16],\n });\n\n channel = validateChannel(this, channel);\n\n let newImage = Image.createFrom(this, {\n components: 1,\n alpha: keepAlpha,\n colorModel: GREY,\n });\n let ptr = 0;\n for (let j = 0; j < this.data.length; j += this.channels) {\n if (mergeAlpha) {\n newImage.data[ptr++] =\n (this.data[j + channel] * this.data[j + this.components]) /\n this.maxValue;\n } else {\n newImage.data[ptr++] = this.data[j + channel];\n if (keepAlpha) {\n newImage.data[ptr++] = this.data[j + this.components];\n }\n }\n }\n\n return newImage;\n}\n","import Image from '../Image';\nimport { GREY } from '../model/model';\n\n/**\n * Create a new grey Image by combining the channels of the current image.\n * @memberof Image\n * @instance\n * @param {function} method\n * @param {object} [options]\n * @param {boolean} [options.mergeAlpha=false]\n * @param {boolean} [options.keepAlpha=false]\n * @return {Image}\n */\nexport default function combineChannels(\n method = defaultCombineMethod,\n options = {},\n) {\n let { mergeAlpha = false, keepAlpha = false } = options;\n\n mergeAlpha &= this.alpha;\n keepAlpha &= this.alpha;\n\n this.checkProcessable('combineChannels', {\n bitDepth: [8, 16],\n });\n\n let newImage = Image.createFrom(this, {\n components: 1,\n alpha: keepAlpha,\n colorModel: GREY,\n });\n\n let ptr = 0;\n for (let i = 0; i < this.size; i++) {\n // TODO quite slow because we create a new pixel each time\n let value = method(this.getPixel(i));\n if (mergeAlpha) {\n newImage.data[ptr++] =\n (value * this.data[i * this.channels + this.components]) /\n this.maxValue;\n } else {\n newImage.data[ptr++] = value;\n if (keepAlpha) {\n newImage.data[ptr++] = this.data[i * this.channels + this.components];\n }\n }\n }\n\n return newImage;\n}\n\nfunction defaultCombineMethod(pixel) {\n return (pixel[0] + pixel[1] + pixel[2]) / 3;\n}\n","import { validateChannel } from '../../util/channel';\n\n/**\n * @memberof Image\n * @instance\n * @param {*} channel\n * @param {Image} image\n *\n * @return {this}\n */\nexport default function setChannel(channel, image) {\n this.checkProcessable('setChannel', {\n bitDepth: [8, 16],\n });\n\n image.checkProcessable('setChannel (image parameter check)', {\n bitDepth: [this.bitDepth],\n alpha: [0],\n components: [1],\n });\n\n if (image.width !== this.width || image.height !== this.height) {\n throw new Error('Images must have exactly the same width and height');\n }\n\n channel = validateChannel(this, channel);\n\n let ptr = channel;\n for (let i = 0; i < image.data.length; i++) {\n this.data[ptr] = image.data[i];\n ptr += this.channels;\n }\n\n return this;\n}\n","import newArray from 'new-array';\n\nimport { validateArrayOfChannels } from '../../util/channel';\n\n/**\n * Try to match the current pictures with another one. If normalize we normalize separately the 2 images.\n * @memberof Image\n * @instance\n * @param {Image} image - Other image\n * @param {object} [options]\n * @return {number[]|number}\n */\nexport default function getSimilarity(image, options = {}) {\n let {\n shift = [0, 0],\n average,\n channels,\n defaultAlpha,\n normalize,\n border = [0, 0],\n } = options;\n\n this.checkProcessable('getSimilarity', {\n bitDepth: [8, 16],\n });\n\n if (!Array.isArray(border)) {\n border = [border, border];\n }\n channels = validateArrayOfChannels(this, {\n channels: channels,\n defaultAlpha: defaultAlpha,\n });\n\n if (this.bitDepth !== image.bitDepth) {\n throw new Error('Both images must have the same bitDepth');\n }\n if (this.channels !== image.channels) {\n throw new Error('Both images must have the same number of channels');\n }\n if (this.colorModel !== image.colorModel) {\n throw new Error('Both images must have the same colorModel');\n }\n\n if (typeof average === 'undefined') {\n average = true;\n }\n\n // we allow a shift\n // we need to find the minX, maxX, minY, maxY\n let minX = Math.max(border[0], -shift[0]);\n let maxX = Math.min(this.width - border[0], this.width - shift[0]);\n let minY = Math.max(border[1], -shift[1]);\n let maxY = Math.min(this.height - border[1], this.height - shift[1]);\n\n let results = newArray(channels.length, 0);\n for (let i = 0; i < channels.length; i++) {\n let c = channels[i];\n let sumThis = normalize ? this.sum[c] : Math.max(this.sum[c], image.sum[c]);\n let sumImage = normalize\n ? image.sum[c]\n : Math.max(this.sum[c], image.sum[c]);\n\n if (sumThis !== 0 && sumImage !== 0) {\n for (let x = minX; x < maxX; x++) {\n for (let y = minY; y < maxY; y++) {\n let indexThis = x * this.multiplierX + y * this.multiplierY + c;\n let indexImage =\n indexThis +\n shift[0] * this.multiplierX +\n shift[1] * this.multiplierY;\n results[i] += Math.min(\n this.data[indexThis] / sumThis,\n image.data[indexImage] / sumImage,\n );\n }\n }\n }\n }\n\n if (average) {\n return results.reduce((sum, x) => sum + x) / results.length;\n }\n return results;\n}\n","/**\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number[]} [options.sampling=[10, 10]]\n * @param {boolean} [options.painted=false]\n * @param {Image} [options.mask]\n * @return {object}\n */\nexport default function getPixelsGrid(options = {}) {\n let { sampling = [10, 10], painted = false, mask } = options;\n\n this.checkProcessable('getPixelsGrid', {\n bitDepth: [8, 16],\n channels: 1,\n });\n\n if (!Array.isArray(sampling)) {\n sampling = [sampling, sampling];\n }\n\n const xSampling = sampling[0];\n const ySampling = sampling[1];\n\n const xyS = [];\n const zS = [];\n\n const xStep = this.width / xSampling;\n const yStep = this.height / ySampling;\n let currentX = Math.floor(xStep / 2);\n\n for (let i = 0; i < xSampling; i++) {\n let currentY = Math.floor(yStep / 2);\n for (let j = 0; j < ySampling; j++) {\n let x = Math.round(currentX);\n let y = Math.round(currentY);\n if (!mask || mask.getBitXY(x, y)) {\n xyS.push([x, y]);\n zS.push(this.getPixelXY(x, y));\n }\n currentY += yStep;\n }\n currentX += xStep;\n }\n\n const toReturn = { xyS, zS };\n\n if (painted) {\n toReturn.painted = this.rgba8().paintPoints(xyS);\n }\n\n return toReturn;\n}\n","export default function Matrix(width, height, defaultValue) {\n const matrix = new Array(width);\n for (let x = 0; x < width; x++) {\n matrix[x] = new Array(height);\n }\n if (defaultValue) {\n for (let x = 0; x < width; x++) {\n for (let y = 0; y < height; y++) {\n matrix[x][y] = defaultValue;\n }\n }\n }\n matrix.width = width;\n matrix.height = height;\n Object.setPrototypeOf(matrix, Matrix.prototype);\n return matrix;\n}\n\nMatrix.prototype.localMin = function (x, y) {\n let min = this[x][y];\n let position = [x, y];\n for (let i = Math.max(0, x - 1); i < Math.min(this.length, x + 2); i++) {\n for (let j = Math.max(0, y - 1); j < Math.min(this[0].length, y + 2); j++) {\n if (this[i][j] < min) {\n min = this[i][j];\n position = [i, j];\n }\n }\n }\n return {\n position: position,\n value: min,\n };\n};\n\nMatrix.prototype.localMax = function (x, y) {\n let max = this[x][y];\n let position = [x, y];\n for (let i = Math.max(0, x - 1); i < Math.min(this.length, x + 2); i++) {\n for (let j = Math.max(0, y - 1); j < Math.min(this[0].length, y + 2); j++) {\n if (this[i][j] > max) {\n max = this[i][j];\n position = [i, j];\n }\n }\n }\n return {\n position: position,\n value: max,\n };\n};\n\nMatrix.prototype.localSearch = function (x, y, value) {\n let results = [];\n for (let i = Math.max(0, x - 1); i < Math.min(this.length, x + 2); i++) {\n for (let j = Math.max(0, y - 1); j < Math.min(this[0].length, y + 2); j++) {\n if (this[i][j] === value) {\n results.push([i, j]);\n }\n }\n }\n return results;\n};\n","import Matrix from '../../util/matrix';\n\n/**\n * Try to match the current pictures with another one\n * @memberof Image\n * @instance\n * @param {Image} image - Other image to match\n * @param {object} [options]\n * @return {number[]}\n */\nexport default function getBestMatch(image, options = {}) {\n let { border } = options;\n\n this.checkProcessable('getChannel', {\n bitDepth: [8, 16],\n });\n\n if (this.bitDepth !== image.bitDepth) {\n throw new Error('Both images must have the same bitDepth');\n }\n if (this.channels !== image.channels) {\n throw new Error('Both images must have the same number of channels');\n }\n if (this.colorModel !== image.colorModel) {\n throw new Error('Both images must have the same colorModel');\n }\n\n // there could be many names\n let similarityMatrix = new Matrix(image.width, image.height, -Infinity);\n\n let currentX = Math.floor(image.width / 2);\n let currentY = Math.floor(image.height / 2);\n let middleX = currentX;\n let middleY = currentY;\n let theEnd = false;\n\n while (!theEnd) {\n let toCalculatePositions = similarityMatrix.localSearch(\n currentX,\n currentY,\n -Infinity,\n );\n for (let i = 0; i < toCalculatePositions.length; i++) {\n let position = toCalculatePositions[i];\n let similarity = this.getSimilarity(image, {\n border: border,\n shift: [middleX - position[0], middleY - position[1]],\n });\n similarityMatrix[position[0]][position[1]] = similarity;\n }\n\n let max = similarityMatrix.localMax(currentX, currentY);\n if (max.position[0] !== currentX || max.position[1] !== currentY) {\n currentX = max.position[0];\n currentY = max.position[1];\n } else {\n theEnd = true;\n }\n }\n\n return [currentX - middleX, currentY - middleY];\n}\n","import { checkRow, checkChannel } from '../internal/checks';\n\n/**\n * @memberof Image\n * @instance\n * @param {number} row\n * @param {number} [channel=0]\n * @return {number[]}\n */\nexport default function getRow(row, channel = 0) {\n this.checkProcessable('getRow', {\n bitDepth: [8, 16],\n });\n\n checkRow(this, row);\n checkChannel(this, channel);\n\n let array = new Array(this.width);\n let ptr = 0;\n let begin = row * this.width * this.channels + channel;\n let end = begin + this.width * this.channels;\n for (let j = begin; j < end; j += this.channels) {\n array[ptr++] = this.data[j];\n }\n\n return array;\n}\n","import { checkColumn, checkChannel } from '../internal/checks';\n\n/**\n * @memberof Image\n * @instance\n * @param {number} column\n * @param {number} [channel=0]\n * @return {number[]}\n */\nexport default function getColumn(column, channel = 0) {\n this.checkProcessable('getColumn', {\n bitDepth: [8, 16],\n });\n\n checkColumn(this, column);\n checkChannel(this, channel);\n\n let array = new Array(this.height);\n let ptr = 0;\n let step = this.width * this.channels;\n for (\n let j = channel + column * this.channels;\n j < this.data.length;\n j += step\n ) {\n array[ptr++] = this.data[j];\n }\n return array;\n}\n","import Matrix from 'ml-matrix';\n\n/**\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.channel]\n * @return {Matrix}\n */\nexport default function getMatrix(options = {}) {\n let { channel } = options;\n this.checkProcessable('getMatrix', {\n bitDepth: [8, 16],\n });\n\n if (channel === undefined) {\n if (this.components > 1) {\n throw new RangeError(\n 'You need to define the channel for an image that contains more than one channel',\n );\n }\n channel = 0;\n }\n\n let matrix = new Matrix(this.height, this.width);\n for (let x = 0; x < this.height; x++) {\n for (let y = 0; y < this.width; y++) {\n matrix.set(x, y, this.getValueXY(y, x, channel));\n }\n }\n\n return matrix;\n}\n","import { Matrix } from 'ml-matrix';\n\n/**\n * We set the data of the image from a matrix. The size of the matrix and the data have to be the same.\n * @memberof Image\n * @instance\n * @param {Matrix} matrix\n * @param {object} [options]\n * @param {number} [options.channel]\n */\nexport default function setMatrix(matrix, options = {}) {\n matrix = new Matrix(matrix);\n let { channel } = options;\n this.checkProcessable('getMatrix', {\n bitDepth: [8, 16],\n });\n\n if (channel === undefined) {\n if (this.components > 1) {\n throw new RangeError(\n 'You need to define the channel for an image that contains more than one channel',\n );\n }\n channel = 0;\n }\n\n if (this.width !== matrix.columns || this.height !== matrix.rows) {\n throw new RangeError(\n 'The size of the matrix must be equal to the size of the image',\n );\n }\n\n for (let x = 0; x < this.height; x++) {\n for (let y = 0; y < this.width; y++) {\n this.setValueXY(y, x, channel, matrix.get(x, y));\n }\n }\n}\n","/**\n * Returns an array of arrays containing the pixel values in the form\n * [[R1, G1, B1], [R2, G2, B2], ...]\n * @memberof Image\n * @instance\n * @return {Array>}\n */\nexport default function getPixelsArray() {\n this.checkProcessable('getPixelsArray', {\n bitDepth: [8, 16, 32],\n });\n\n let array = new Array(this.size);\n let ptr = 0;\n for (let i = 0; i < this.data.length; i += this.channels) {\n let pixel = new Array(this.components);\n for (let j = 0; j < this.components; j++) {\n pixel[j] = this.data[i + j];\n }\n array[ptr++] = pixel;\n }\n\n return array;\n}\n","/**\n * Find intersection of points between two different masks\n * @memberof Image\n * @instance\n * @param {Image} mask2 - a mask (1 bit image)\n * @return {object} - object containing number of white pixels for mask1, for mask 2 and for them both\n */\nexport default function getIntersection(mask2) {\n let mask1 = this;\n let closestParent = mask1.getClosestCommonParent(mask2);\n\n let startPos1 = mask1.getRelativePosition(closestParent, {\n defaultFurther: true,\n });\n let allRelPos1 = getRelativePositionForAllPixels(mask1, startPos1);\n let startPos2 = mask2.getRelativePosition(closestParent, {\n defaultFurther: true,\n });\n let allRelPos2 = getRelativePositionForAllPixels(mask2, startPos2);\n\n let commonSurface = getCommonSurface(allRelPos1, allRelPos2);\n let intersection = {\n whitePixelsMask1: [],\n whitePixelsMask2: [],\n commonWhitePixels: [],\n };\n\n for (let i = 0; i < commonSurface.length; i++) {\n let currentRelativePos = commonSurface[i];\n let realPos1 = [\n currentRelativePos[0] - startPos1[0],\n currentRelativePos[1] - startPos1[1],\n ];\n let realPos2 = [\n currentRelativePos[0] - startPos2[0],\n currentRelativePos[1] - startPos2[1],\n ];\n let valueBitMask1 = mask1.getBitXY(realPos1[0], realPos1[1]);\n let valueBitMask2 = mask2.getBitXY(realPos2[0], realPos2[1]);\n\n if (valueBitMask1 === 1 && valueBitMask2 === 1) {\n intersection.commonWhitePixels.push(currentRelativePos);\n }\n }\n\n for (let i = 0; i < allRelPos1.length; i++) {\n let posX;\n let posY;\n if (i !== 0) {\n posX = Math.floor(i / mask1.width);\n posY = i % mask1.width;\n }\n if (mask1.getBitXY(posX, posY) === 1) {\n intersection.whitePixelsMask1.push(allRelPos1[i]);\n }\n }\n\n for (let i = 0; i < allRelPos2.length; i++) {\n let posX = 0;\n let posY = 0;\n if (i !== 0) {\n posX = Math.floor(i / mask2.width);\n posY = i % mask2.width;\n }\n if (mask2.getBitXY(posX, posY) === 1) {\n intersection.whitePixelsMask2.push(allRelPos2[i]);\n }\n }\n\n return intersection;\n}\n\n/**\n * Get relative position array for all pixels in masks\n * @param {Image} mask - a mask (1 bit image)\n * @param {Array} startPosition - start position of mask relative to parent\n * @return {Array} - relative position of all pixels\n * @private\n */\nfunction getRelativePositionForAllPixels(mask, startPosition) {\n let relativePositions = [];\n for (let i = 0; i < mask.height; i++) {\n for (let j = 0; j < mask.width; j++) {\n let originalPos = [i, j];\n relativePositions.push([\n originalPos[0] + startPosition[0],\n originalPos[1] + startPosition[1],\n ]);\n }\n }\n return relativePositions;\n}\n\n/**\n * Finds common surface for two arrays containing the positions of the pixels relative to parent image\n * @param {Array} positionArray1 - positions of pixels relative to parent\n * @param {Array} positionArray2 - positions of pixels relative to parent\n * @return {Array} - positions of common pixels for both arrays\n * @private\n */\nfunction getCommonSurface(positionArray1, positionArray2) {\n let i = 0;\n let j = 0;\n let commonSurface = [];\n while (i < positionArray1.length && j < positionArray2.length) {\n if (\n positionArray1[i][0] === positionArray2[j][0] &&\n positionArray1[i][1] === positionArray2[j][1]\n ) {\n commonSurface.push(positionArray1[i]);\n i++;\n j++;\n } else if (\n positionArray1[i][0] < positionArray2[j][0] ||\n (positionArray1[i][0] === positionArray2[j][0] &&\n positionArray1[i][1] < positionArray2[j][1])\n ) {\n i++;\n } else {\n j++;\n }\n }\n return commonSurface;\n}\n","/**\n * Finds common parent between two different masks\n * @memberof Image\n * @instance\n * @param {Image} mask - a mask (1 bit image)\n * @return {Image} - the lowest common parent of both masks\n */\nexport default function getClosestCommonParent(mask) {\n let depthMask1 = getDepth(this);\n let depthMask2 = getDepth(mask);\n\n let furthestParent;\n if (depthMask1 >= depthMask2) {\n furthestParent = getFurthestParent(this, depthMask1);\n } else {\n furthestParent = getFurthestParent(mask, depthMask2);\n }\n\n if (depthMask1 === 0 || depthMask2 === 0) {\n // comparing with at least one original image -> no common parent\n return furthestParent;\n }\n let m1 = this;\n let m2 = mask;\n\n while (depthMask1 !== depthMask2) {\n if (depthMask1 > depthMask2) {\n m1 = m1.parent;\n if (m1 === null) {\n return furthestParent;\n }\n depthMask1 = depthMask1 - 1;\n } else {\n m2 = m2.parent;\n if (m2 === null) {\n return furthestParent;\n }\n depthMask2 = depthMask2 - 1;\n }\n }\n\n while (m1 !== m2 && m1 !== null && m2 !== null) {\n m1 = m1.parent;\n m2 = m2.parent;\n if (m1 === null || m2 === null) {\n return furthestParent;\n }\n }\n\n // TODO\n // no common parent, use parent at top of hierarchy of m1\n // we assume it works for now\n if (m1 !== m2) {\n return furthestParent;\n }\n\n return m1;\n}\n\n/**\n * Find the depth of the mask with respect to its arborescence.\n * Helper function to find the common parent between two masks.\n * @param {Image} mask - a mask (1 bit Image)\n * @return {number} - depth of mask\n * @private\n */\nfunction getDepth(mask) {\n let d = 0;\n let m = mask;\n // a null parent means it's the original image\n while (m.parent != null) {\n m = m.parent;\n d++;\n }\n return d;\n}\n\nfunction getFurthestParent(mask, depth) {\n let m = mask;\n while (depth > 0) {\n m = m.parent;\n depth = depth - 1;\n }\n return m;\n}\n","const defaultOptions = {\n lowThreshold: 10,\n highThreshold: 30,\n gaussianBlur: 1.1\n};\n\nconst Gx = [\n [-1, 0, +1],\n [-2, 0, +2],\n [-1, 0, +1]\n];\n\nconst Gy = [\n [-1, -2, -1],\n [0, 0, 0],\n [+1, +2, +1]\n];\n\nconst convOptions = {\n bitDepth: 32,\n mode: 'periodic'\n};\n\nexport default function cannyEdgeDetector(image, options) {\n image.checkProcessable('Canny edge detector', {\n bitDepth: 8,\n channels: 1,\n components: 1\n });\n\n options = Object.assign({}, defaultOptions, options);\n\n const width = image.width;\n const height = image.height;\n const brightness = image.maxValue;\n\n const gfOptions = {\n sigma: options.gaussianBlur,\n radius: 3\n };\n\n const gf = image.gaussianFilter(gfOptions);\n\n const gradientX = gf.convolution(Gy, convOptions);\n const gradientY = gf.convolution(Gx, convOptions);\n\n const G = gradientY.hypotenuse(gradientX);\n\n const Image = image.constructor;\n\n const nms = new Image(width, height, {\n kind: 'GREY',\n bitDepth: 32\n });\n\n const edges = new Image(width, height, {\n kind: 'GREY',\n bitDepth: 32\n });\n\n const finalImage = new Image(width, height, {\n kind: 'GREY'\n });\n\n // Non-Maximum supression\n for (var i = 1; i < width - 1; i++) {\n for (var j = 1; j < height - 1; j++) {\n\n var dir = (Math.round(Math.atan2(gradientY.getValueXY(i, j, 0), gradientX.getValueXY(i, j, 0)) * (5.0 / Math.PI)) + 5) % 5;\n\n if (\n !((dir === 0 && (G.getValueXY(i, j, 0) <= G.getValueXY(i, j - 1, 0) || G.getValueXY(i, j, 0) <= G.getValueXY(i, j + 1, 0)))\n || (dir === 1 && (G.getValueXY(i, j, 0) <= G.getValueXY(i - 1, j + 1, 0) || G.getValueXY(i, j, 0) <= G.getValueXY(i + 1, j - 1, 0)))\n || (dir === 2 && (G.getValueXY(i, j, 0) <= G.getValueXY(i - 1, j, 0) || G.getValueXY(i, j, 0) <= G.getValueXY(i + 1, j, 0)))\n || (dir === 3 && (G.getValueXY(i, j, 0) <= G.getValueXY(i - 1, j - 1, 0) || G.getValueXY(i, j, 0) <= G.getValueXY(i + 1, j + 1, 0))))\n ) {\n nms.setValueXY(i, j, 0, G.getValueXY(i, j, 0));\n }\n }\n }\n\n for (i = 0; i < width * height; ++i) {\n var currentNms = nms.data[i];\n var currentEdge = 0;\n if (currentNms > options.highThreshold) {\n currentEdge++;\n finalImage.data[i] = brightness;\n }\n if (currentNms > options.lowThreshold) {\n currentEdge++;\n }\n\n edges.data[i] = currentEdge;\n }\n\n // Hysteresis: first pass\n var currentPixels = [];\n for (i = 1; i < width - 1; ++i) {\n for (j = 1; j < height - 1; ++j) {\n if (edges.getValueXY(i, j, 0) !== 1) {\n continue;\n }\n\n outer: for (var k = i - 1; k < i + 2; ++k) {\n for (var l = j - 1; l < j + 2; ++l) {\n if (edges.getValueXY(k, l, 0) === 2) {\n currentPixels.push([i, j]);\n finalImage.setValueXY(i, j, 0, brightness);\n break outer;\n }\n }\n }\n }\n }\n\n // Hysteresis: second pass\n while (currentPixels.length > 0) {\n var newPixels = [];\n for (i = 0; i < currentPixels.length; ++i) {\n for (j = -1; j < 2; ++j) {\n for (k = -1; k < 2; ++k) {\n if (j === 0 && k === 0) {\n continue;\n }\n var row = currentPixels[i][0] + j;\n var col = currentPixels[i][1] + k;\n if (edges.getValueXY(row, col, 0) === 1 && finalImage.getValueXY(row, col, 0) === 0) {\n newPixels.push([row, col]);\n finalImage.setValueXY(row, col, 0, brightness);\n }\n }\n }\n }\n currentPixels = newPixels;\n }\n\n return finalImage;\n}\n","import cannyEdgeDetector from 'canny-edge-detector';\n\n/**\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @return {Image}\n */\nexport default function cannyEdge(options) {\n return cannyEdgeDetector(this, options);\n}\n","import Image from '../Image';\n\n/**\n * Extracts a part of an original image based on a mask. By default the mask may contain\n * a relative position and this part of the original image will be extracted.\n * @memberof Image\n * @instance\n * @param {Image} mask - Image containing a binary mask\n * @param {object} [options]\n * @param {number[]} [options.position] - Array of 2 elements to force the x,y coordinates\n * @return {Image} A new image\n */\nexport default function extract(mask, options = {}) {\n let { position } = options;\n this.checkProcessable('extract', {\n bitDepth: [1, 8, 16],\n });\n\n // we need to find the relative position to the parent\n if (!position) {\n position = mask.getRelativePosition(this);\n if (!position) {\n throw new Error(\n 'extract : can not extract an image because the relative position can not be ' +\n 'determined, try to specify manually the position as an array of 2 elements [x,y].',\n );\n }\n }\n\n if (this.bitDepth > 1) {\n let extract = Image.createFrom(this, {\n width: mask.width,\n height: mask.height,\n alpha: 1, // we force the alpha, otherwise difficult to extract a mask ...\n position: position,\n parent: this,\n });\n\n for (let x = 0; x < mask.width; x++) {\n for (let y = 0; y < mask.height; y++) {\n // we copy the point\n for (let channel = 0; channel < this.channels; channel++) {\n let value = this.getValueXY(\n x + position[0],\n y + position[1],\n channel,\n );\n extract.setValueXY(x, y, channel, value);\n }\n // we make it transparent in case it is not in the mask\n if (!mask.getBitXY(x, y)) {\n extract.setValueXY(x, y, this.components, 0);\n }\n }\n }\n\n return extract;\n } else {\n let extract = Image.createFrom(this, {\n width: mask.width,\n height: mask.height,\n position: position,\n parent: this,\n });\n for (let y = 0; y < mask.height; y++) {\n for (let x = 0; x < mask.width; x++) {\n if (mask.getBitXY(x, y)) {\n if (this.getBitXY(x + position[0], y + position[1])) {\n extract.setBitXY(x, y);\n }\n }\n }\n }\n\n return extract;\n }\n}\n",";(function() { // closure for web browsers\n\nfunction Item (data, prev, next) {\n this.next = next\n if (next) next.prev = this\n this.prev = prev\n if (prev) prev.next = this\n this.data = data\n}\n\nfunction FastList () {\n if (!(this instanceof FastList)) return new FastList\n this._head = null\n this._tail = null\n this.length = 0\n}\n\nFastList.prototype =\n{ push: function (data) {\n this._tail = new Item(data, this._tail, null)\n if (!this._head) this._head = this._tail\n this.length ++\n }\n\n, pop: function () {\n if (this.length === 0) return undefined\n var t = this._tail\n this._tail = t.prev\n if (t.prev) {\n t.prev = this._tail.next = null\n }\n this.length --\n if (this.length === 1) this._head = this._tail\n else if (this.length === 0) this._head = this._tail = null\n return t.data\n }\n\n, unshift: function (data) {\n this._head = new Item(data, null, this._head)\n if (!this._tail) this._tail = this._head\n this.length ++\n }\n\n, shift: function () {\n if (this.length === 0) return undefined\n var h = this._head\n this._head = h.next\n if (h.next) {\n h.next = this._head.prev = null\n }\n this.length --\n if (this.length === 1) this._tail = this._head\n else if (this.length === 0) this._head = this._tail = null\n return h.data\n }\n\n, item: function (n) {\n if (n < 0) n = this.length + n\n var h = this._head\n while (n-- > 0 && h) h = h.next\n return h ? h.data : undefined\n }\n\n, slice: function (n, m) {\n if (!n) n = 0\n if (!m) m = this.length\n if (m < 0) m = this.length + m\n if (n < 0) n = this.length + n\n\n if (m === n) {\n return []\n }\n\n if (m < n) {\n throw new Error(\"invalid offset: \"+n+\",\"+m+\" (length=\"+this.length+\")\")\n }\n\n var len = m - n\n , ret = new Array(len)\n , i = 0\n , h = this._head\n while (n-- > 0 && h) h = h.next\n while (i < len && h) {\n ret[i++] = h.data\n h = h.next\n }\n return ret\n }\n\n, drop: function () {\n FastList.call(this)\n }\n\n, forEach: function (fn, thisp) {\n var p = this._head\n , i = 0\n , len = this.length\n while (i < len && p) {\n fn.call(thisp || this, p.data, i, this)\n p = p.next\n i ++\n }\n }\n\n, map: function (fn, thisp) {\n var n = new FastList()\n this.forEach(function (v, i, me) {\n n.push(fn.call(thisp || me, v, i, me))\n })\n return n\n }\n\n, filter: function (fn, thisp) {\n var n = new FastList()\n this.forEach(function (v, i, me) {\n if (fn.call(thisp || me, v, i, me)) n.push(v)\n })\n return n\n }\n\n, reduce: function (fn, val, thisp) {\n var i = 0\n , p = this._head\n , len = this.length\n if (!val) {\n i = 1\n val = p && p.data\n p = p && p.next\n }\n while (i < len && p) {\n val = fn.call(thisp || this, val, p.data, this)\n i ++\n p = p.next\n }\n return val\n }\n}\n\nif (\"undefined\" !== typeof(exports)) module.exports = FastList\nelse if (\"function\" === typeof(define) && define.amd) {\n define(\"FastList\", function() { return FastList })\n} else (function () { return this })().FastList = FastList\n\n})()\n","import LinkedList from 'fast-list';\n\nimport Image from '../Image';\n\nexport default function floodFill(options = {}) {\n const { x = 0, y = 0, inPlace = true } = options;\n\n const destination = inPlace ? this : Image.createFrom(this);\n\n this.checkProcessable('floodFill', { bitDepth: 1 });\n\n const bit = this.getBitXY(x, y);\n if (bit) return destination;\n const queue = new LinkedList();\n queue.push(new Node(x, y));\n while (queue.length > 0) {\n const node = queue.shift();\n destination.setBitXY(node.x, node.y);\n for (let i = node.x + 1; i < this.width; i++) {\n if (!destination.getBitXY(i, node.y) && !this.getBitXY(i, node.y)) {\n destination.setBitXY(i, node.y);\n if (node.y + 1 < this.height && !this.getBitXY(i, node.y + 1)) {\n queue.push(new Node(i, node.y + 1));\n }\n if (node.y - 1 >= 0 && !this.getBitXY(i, node.y - 1)) {\n queue.push(new Node(i, node.y - 1));\n }\n } else {\n break;\n }\n }\n // eslint-disable-next-line for-direction\n for (let i = node.x - 1; i >= 0; i++) {\n if (!destination.getBitXY(i, node.y) && !this.getBitXY(i, node.y)) {\n destination.setBitXY(i, node.y);\n if (node.y + 1 < this.height && !this.getBitXY(i, node.y + 1)) {\n queue.push(new Node(i, node.y + 1));\n }\n if (node.y - 1 >= 0 && !this.getBitXY(i, node.y - 1)) {\n queue.push(new Node(i, node.y - 1));\n }\n } else {\n break;\n }\n }\n }\n\n return destination;\n}\n\nfunction Node(x, y) {\n this.x = x;\n this.y = y;\n}\n","export default function _extends() {\n _extends = Object.assign || function (target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i];\n\n for (var key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n target[key] = source[key];\n }\n }\n }\n\n return target;\n };\n\n return _extends.apply(this, arguments);\n}","import _extends from '@babel/runtime/helpers/extends';\n\nfunction hex2rgb (hex) {\n if (hex[0] === '#') hex = hex.substr(1);\n\n if (hex.length === 3) {\n return {\n r: parseInt(hex[0] + hex[0], 16),\n g: parseInt(hex[1] + hex[1], 16),\n b: parseInt(hex[2] + hex[2], 16)\n };\n }\n\n return {\n r: parseInt(hex.substr(0, 2), 16),\n g: parseInt(hex.substr(2, 2), 16),\n b: parseInt(hex.substr(4, 2), 16)\n };\n}\n\nfunction hsv2rgb (h, s, v) {\n s = s / 100;\n v = v / 100;\n var rgb = [];\n var c = v * s;\n var hh = h / 60;\n var x = c * (1 - Math.abs(hh % 2 - 1));\n var m = v - c;\n\n if (hh >= 0 && hh < 1) {\n rgb = [c, x, 0];\n } else if (hh >= 1 && hh < 2) {\n rgb = [x, c, 0];\n } else if (hh >= 2 && hh < 3) {\n rgb = [0, c, x];\n } else if (h >= 3 && hh < 4) {\n rgb = [0, x, c];\n } else if (h >= 4 && hh < 5) {\n rgb = [x, 0, c];\n } else if (h >= 5 && hh <= 6) {\n rgb = [c, 0, x];\n } else {\n rgb = [0, 0, 0];\n }\n\n return {\n r: Math.round(255 * (rgb[0] + m)),\n g: Math.round(255 * (rgb[1] + m)),\n b: Math.round(255 * (rgb[2] + m))\n };\n}\n\nfunction convert(num) {\n var hex = num.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n}\n\nfunction rgb2hex (r, g, b) {\n return '#' + [convert(r), convert(g), convert(b)].join('');\n}\n\nfunction hsv2hex (h, s, v) {\n var rgb = hsv2rgb(h, s, v);\n return rgb2hex(rgb.r, rgb.g, rgb.b);\n}\n\nfunction rgb2hsv (r, g, b) {\n var h, s, v;\n var max = Math.max(r, g, b);\n var min = Math.min(r, g, b);\n var delta = max - min;\n\n if (delta === 0) {\n h = 0;\n } else if (r === max) {\n h = (g - b) / delta % 6;\n } else if (g === max) {\n h = (b - r) / delta + 2;\n } else {\n h = (r - g) / delta + 4;\n }\n\n h = Math.round(h * 60);\n if (h < 0) h += 360;\n s = Math.round((max === 0 ? 0 : delta / max) * 100);\n v = Math.round(max / 255 * 100);\n return {\n h: h,\n s: s,\n v: v\n };\n}\n\nfunction rgba (r, g, b, a) {\n return 'rgba(' + [r, g, b, a / 100].join(',') + ')';\n}\n\nfunction rgba2rgb (r, g, b, a) {\n a = a / 100;\n return {\n r: parseInt((1 - a) * 255 + a * r, 10),\n g: parseInt((1 - a) * 255 + a * g, 10),\n b: parseInt((1 - a) * 255 + a * b, 10)\n };\n}\n\nfunction rgba2hex (r, g, b, a) {\n var rgb = rgba2rgb(r, g, b, a);\n return rgb2hex(rgb.r, rgb.g, rgb.b);\n}\n\nfunction hsl2hsv (h, s, l) {\n s *= (l < 50 ? l : 100 - l) / 100;\n return {\n h: h,\n s: 2 * s / (l + s) * 100,\n v: l + s\n };\n}\n\nfunction hsv2hsl (h, s, v) {\n var hh = (200 - s) * v / 100;\n return {\n h: h,\n s: s * v / (hh < 100 ? hh : 200 - hh),\n l: hh / 2\n };\n}\n\nfunction hsl2rgb (h, s, l) {\n var hsv = hsl2hsv(h, s, l);\n return hsv2rgb(hsv.h, hsv.s, hsv.v);\n}\n\nvar colors = {\n aliceblue: [240, 248, 255],\n antiquewhite: [250, 235, 215],\n aqua: [0, 255, 255],\n aquamarine: [127, 255, 212],\n azure: [240, 255, 255],\n beige: [245, 245, 220],\n bisque: [255, 228, 196],\n black: [0, 0, 0],\n blanchedalmond: [255, 235, 205],\n blue: [0, 0, 255],\n blueviolet: [138, 43, 226],\n brown: [165, 42, 42],\n burlywood: [222, 184, 135],\n cadetblue: [95, 158, 160],\n chartreuse: [127, 255, 0],\n chocolate: [210, 105, 30],\n coral: [255, 127, 80],\n cornflowerblue: [100, 149, 237],\n cornsilk: [255, 248, 220],\n crimson: [220, 20, 60],\n cyan: [0, 255, 255],\n darkblue: [0, 0, 139],\n darkcyan: [0, 139, 139],\n darkgoldenrod: [184, 132, 11],\n darkgray: [169, 169, 169],\n darkgreen: [0, 100, 0],\n darkgrey: [169, 169, 169],\n darkkhaki: [189, 183, 107],\n darkmagenta: [139, 0, 139],\n darkolivegreen: [85, 107, 47],\n darkorange: [255, 140, 0],\n darkorchid: [153, 50, 204],\n darkred: [139, 0, 0],\n darksalmon: [233, 150, 122],\n darkseagreen: [143, 188, 143],\n darkslateblue: [72, 61, 139],\n darkslategray: [47, 79, 79],\n darkslategrey: [47, 79, 79],\n darkturquoise: [0, 206, 209],\n darkviolet: [148, 0, 211],\n deeppink: [255, 20, 147],\n deepskyblue: [0, 191, 255],\n dimgray: [105, 105, 105],\n dimgrey: [105, 105, 105],\n dodgerblue: [30, 144, 255],\n firebrick: [178, 34, 34],\n floralwhite: [255, 255, 240],\n forestgreen: [34, 139, 34],\n fuchsia: [255, 0, 255],\n gainsboro: [220, 220, 220],\n ghostwhite: [248, 248, 255],\n gold: [255, 215, 0],\n goldenrod: [218, 165, 32],\n gray: [128, 128, 128],\n green: [0, 128, 0],\n greenyellow: [173, 255, 47],\n grey: [128, 128, 128],\n honeydew: [240, 255, 240],\n hotpink: [255, 105, 180],\n indianred: [205, 92, 92],\n indigo: [75, 0, 130],\n ivory: [255, 255, 240],\n khaki: [240, 230, 140],\n lavender: [230, 230, 250],\n lavenderblush: [255, 240, 245],\n lawngreen: [124, 252, 0],\n lemonchiffon: [255, 250, 205],\n lightblue: [173, 216, 230],\n lightcoral: [240, 128, 128],\n lightcyan: [224, 255, 255],\n lightgoldenrodyellow: [250, 250, 210],\n lightgray: [211, 211, 211],\n lightgreen: [144, 238, 144],\n lightgrey: [211, 211, 211],\n lightpink: [255, 182, 193],\n lightsalmon: [255, 160, 122],\n lightseagreen: [32, 178, 170],\n lightskyblue: [135, 206, 250],\n lightslategray: [119, 136, 153],\n lightslategrey: [119, 136, 153],\n lightsteelblue: [176, 196, 222],\n lightyellow: [255, 255, 224],\n lime: [0, 255, 0],\n limegreen: [50, 205, 50],\n linen: [250, 240, 230],\n magenta: [255, 0, 255],\n maroon: [128, 0, 0],\n mediumaquamarine: [102, 205, 170],\n mediumblue: [0, 0, 205],\n mediumorchid: [186, 85, 211],\n mediumpurple: [147, 112, 219],\n mediumseagreen: [60, 179, 113],\n mediumslateblue: [123, 104, 238],\n mediumspringgreen: [0, 250, 154],\n mediumturquoise: [72, 209, 204],\n mediumvioletred: [199, 21, 133],\n midnightblue: [25, 25, 112],\n mintcream: [245, 255, 250],\n mistyrose: [255, 228, 225],\n moccasin: [255, 228, 181],\n navajowhite: [255, 222, 173],\n navy: [0, 0, 128],\n oldlace: [253, 245, 230],\n olive: [128, 128, 0],\n olivedrab: [107, 142, 35],\n orange: [255, 165, 0],\n orangered: [255, 69, 0],\n orchid: [218, 112, 214],\n palegoldenrod: [238, 232, 170],\n palegreen: [152, 251, 152],\n paleturquoise: [175, 238, 238],\n palevioletred: [219, 112, 147],\n papayawhip: [255, 239, 213],\n peachpuff: [255, 218, 185],\n peru: [205, 133, 63],\n pink: [255, 192, 203],\n plum: [221, 160, 203],\n powderblue: [176, 224, 230],\n purple: [128, 0, 128],\n rebeccapurple: [102, 51, 153],\n red: [255, 0, 0],\n rosybrown: [188, 143, 143],\n royalblue: [65, 105, 225],\n saddlebrown: [139, 69, 19],\n salmon: [250, 128, 114],\n sandybrown: [244, 164, 96],\n seagreen: [46, 139, 87],\n seashell: [255, 245, 238],\n sienna: [160, 82, 45],\n silver: [192, 192, 192],\n skyblue: [135, 206, 235],\n slateblue: [106, 90, 205],\n slategray: [119, 128, 144],\n slategrey: [119, 128, 144],\n snow: [255, 255, 250],\n springgreen: [0, 255, 127],\n steelblue: [70, 130, 180],\n tan: [210, 180, 140],\n teal: [0, 128, 128],\n thistle: [216, 191, 216],\n tomato: [255, 99, 71],\n turquoise: [64, 224, 208],\n violet: [238, 130, 238],\n wheat: [245, 222, 179],\n white: [255, 255, 255],\n whitesmoke: [245, 245, 245],\n yellow: [255, 255, 0],\n yellowgreen: [154, 205, 5]\n};\n\nfunction parse(str) {\n return named(str) || hex3(str) || hex6(str) || rgb(str) || rgba$1(str) || hsl(str) || hsla(str);\n}\n\nfunction named(str) {\n var c = colors[str.toLowerCase()];\n if (!c) return;\n return {\n r: c[0],\n g: c[1],\n b: c[2],\n a: 100\n };\n}\n\nfunction rgb(str) {\n var m = str.match(/rgb\\(([^)]+)\\)/);\n\n if (m) {\n var parts = m[1].split(/ *, */).map(Number);\n return {\n r: parts[0],\n g: parts[1],\n b: parts[2],\n a: 100\n };\n }\n}\n\nfunction rgba$1(str) {\n var m = str.match(/rgba\\(([^)]+)\\)/);\n\n if (m) {\n var parts = m[1].split(/ *, */).map(Number);\n return {\n r: parts[0],\n g: parts[1],\n b: parts[2],\n a: parts[3] * 100\n };\n }\n}\n\nfunction hex6(str) {\n if ('#' === str[0] && 7 === str.length) {\n return {\n r: parseInt(str.slice(1, 3), 16),\n g: parseInt(str.slice(3, 5), 16),\n b: parseInt(str.slice(5, 7), 16),\n a: 100\n };\n }\n}\n\nfunction hex3(str) {\n if ('#' === str[0] && 4 === str.length) {\n return {\n r: parseInt(str[1] + str[1], 16),\n g: parseInt(str[2] + str[2], 16),\n b: parseInt(str[3] + str[3], 16),\n a: 100\n };\n }\n}\n\nfunction hsl(str) {\n var m = str.match(/hsl\\(([^)]+)\\)/);\n\n if (m) {\n var parts = m[1].split(/ *, */);\n var h = parseInt(parts[0], 10);\n var s = parseInt(parts[1], 10);\n var l = parseInt(parts[2], 10);\n\n var _rgb = hsl2rgb(h, s, l);\n\n return _extends({}, _rgb, {\n a: 100\n });\n }\n}\n\nfunction hsla(str) {\n var m = str.match(/hsla\\(([^)]+)\\)/);\n\n if (m) {\n var parts = m[1].split(/ *, */);\n var h = parseInt(parts[0], 10);\n var s = parseInt(parts[1], 10);\n var l = parseInt(parts[2], 10);\n var a = parseInt(parseFloat(parts[3]) * 100, 10);\n\n var _rgb2 = hsl2rgb(h, s, l);\n\n return _extends({}, _rgb2, {\n a: a\n });\n }\n}\n\nfunction hex2hsv (hex) {\n var _hex2rgb = hex2rgb(hex),\n r = _hex2rgb.r,\n g = _hex2rgb.g,\n b = _hex2rgb.b;\n\n return rgb2hsv(r, g, b);\n}\n\nfunction hex2hsl (hex) {\n var _hex2hsv = hex2hsv(hex),\n h = _hex2hsv.h,\n s = _hex2hsv.s,\n v = _hex2hsv.v;\n\n return hsv2hsl(h, s, v);\n}\n\nfunction hex2alpha(aa) {\n return Math.round(parseInt('0x' + aa, 16) / 255 * 100);\n}\n\nexport { parse as cssColor, hex2alpha, hex2hsl, hex2hsv, hex2rgb, hsl2hsv, hsl2rgb, hsv2hex, hsv2hsl, hsv2rgb, rgb2hex, rgb2hsv, rgba, rgba2hex, rgba2rgb };\n","import { cssColor } from '@swiftcarrot/color-fns';\n\nexport function css2array(string) {\n let color = cssColor(string);\n return [color.r, color.g, color.b, Math.round((color.a * 255) / 100)];\n}\n\nfunction hue2rgb(p, q, t) {\n if (t < 0) {\n t += 1;\n }\n if (t > 1) {\n t -= 1;\n }\n if (t < 1 / 6) {\n return p + (q - p) * 6 * t;\n }\n if (t < 1 / 2) {\n return q;\n }\n if (t < 2 / 3) {\n return p + (q - p) * (2 / 3 - t) * 6;\n }\n return p;\n}\n\nfunction hsl2rgb(h, s, l) {\n let m1, m2, hue, r, g, b;\n s /= 100;\n l /= 100;\n\n if (s === 0) {\n r = g = b = l * 255;\n } else {\n if (l <= 0.5) {\n m2 = l * (s + 1);\n } else {\n m2 = l + s - l * s;\n }\n\n m1 = l * 2 - m2;\n hue = h / 360;\n r = hue2rgb(m1, m2, hue + 1 / 3);\n g = hue2rgb(m1, m2, hue);\n b = hue2rgb(m1, m2, hue - 1 / 3);\n }\n return { r: r, g: g, b: b };\n}\n\nexport function getDistinctColors(numColors) {\n let colors = new Array(numColors);\n let j = 0;\n for (let i = 0; i < 360; i += 360 / numColors) {\n j++;\n let color = hsl2rgb(i, 100, 30 + (j % 4) * 15);\n colors[j - 1] = [\n Math.round(color.r * 255),\n Math.round(color.g * 255),\n Math.round(color.b * 255),\n ];\n }\n return colors;\n}\n\nexport function getRandomColor() {\n return [\n Math.floor(Math.random() * 256),\n Math.floor(Math.random() * 256),\n Math.floor(Math.random() * 256),\n ];\n}\n\n/**\n * returns an array of colors based on various options\n * by default this methods return 50 distinct colors\n * @param {object} [options]\n * @param {Array|string} [options.color] - Array of 3 elements (R, G, B) or a valid css color.\n * @param {Array>|Array} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask\n * @param {boolean} [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined\n * @param {boolean} [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined\n * @param {boolean} [options.numberColors=50] - number of colors to generate by default\n * @return {Array} Array of colors\n * @private\n */\nexport function getColors(options) {\n let {\n color,\n colors,\n randomColors, // true / false\n numberColors = 50,\n } = options;\n\n if (color && !Array.isArray(color)) {\n color = css2array(color);\n }\n\n if (color) {\n return [color];\n }\n\n if (colors) {\n colors = colors.map(function (color) {\n if (!Array.isArray(color)) {\n return css2array(color);\n }\n return color;\n });\n return colors;\n }\n\n if (randomColors) {\n colors = new Array(numberColors);\n for (let i = 0; i < numberColors; i++) {\n colors[i] = getRandomColor();\n }\n }\n\n return getDistinctColors(numberColors);\n}\n","import { css2array } from '../../util/color';\nimport { RGB } from '../model/model';\n\n/**\n * Paint a mask or masks on the current image.\n * @memberof Image\n * @instance\n *\n * @param {Array} [labels] - Array of labels to display. Should the the same size as masks.\n * @param {Array} [positions] - Array of labels to display. Should the the same size as masks.\n * @param {object} [options]\n * @param {number[]|string} [options.color='red'] - Array of 3 elements (R, G, B) or a valid css color.\n * @param {Array>|Array} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask\n * @param {string|Array} [options.font='12px Helvetica'] - Paint the labels in a different CSS style\n * @param {number|Array} [options.rotate=0] - Rotate each label of a define angle\n * @return {this} The original painted image\n */\nexport default function paintLabels(labels, positions, options = {}) {\n let { color = 'blue', colors, font = '12px Helvetica', rotate = 0 } = options;\n\n this.checkProcessable('paintMasks', {\n channels: [3, 4],\n bitDepth: [8, 16],\n colorModel: RGB,\n });\n\n if (!Array.isArray(labels)) {\n throw Error('paintLabels: labels must be an array');\n }\n\n if (!Array.isArray(positions)) {\n throw Error('paintLabels: positions must be an array');\n }\n\n if (color && !Array.isArray(color)) {\n color = css2array(color);\n }\n\n if (colors) {\n colors = colors.map(function (color) {\n if (!Array.isArray(color)) {\n return css2array(color);\n }\n return color;\n });\n } else {\n colors = [color];\n }\n\n if (labels.length !== positions.length) {\n throw Error(\n 'paintLabels: positions and labels must be arrays from the same size',\n );\n }\n\n // We convert everything to array so that we can simply loop thourgh all the labels\n if (!Array.isArray(font)) font = [font];\n if (!Array.isArray(rotate)) rotate = [rotate];\n\n let canvas = this.getCanvas();\n let ctx = canvas.getContext('2d');\n for (let i = 0; i < labels.length; i++) {\n ctx.save();\n let color = colors[i % colors.length];\n ctx.fillStyle = `rgba(${color[0]},${color[1]},${color[2]},${\n color[3] / this.maxValue\n })`;\n ctx.font = font[i % font.length];\n let position = positions[i];\n ctx.translate(position[0], position[1]);\n ctx.rotate((rotate[i % rotate.length] / 180) * Math.PI);\n ctx.fillText(labels[i], 0, 0);\n ctx.restore();\n }\n this.data = Uint8Array.from(\n ctx.getImageData(0, 0, this.width, this.height).data,\n );\n\n return this;\n}\n","import { getColors } from '../../util/color';\nimport { RGB } from '../model/model';\n\n/**\n * Paint a mask or masks on the current image.\n * @memberof Image\n * @instance\n * @param {(Image|Array)} masks - Image containing a binary mask\n * @param {object} [options]\n * @param {Array|string} [options.color] - Array of 3 elements (R, G, B) or a valid css color.\n * @param {Array>|Array} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask\n * @param {boolean} [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined\n * @param {boolean} [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined\n * @param {number} [options.alpha=255] - Value from 0 to 255 to specify the alpha.\n * @param {Array} [options.labels] - Array of labels to display. Should the the same size as masks.\n * @param {Array>} [options.labelsPosition] - Array of points [x,y] where the labels should be displayed.\n * By default it is the 0,0 position of the correesponding mask.\n * @param {string} [options.labelColor='blue'] - Define the color to paint the labels\n * @param {string} [options.labelFont='12px Helvetica'] - Paint the labels in a different CSS style\n * @return {this} The original painted image\n */\nexport default function paintMasks(masks, options = {}) {\n let {\n alpha = 255,\n labels = [],\n labelsPosition = [],\n labelColor = 'blue',\n labelFont = '12px Helvetica',\n } = options;\n\n this.checkProcessable('paintMasks', {\n channels: [3, 4],\n bitDepth: [8, 16],\n colorModel: RGB,\n });\n\n let colors = getColors(\n Object.assign({}, options, { numberColors: masks.length }),\n );\n\n if (!Array.isArray(masks)) {\n masks = [masks];\n }\n\n for (let i = 0; i < masks.length; i++) {\n let mask = masks[i];\n // we need to find the parent image to calculate the relative position\n let color = colors[i % colors.length];\n for (let x = 0; x < mask.width; x++) {\n for (let y = 0; y < mask.height; y++) {\n if (mask.getBitXY(x, y)) {\n for (\n let component = 0;\n component < Math.min(this.components, color.length);\n component++\n ) {\n if (alpha === 255) {\n this.setValueXY(\n x + mask.position[0],\n y + mask.position[1],\n component,\n color[component],\n );\n } else {\n let value = this.getValueXY(\n x + mask.position[0],\n y + mask.position[1],\n component,\n );\n value = Math.round(\n (value * (255 - alpha) + color[component] * alpha) / 255,\n );\n this.setValueXY(\n x + mask.position[0],\n y + mask.position[1],\n component,\n value,\n );\n }\n }\n }\n }\n }\n }\n\n if (Array.isArray(labels) && labels.length > 0) {\n let canvas = this.getCanvas();\n let ctx = canvas.getContext('2d');\n ctx.fillStyle = labelColor;\n ctx.font = labelFont;\n for (let i = 0; i < Math.min(masks.length, labels.length); i++) {\n let position = labelsPosition[i] ? labelsPosition[i] : masks[i].position;\n ctx.fillText(labels[i], position[0], position[1]);\n }\n this.data = Uint8Array.from(\n ctx.getImageData(0, 0, this.width, this.height).data,\n );\n }\n\n return this;\n}\n","export default function zerosMatrix(height, width) {\n let matrix = new Array(height);\n for (let i = 0; i < height; i++) {\n matrix[i] = new Array(width).fill(0);\n }\n return matrix;\n}\n","import Image from '../image/Image';\nimport { BINARY } from '../image/core/kindNames';\n\nimport zerosMatrix from './zerosMatrix';\n\nconst cross = [\n [0, 0, 1, 0, 0],\n [0, 0, 1, 0, 0],\n [1, 1, 1, 1, 1],\n [0, 0, 1, 0, 0],\n [0, 0, 1, 0, 0],\n];\n\nconst smallCross = [\n [0, 1, 0],\n [1, 1, 1],\n [0, 1, 0],\n];\n\n/**\n * Class representing a shape\n * @class Shape\n * @param {object} [options]\n * @param {string} [options.kind='cross'] - Predefined matrix shape, 'cross' or 'smallCross'\n * @param {string} [options.shape] - Value may be 'square', 'rectangle', 'circle', 'ellipse' or 'triangle'\n * The size of the shape will be determined by the size, width and height.\n * A Shape is by default filled.\n * @param {number} [options.size]\n * @param {number} [options.width=options.size] - width of the shape. Must be odd.\n * @param {number} [options.height=options.size] - width of the shape. Must be odd.\n * @param {boolean} [options.filled=true] - If false only the border ot the shape is taken into account.\n */\nexport default class Shape {\n constructor(options = {}) {\n let { kind = 'cross', shape, size, width, height, filled = true } = options;\n if (size) {\n width = size;\n height = size;\n }\n\n if (shape) {\n switch (shape.toLowerCase()) {\n case 'square':\n case 'rectangle':\n this.matrix = rectangle(width, height, { filled });\n break;\n case 'circle':\n case 'ellipse':\n this.matrix = ellipse(width, height, { filled });\n break;\n case 'triangle':\n this.matrix = triangle(width, height, { filled });\n break;\n default:\n throw new Error(`Shape: unexpected shape: ${shape}`);\n }\n } else if (kind) {\n switch (kind.toLowerCase()) {\n case 'cross':\n this.matrix = cross;\n break;\n case 'smallcross':\n this.matrix = smallCross;\n break;\n default:\n throw new Error(`Shape: unexpected kind: ${kind}`);\n }\n } else {\n throw new Error('Shape: expected a kind or a shape option');\n }\n this.height = this.matrix.length;\n this.width = this.matrix[0].length;\n this.halfHeight = (this.height / 2) >> 0;\n this.halfWidth = (this.width / 2) >> 0;\n }\n\n /**\n * Returns an array of [x,y] points\n * @return {Array>} - Array of [x,y] points\n */\n getPoints() {\n let matrix = this.matrix;\n let points = [];\n for (let y = 0; y < matrix.length; y++) {\n for (let x = 0; x < matrix[0].length; x++) {\n if (matrix[y][x]) {\n points.push([x - this.halfWidth, y - this.halfHeight]);\n }\n }\n }\n return points;\n }\n\n /**\n * Returns a Mask (1 bit Image) corresponding to this shape.\n * @return {Image}\n */\n getMask() {\n let img = new Image(this.width, this.height, {\n kind: BINARY,\n });\n for (let y = 0; y < this.matrix.length; y++) {\n for (let x = 0; x < this.matrix[0].length; x++) {\n if (this.matrix[y][x]) {\n img.setBitXY(x, y);\n }\n }\n }\n return img;\n }\n}\n\nfunction rectangle(width, height, options) {\n const matrix = zerosMatrix(height, width);\n if (options.filled) {\n for (let y = 0; y < height; y++) {\n for (let x = 0; x < width; x++) {\n matrix[y][x] = 1;\n }\n }\n } else {\n for (let y of [0, height - 1]) {\n for (let x = 0; x < width; x++) {\n matrix[y][x] = 1;\n }\n }\n for (let y = 0; y < height; y++) {\n for (let x of [0, width - 1]) {\n matrix[y][x] = 1;\n }\n }\n }\n\n return matrix;\n}\n\nfunction ellipse(width, height, options) {\n const matrix = zerosMatrix(height, width, options);\n let yEven = 1 - (height % 2);\n let xEven = 1 - (width % 2);\n let a = Math.floor((width - 1) / 2); // horizontal ellipse axe\n let b = Math.floor((height - 1) / 2); // vertical ellipse axe\n let a2 = a * a;\n let b2 = b * b;\n if (options.filled) {\n for (let y = 0; y <= b; y++) {\n let shift = Math.floor(Math.sqrt(a2 - (a2 * y * y) / b2));\n for (let x = a - shift; x <= a; x++) {\n matrix[b - y][x] = 1;\n matrix[b + y + yEven][x] = 1;\n matrix[b - y][width - x - 1] = 1;\n matrix[b + y + yEven][width - x - 1] = 1;\n }\n }\n } else {\n for (let y = 0; y <= b; y++) {\n let shift = Math.floor(Math.sqrt(a2 - (a2 * y * y) / b2));\n let x = a - shift;\n matrix[b - y][x] = 1;\n matrix[b + y + yEven][x] = 1;\n matrix[b - y][width - x - 1] = 1;\n matrix[b + y + yEven][width - x - 1] = 1;\n }\n\n for (let x = 0; x <= a; x++) {\n let shift = Math.floor(Math.sqrt(b2 - (b2 * x * x) / a2));\n let y = b - shift;\n matrix[y][a - x] = 1;\n matrix[y][a + x + xEven] = 1;\n matrix[height - y - 1][a - x] = 1;\n matrix[height - y - 1][a + x + xEven] = 1;\n }\n }\n return matrix;\n}\n\nfunction triangle(width, height, options) {\n if (!options.filled) {\n throw new Error('Non filled triangle is not implemented');\n }\n const matrix = zerosMatrix(height, width, options);\n for (let y = 0; y < height; y++) {\n let shift = Math.floor(((1 - y / height) * width) / 2);\n for (let x = shift; x < width - shift; x++) {\n matrix[y][x] = 1;\n }\n }\n return matrix;\n}\n","import Shape from '../../util/Shape';\nimport { getColors } from '../../util/color';\n\n/**\n * Paint pixels on the current image.\n * @memberof Image\n * @instance\n * @param {Array>} points - Array of [x,y] points\n * @param {object} [options]\n * @param {Array|string} [options.color] - Array of 3 elements (R, G, B) or a valid css color.\n * @param {Array>|Array} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask\n * @param {boolean} [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined\n * @param {boolean} [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined\n * @param {object} [options.shape] - Definition of the shape, see Shape contructor.\n * @return {this} The original painted image\n */\nexport default function paintPoints(points, options = {}) {\n let { shape } = options;\n\n this.checkProcessable('paintPoints', {\n bitDepth: [8, 16],\n });\n\n let colors = getColors(\n Object.assign({}, options, { numberColors: points.length }),\n );\n\n let shapePixels = new Shape(shape).getPoints();\n\n let numberChannels = Math.min(this.channels, colors[0].length);\n\n for (let i = 0; i < points.length; i++) {\n let color = colors[i % colors.length];\n let xP = points[i][0];\n let yP = points[i][1];\n for (let j = 0; j < shapePixels.length; j++) {\n let xS = shapePixels[j][0];\n let yS = shapePixels[j][1];\n if (\n xP + xS >= 0 &&\n yP + yS >= 0 &&\n xP + xS < this.width &&\n yP + yS < this.height\n ) {\n let position = (xP + xS + (yP + yS) * this.width) * this.channels;\n for (let channel = 0; channel < numberChannels; channel++) {\n this.data[position + channel] = color[channel];\n }\n }\n }\n }\n\n return this;\n}\n","/**\n * Paint a polyline defined by an array of points.\n * @memberof Image\n * @instance\n * @param {Array>} points - Array of [x,y] points\n * @param {object} [options]\n * @param {Array} [options.color=[max,0,0]] - Array of 3 elements (R, G, B), default is red.\n * @param {boolean} [options.closed=false] - Close the polyline.\n * @return {this} The original painted image\n */\nexport default function paintPolyline(points, options = {}) {\n let { color = [this.maxValue, 0, 0], closed = false } = options;\n\n this.checkProcessable('paintPoints', {\n bitDepth: [1, 8, 16],\n });\n\n let numberChannels = Math.min(this.channels, color.length);\n\n for (let i = 0; i < points.length - 1 + closed; i++) {\n let from = points[i];\n let to = points[(i + 1) % points.length];\n\n let dx = to[0] - from[0];\n let dy = to[1] - from[1];\n let steps = Math.max(Math.abs(dx), Math.abs(dy));\n\n let xIncrement = dx / steps;\n let yIncrement = dy / steps;\n\n let x = from[0];\n let y = from[1];\n\n for (let j = 0; j <= steps; j++) {\n let xPoint = Math.round(x);\n let yPoint = Math.round(y);\n if (\n xPoint >= 0 &&\n yPoint >= 0 &&\n xPoint < this.width &&\n yPoint < this.height\n ) {\n if (this.bitDepth === 1) {\n this.setBitXY(xPoint, yPoint);\n } else {\n let position = (xPoint + yPoint * this.width) * this.channels;\n for (let channel = 0; channel < numberChannels; channel++) {\n this.data[position + channel] = color[channel];\n }\n }\n }\n\n x = x + xIncrement;\n y = y + yIncrement;\n }\n }\n\n return this;\n}\n","import { getColors } from '../../util/color';\n\n/**\n * Paint polylines on the current image.\n * @memberof Image\n * @instance\n * @param {Array>} polylines - Array of array of [x,y] points\n * @param {object} [options]\n * @param {Array|string} [options.color] - Array of 3 elements (R, G, B) or a valid css color.\n * @param {Array>|Array} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask\n * @param {boolean} [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined\n * @param {boolean} [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined\n * @param {object} [options.shape] - Definition of the shape, see Shape contructor.\n * @return {this} The original painted image\n */\nexport default function paintPolylines(polylines, options = {}) {\n let optionsCopy = Object.assign({}, options);\n\n this.checkProcessable('paintPolylines', {\n bitDepth: [8, 16],\n });\n\n let colors = getColors(\n Object.assign({}, options, { numberColors: polylines.length }),\n );\n\n for (let i = 0; i < polylines.length; i++) {\n optionsCopy.color = colors[i % colors.length];\n this.paintPolyline(polylines[i], optionsCopy);\n }\n\n return this;\n}\n","/**\n * Paint a polygon defined by an array of points.\n * @memberof Image\n * @instance\n * @param {Array>} points - Array of [x,y] points\n * @param {object} [options]\n * @param {Array} [options.color=[max,0,0]] - Array of 3 elements (R, G, B), default is red.\n * @param {Array} [options.filled=false] - If you want the polygon to be filled or not.\n * @return {this} The original painted image\n */\nexport default function paintPolygon(points, options = {}) {\n let { color = [this.maxValue, 0, 0], filled = false } = options;\n\n this.checkProcessable('paintPoints', {\n bitDepth: [1, 8, 16],\n });\n\n options.closed = true;\n\n let filteredPoints = deleteDouble(points);\n if (filled === false) {\n return this.paintPolyline(points, options);\n } else {\n let matrixBinary = Array(this.height);\n for (let i = 0; i < this.height; i++) {\n matrixBinary[i] = [];\n for (let j = 0; j < this.width; j++) {\n matrixBinary[i].push(0);\n }\n }\n for (let p = 0; p < filteredPoints.length; p++) {\n const line = lineBetweenTwoPoints(\n filteredPoints[p],\n filteredPoints[(p + 1) % filteredPoints.length],\n );\n for (let y = 0; y < this.height; y++) {\n for (let x = 0; x < this.width; x++) {\n if (isAtTheRightOfTheLine(x, y, line, this.height)) {\n matrixBinary[y][x] = matrixBinary[y][x] === 0 ? 1 : 0;\n }\n }\n }\n }\n for (let y = 0; y < this.height; y++) {\n for (let x = 0; x < this.width; x++) {\n if (matrixBinary[y][x] === 1) {\n if (this.bitDepth === 1) {\n this.setBitXY(x, y);\n } else {\n let numberChannels = Math.min(this.channels, color.length);\n let position = (x + y * this.width) * this.channels;\n for (let channel = 0; channel < numberChannels; channel++) {\n this.data[position + channel] = color[channel];\n }\n }\n }\n }\n }\n return this.paintPolyline(points, options);\n }\n}\n\nfunction deleteDouble(points) {\n let finalPoints = [];\n for (let i = 0; i < points.length; i++) {\n if (\n points[i][0] === points[(i + 1) % points.length][0] &&\n points[i][1] === points[(i + 1) % points.length][1]\n ) {\n continue;\n } else if (\n points[i][0] === points[(i - 1 + points.length) % points.length][0] &&\n points[i][1] === points[(i - 1 + points.length) % points.length][1]\n ) {\n continue;\n } else if (\n points[(i + 1) % points.length][0] ===\n points[(i - 1 + points.length) % points.length][0] &&\n points[(i - 1 + points.length) % points.length][1] ===\n points[(i + 1) % points.length][1]\n ) {\n continue; // we don't consider this point only\n } else {\n finalPoints.push(points[i]);\n }\n }\n return finalPoints;\n}\n\nfunction lineBetweenTwoPoints(p1, p2) {\n if (p1[0] === p2[0]) {\n return { a: 0, b: p1[0], vertical: true }; // we store the x of the vertical line into b\n } else {\n const coeffA = (p2[1] - p1[1]) / (p2[0] - p1[0]);\n const coeffB = p1[1] - coeffA * p1[0];\n return { a: coeffA, b: coeffB, vertical: false };\n }\n}\n\nfunction isAtTheRightOfTheLine(x, y, line, height) {\n if (line.vertical === true) {\n return line.b <= x;\n } else {\n if (line.a === 0) {\n return false;\n } else {\n const xline = (y - line.b) / line.a;\n return xline < x && xline >= 0 && xline <= height;\n }\n }\n}\n","import { getColors } from '../../util/color';\n\n/**\n * Paint an array of polygon on the current image.\n * @memberof Image\n * @instance\n * @param {Array>} polygons - Array of array of [x,y] points\n * @param {object} [options]\n * @param {Array|string} [options.color] - Array of 3 elements (R, G, B) or a valid css color.\n * @param {Array>|Array} [options.colors] - Array of Array of 3 elements (R, G, B) for each color of each mask\n * @param {boolean} [options.randomColors=true] - To paint each mask with a random color if color and colors are undefined\n * @param {boolean} [options.distinctColors=false] - To paint each mask with a different color if color and colors are undefined\n * @param {object} [options.shape] - Definition of the shape, see Shape contructor.\n * @return {this} The original painted image\n */\nexport default function paintPolygons(polygons, options = {}) {\n let optionsCopy = Object.assign({}, options);\n\n this.checkProcessable('paintPolygons', {\n bitDepth: [8, 16],\n });\n\n let colors = getColors(\n Object.assign({}, options, { numberColors: polygons.length }),\n );\n\n for (let i = 0; i < polygons.length; i++) {\n optionsCopy.color = colors[i % colors.length];\n this.paintPolygon(polygons[i], optionsCopy);\n }\n\n return this;\n}\n","import isInteger from 'is-integer';\nimport newArray from 'new-array';\n\n/**\n * Returns a histogram for the specified channel\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.maxSlots=256]\n * @param {number} [options.channel]\n * @param {boolean} [options.useAlpha=true]\n * @return {number[]}\n */\nexport function getHistogram(options = {}) {\n let { maxSlots = 256, channel, useAlpha = true } = options;\n this.checkProcessable('getHistogram', {\n bitDepth: [1, 8, 16],\n });\n if (channel === undefined) {\n if (this.components > 1) {\n throw new RangeError(\n 'You need to define the channel for an image that contains more than one channel',\n );\n }\n channel = 0;\n }\n return getChannelHistogram.call(this, channel, { useAlpha, maxSlots });\n}\n\n/**\n * Returns an array (number of channels) of array (number of slots) containing\n * the number of data of a specific intensity.\n * Intensity may be grouped by the maxSlots parameter.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.maxSlots] - Number of slots in the resulting\n * array. The intensity will be evently distributed between 0 and\n * the maxValue allowed for this image (255 for usual images).\n * If maxSlots = 8, all the intensities between 0 and 31 will be\n * placed in the slot 0, 32 to 63 in slot 1, ...\n * @return {Array>}\n * @example\n * image.getHistograms({\n * maxSlots: 8,\n * useAlpha: false\n * });\n */\nexport function getHistograms(options = {}) {\n const { maxSlots = 256, useAlpha = true } = options;\n this.checkProcessable('getHistograms', {\n bitDepth: [8, 16],\n });\n let results = new Array(useAlpha ? this.components : this.channels);\n for (let i = 0; i < results.length; i++) {\n results[i] = getChannelHistogram.call(this, i, { useAlpha, maxSlots });\n }\n return results;\n}\n\nfunction getChannelHistogram(channel, options) {\n let { useAlpha, maxSlots } = options;\n\n // for a mask, return a number array containing count of black and white points (black = array[0], white = array[1])\n\n if (this.bitDepth === 1) {\n let blackWhiteCount = [0, 0];\n for (let i = 0; i < this.height; i++) {\n for (let j = 0; j < this.width; j++) {\n let value = this.getBitXY(i, j);\n if (value === 0) {\n blackWhiteCount[0] += 1;\n } else if (value === 1) {\n blackWhiteCount[1] += 1;\n }\n }\n }\n return blackWhiteCount;\n }\n\n let bitSlots = Math.log2(maxSlots);\n if (!isInteger(bitSlots)) {\n throw new RangeError(\n 'maxSlots must be a power of 2, for example: 64, 256, 1024',\n );\n }\n // we will compare the bitSlots to the bitDepth of the image\n // based on this we will shift the values. This allows to generate a histogram\n // of 16 grey even if the images has 256 shade of grey\n\n let bitShift = 0;\n if (this.bitDepth > bitSlots) {\n bitShift = this.bitDepth - bitSlots;\n }\n\n let data = this.data;\n let result = newArray(Math.pow(2, Math.min(this.bitDepth, bitSlots)), 0);\n if (useAlpha && this.alpha) {\n let alphaChannelDiff = this.channels - channel - 1;\n\n for (let i = channel; i < data.length; i += this.channels) {\n result[data[i] >> bitShift] += data[i + alphaChannelDiff] / this.maxValue;\n }\n } else {\n for (let i = channel; i < data.length; i += this.channels) {\n result[data[i] >> bitShift]++;\n }\n }\n\n return result;\n}\n","import newArray from 'new-array';\n\n/**\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {boolean} [options.useAlpha=true]\n * @param {number} [options.nbSlots=512]\n * @return {number[]}\n */\nexport default function getColorHistogram(options = {}) {\n let { useAlpha = true, nbSlots = 512 } = options;\n\n this.checkProcessable('getColorHistogram', {\n bitDepth: [8, 16],\n components: [3],\n });\n\n let nbSlotsCheck = Math.log(nbSlots) / Math.log(8);\n if (nbSlotsCheck !== Math.floor(nbSlotsCheck)) {\n throw new RangeError(\n 'nbSlots must be a power of 8. Usually 8, 64, 512 or 4096',\n );\n }\n\n let bitShift = this.bitDepth - nbSlotsCheck;\n\n let data = this.data;\n let result = newArray(Math.pow(8, nbSlotsCheck), 0);\n let factor2 = Math.pow(2, nbSlotsCheck * 2);\n let factor1 = Math.pow(2, nbSlotsCheck);\n\n for (let i = 0; i < data.length; i += this.channels) {\n let slot =\n (data[i] >> bitShift) * factor2 +\n (data[i + 1] >> bitShift) * factor1 +\n (data[i + 2] >> bitShift);\n if (useAlpha && this.alpha) {\n result[slot] += data[i + this.channels - 1] / this.maxValue;\n } else {\n result[slot]++;\n }\n }\n\n return result;\n}\n","import newArray from 'new-array';\n\n/**\n * Returns an array with the minimal value of each channel\n * @memberof Image\n * @instance\n * @return {number[]} Array having has size the number of channels\n */\nexport default function min() {\n this.checkProcessable('min', {\n bitDepth: [8, 16, 32],\n });\n\n let result = newArray(this.channels, +Infinity);\n\n for (let i = 0; i < this.data.length; i += this.channels) {\n for (let c = 0; c < this.channels; c++) {\n if (this.data[i + c] < result[c]) {\n result[c] = this.data[i + c];\n }\n }\n }\n return result;\n}\n","import newArray from 'new-array';\n\n/**\n * Returns an array with the maximal value of each channel\n * @memberof Image\n * @instance\n * @return {number[]} Array having has size the number of channels\n */\nexport default function max() {\n this.checkProcessable('max', {\n bitDepth: [8, 16, 32],\n });\n\n let result = newArray(this.channels, -Infinity);\n\n for (let i = 0; i < this.data.length; i += this.channels) {\n for (let c = 0; c < this.channels; c++) {\n if (this.data[i + c] > result[c]) {\n result[c] = this.data[i + c];\n }\n }\n }\n return result;\n}\n","import newArray from 'new-array';\n\n/**\n * Returns an array with the sum of the values of each channel\n * @memberof Image\n * @instance\n * @return {number[]} Array having has size the number of channels\n */\nexport default function sum() {\n this.checkProcessable('sum', {\n bitDepth: [8, 16],\n });\n\n let result = newArray(this.channels, 0);\n\n for (let i = 0; i < this.data.length; i += this.channels) {\n for (let c = 0; c < this.channels; c++) {\n result[c] += this.data[i + c];\n }\n }\n return result;\n}\n","/**\n * Returns the moment of an image (https://en.wikipedia.org/wiki/Image_moment)\n * @memberof Image\n * @instance\n * @param {number} [xPower=0]\n * @param {number} [yPower=0]\n * @return {number}\n */\nexport default function getMoment(xPower = 0, yPower = 0) {\n this.checkProcessable('getMoment', {\n bitDepth: [1],\n });\n\n let m = 0;\n\n for (let x = 0; x < this.width; x++) {\n for (let y = 0; y < this.height; y++) {\n if (this.getBitXY(x, y) === 1) {\n m += x ** xPower * y ** yPower;\n }\n }\n }\n return m;\n}\n","/**\n * Returns an array of object with position.\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Image} [options.mask] - Region of the image that is analyzed. The rest is omitted.\n * @param {number} [options.region=3] - 1, 2 or 3. Define the region around each points that is analyzed. 1 corresponds to 4 cross points, 2 to\n * the 8 points around and 3 to the 12 points around the central pixel.\n * @param {number} [options.removeClosePoints=0] - Remove pts which have a distance between them smaller than this param.\n * @param {boolean} [options.invert=false] - Search for minima instead of maxima\n * @param {number} [options.maxEquals=2] - Maximal number of values that may be equal to the maximum\n * @return {number[]} Array whose size is the number of channels\n */\nexport default function localMaxima(options = {}) {\n let {\n mask,\n region = 3,\n removeClosePoints = 0,\n invert = false,\n maxEquals = 2,\n } = options;\n let image = this;\n this.checkProcessable('localMaxima', {\n bitDepth: [8, 16],\n components: 1,\n });\n region *= 4;\n\n let maskExpectedValue = invert ? 0 : 1;\n\n let dx = [+1, 0, -1, 0, +1, +1, -1, -1, +2, 0, -2, 0, +2, +2, -2, -2];\n let dy = [0, +1, 0, -1, +1, -1, +1, -1, 0, +2, 0, -2, +2, -2, +2, -2];\n let shift = region <= 8 ? 1 : 2;\n let points = [];\n for (let currentY = shift; currentY < image.height - shift; currentY++) {\n for (let currentX = shift; currentX < image.width - shift; currentX++) {\n if (mask && mask.getBitXY(currentX, currentY) !== maskExpectedValue) {\n continue;\n }\n let counter = 0;\n let nbEquals = 0;\n let currentValue = image.data[currentX + currentY * image.width];\n for (let dir = 0; dir < region; dir++) {\n if (invert) {\n // we search for minima\n if (\n image.data[\n currentX + dx[dir] + (currentY + dy[dir]) * image.width\n ] > currentValue\n ) {\n counter++;\n }\n } else {\n if (\n image.data[\n currentX + dx[dir] + (currentY + dy[dir]) * image.width\n ] < currentValue\n ) {\n counter++;\n }\n }\n if (\n image.data[\n currentX + dx[dir] + (currentY + dy[dir]) * image.width\n ] === currentValue\n ) {\n nbEquals++;\n }\n }\n if (counter + nbEquals === region && nbEquals <= maxEquals) {\n points.push([currentX, currentY]);\n }\n }\n }\n // TODO How to make a more performant and general way\n // we don't deal correctly here with groups of points that should be grouped if at the\n // beginning one of them is closer to another\n // Seems that we would ened to calculate a matrix and then split this matrix in 'independant matrices'\n // Or to assign a cluster to each point and regroup them if 2 clusters are close to each other\n // later approach seems much better\n if (removeClosePoints > 0) {\n for (let i = 0; i < points.length; i++) {\n for (let j = i + 1; j < points.length; j++) {\n if (\n Math.sqrt(\n Math.pow(points[i][0] - points[j][0], 2) +\n Math.pow(points[i][1] - points[j][1], 2),\n ) < removeClosePoints\n ) {\n points[i][0] = (points[i][0] + points[j][0]) >> 1;\n points[i][1] = (points[i][1] + points[j][1]) >> 1;\n points.splice(j, 1);\n j--;\n }\n }\n }\n }\n return points;\n}\n","import { mean as histogramMean } from '../../util/histogram';\n\n/**\n * Returns an array with the average value of each channel\n * @memberof Image\n * @instance\n * @return {number[]} Array having has size the number of channels\n */\nexport default function mean() {\n let histograms = this.getHistograms({ maxSlots: this.maxValue + 1 });\n let result = new Array(histograms.length);\n for (let c = 0; c < histograms.length; c++) {\n let histogram = histograms[c];\n result[c] = histogramMean(histogram);\n }\n return result;\n}\n","import { median as histogramMedian } from '../../util/histogram';\n\n/**\n * Returns an array with the median value of each channel\n * @memberof Image\n * @instance\n * @return {number[]} Array having has size the number of channels\n */\nexport default function median() {\n let histograms = this.getHistograms({ maxSlots: this.maxValue + 1 });\n let result = new Array(histograms.length);\n for (let c = 0; c < histograms.length; c++) {\n let histogram = histograms[c];\n result[c] = histogramMedian(histogram);\n }\n return result;\n}\n","/**\n * Allows to generate an array of points for a binary image (bit depth = 1)\n * @memberof Image\n * @instance\n * @return {Array>} - an array of [x,y] corresponding to the set pixels in the binary image\n */\nexport default function points() {\n this.checkProcessable('points', {\n bitDepth: [1],\n });\n\n const pixels = [];\n for (let x = 0; x < this.width; x++) {\n for (let y = 0; y < this.height; y++) {\n if (this.getBitXY(x, y) === 1) {\n pixels.push([x, y]);\n }\n }\n }\n return pixels;\n}\n","/**\n * Allows to generate an array of points for a binary image (bit depth = 1)\n * The points consider the beginning and the end of each pixel\n * @memberof Image\n * @instance\n * @return {Array>} - an array of [x,y] corresponding to the set pixels in the binary image\n */\nexport default function extendedPoints() {\n this.checkProcessable('extendedPoints', {\n bitDepth: [1],\n });\n\n const pixels = [];\n for (let y = 0; y < this.height; y++) {\n for (let x = 0; x < this.width; x++) {\n if (this.getBitXY(x, y) === 1) {\n pixels.push([x, y]);\n if (this.getBitXY(x + 1, y) !== 1) {\n pixels.push([x + 1, y]);\n pixels.push([x + 1, y + 1]);\n if (this.getBitXY(x, y + 1) !== 1) {\n pixels.push([x, y + 1]);\n }\n } else {\n if (this.getBitXY(x, y + 1) !== 1) {\n pixels.push([x, y + 1]);\n pixels.push([x + 1, y + 1]);\n }\n }\n }\n }\n }\n return pixels;\n}\n","/**\n * An image may be derived from another image either by a crop\n * or because it is a ROI (region of interest)\n * Also a region of interest can be reprocessed to generated another\n * set of region of interests.\n * It is therefore important to keep the hierarchy of images to know\n * which image is derived from which one and be able to get the\n * relative position of one image in another\n * This methods takes care of this.\n * @memberof Image\n * @instance\n * @param {Image} targetImage\n * @param {object} [options={}]\n * @param {boolean} [options.defaultFurther=false] If set to true and no parent found returns the relative position\n * to the further parent\n * @return {number[]|boolean}\n */\nexport default function getRelativePosition(targetImage, options = {}) {\n if (this === targetImage) {\n return [0, 0];\n }\n let position = [0, 0];\n\n let currentImage = this;\n while (currentImage) {\n if (currentImage === targetImage) {\n return position;\n }\n if (currentImage.position) {\n position[0] += currentImage.position[0];\n position[1] += currentImage.position[1];\n }\n currentImage = currentImage.parent;\n }\n // we should never reach this place, this means we could not find the parent\n // throw Error('Parent image was not found, can not get relative position.')\n if (options.defaultFurther) return position;\n\n return false;\n}\n","/**\n * Returns the number of transparent pixels\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {number} [options.alpha=1] - Value of the alpha value to count.\n * @return {number} Number of transparent pixels\n */\nexport default function countAlphaPixels(options = {}) {\n let { alpha = 1 } = options;\n this.checkProcessable('countAlphaPixels', {\n bitDepth: [8, 16],\n alpha: 1,\n });\n\n let count = 0;\n\n if (alpha !== undefined) {\n for (let i = this.components; i < this.data.length; i += this.channels) {\n if (this.data[i] === alpha) {\n count++;\n }\n }\n return count;\n } else {\n // because there is an alpha channel all the pixels have an alpha\n return this.size;\n }\n}\n","/**\n * Computes the convex hull of a binary image using Andrew's Monotone Chain Algorithm\n * http://www.algorithmist.com/index.php/Monotone_Chain_Convex_Hull\n * @param {Array>} points - An array of points (two elements arrays)\n * @param {object} [options]\n * @param {boolean} [options.sorted=false]\n * @return {Array>} Coordinates of the convex hull in clockwise order\n */\nexport default function monotoneChainConvexHull(points, options = {}) {\n if (!options.sorted) {\n points.sort(byXThenY);\n }\n\n const n = points.length;\n const result = new Array(n * 2);\n var k = 0;\n\n for (var i = 0; i < n; i++) {\n const point = points[i];\n while (k >= 2 && cw(result[k - 2], result[k - 1], point) <= 0) {\n k--;\n }\n result[k++] = point;\n }\n\n const t = k + 1;\n for (i = n - 2; i >= 0; i--) {\n const point = points[i];\n while (k >= t && cw(result[k - 2], result[k - 1], point) <= 0) {\n k--;\n }\n result[k++] = point;\n }\n\n return result.slice(0, k - 1);\n}\n\nfunction cw(p1, p2, p3) {\n return (p2[1] - p1[1]) * (p3[0] - p1[0]) - (p2[0] - p1[0]) * (p3[1] - p1[1]);\n}\n\nfunction byXThenY(point1, point2) {\n if (point1[0] === point2[0]) {\n return point1[1] - point2[1];\n }\n return point1[0] - point2[0];\n}\n","import mcch from 'monotone-chain-convex-hull';\n\n/**\n * Returns the convex hull of a binary image\n * @memberof Image\n * @instance\n * @return {Array>}\n */\nexport default function monotoneChainConvexHull() {\n return mcch(this.extendedPoints, { sorted: false });\n}\n","/**\n * Rounds all the x and y values of an array of points\n * @param {Array>} points\n * @return {Array>} modified input value\n * @private\n */\nexport function round(points) {\n for (let i = 0; i < points.length; i++) {\n points[i][0] = Math.round(points[i][0]);\n points[i][1] = Math.round(points[i][1]);\n }\n return points;\n}\n\n/**\n * Calculates a new point that is the difference p1 - p2\n * @param {Array} p1\n * @param {Array} p2\n * @return {Array}\n * @private\n */\nexport function difference(p1, p2) {\n return [p1[0] - p2[0], p1[1] - p2[1]];\n}\n\n/**\n * Normalize a point\n * @param {Array} p\n * @return {Array}\n * @private\n */\nexport function normalize(p) {\n let length = Math.sqrt(p[0] ** 2 + p[1] ** 2);\n return [p[0] / length, p[1] / length];\n}\n\n/**\n * We rotate an array of points\n * @param {number} radians\n * @param {Array>} srcPoints\n * @param {Array>} destPoints\n * @return {Array>}\n * @private\n */\nexport function rotate(radians, srcPoints, destPoints) {\n if (destPoints === undefined) destPoints = new Array(srcPoints.length);\n let cos = Math.cos(radians);\n let sin = Math.sin(radians);\n for (let i = 0; i < destPoints.length; ++i) {\n destPoints[i] = [\n cos * srcPoints[i][0] - sin * srcPoints[i][1],\n sin * srcPoints[i][0] + cos * srcPoints[i][1],\n ];\n }\n return destPoints;\n}\n\n/**\n * Dot products of 2 points assuming vectors starting from (0,0)\n * @param {Array} p1\n * @param {Array} p2\n * @return {number}\n * @private\n */\nexport function dot(p1, p2) {\n return p1[0] * p2[0] + p1[1] * p2[1];\n}\n\n/**\n * Returns the angle between 3 points. The first one is a common point\n * @param {Array} origin\n * @param {Array} p1\n * @param {Array} p2\n * @return {number}\n * @private\n */\nexport function angle(origin, p1, p2) {\n let v1 = normalize(difference(p1, origin));\n let v2 = normalize(difference(p2, origin));\n let dotProduct = dot(v1, v2);\n // TODO this code is not correct because it may yield the opposite angle\n return Math.acos(dotProduct);\n}\n\n/**\n * Returns the 4 points of an horizontal rectangle that includes all the points\n * @param {Array>} points\n * @return {Array>}\n * @private\n */\nexport function boundary(points) {\n let minMaxValues = minMax(points);\n let xMin = minMaxValues[0][0];\n let yMin = minMaxValues[0][1];\n let xMax = minMaxValues[1][0];\n let yMax = minMaxValues[1][1];\n return [\n [xMin, yMin],\n [xMax, yMin],\n [xMax, yMax],\n [xMin, yMax],\n ];\n}\n\n/**\n * Returns the perimeter represented by the points (a polygon)\n * @param {Array>} points\n */\nexport function perimeter(vertices) {\n let total = 0;\n for (let i = 0; i < vertices.length; i++) {\n let fromX = vertices[i][0];\n let fromY = vertices[i][1];\n let toX = vertices[i === vertices.length - 1 ? 0 : i + 1][0];\n let toY = vertices[i === vertices.length - 1 ? 0 : i + 1][1];\n total += Math.sqrt((toX - fromX) ** 2 + (toY - fromY) ** 2);\n }\n return total;\n}\n\n/**\n * Returns the surface represented by the points (a polygon)\n * @param {Array>} points\n */\nexport function surface(vertices) {\n let total = 0;\n\n for (let i = 0; i < vertices.length; i++) {\n let addX = vertices[i][0];\n let addY = vertices[i === vertices.length - 1 ? 0 : i + 1][1];\n let subX = vertices[i === vertices.length - 1 ? 0 : i + 1][0];\n let subY = vertices[i][1];\n\n total += addX * addY * 0.5;\n total -= subX * subY * 0.5;\n }\n\n return Math.abs(total);\n}\n\n/**\n * Returns 2 points with minimal and maximal XY\n * @param {Array>} points\n * @return {Array>}\n * @private\n */\nexport function minMax(points) {\n let xMin = +Infinity;\n let yMin = +Infinity;\n let xMax = -Infinity;\n let yMax = -Infinity;\n for (let i = 0; i < points.length; i++) {\n if (points[i][0] < xMin) xMin = points[i][0];\n if (points[i][0] > xMax) xMax = points[i][0];\n if (points[i][1] < yMin) yMin = points[i][1];\n if (points[i][1] > yMax) yMax = points[i][1];\n }\n return [\n [xMin, yMin],\n [xMax, yMax],\n ];\n}\n\n/**\n * Moves the minX, minY to 0,0\n * All the points will be positive after this move\n * @param {Array>} srcPoints\n * @param {Array>} destPoints\n * @return {Array>}\n * @private\n */\nexport function moveToZeroZero(srcPoints, destPoints) {\n if (destPoints === undefined) {\n destPoints = new Array(srcPoints.length).fill(0).map(() => []);\n }\n let minMaxValues = minMax(srcPoints);\n let xMin = minMaxValues[0][0];\n let yMin = minMaxValues[0][1];\n for (let i = 0; i < srcPoints.length; i++) {\n destPoints[i][0] = srcPoints[i][0] - xMin;\n destPoints[i][1] = srcPoints[i][1] - yMin;\n }\n return destPoints;\n}\n","import { rotate, difference, normalize } from '../../util/points';\n\nimport convexHullFunction from './monotoneChainConvexHull';\n\n/**\n * Computes the minimum bounding box around a binary image\n * https://www.researchgate.net/profile/Lennert_Den_Boer2/publication/303783472_A_Fast_Algorithm_for_Generating_a_Minimal_Bounding_Rectangle/links/5751a14108ae6807fafb2aa5.pdf\n * @memberof Image\n * @instance\n * @param {object} [options]\n * @param {Array>} [options.originalPoints]\n * @return {Array>}\n */\nexport default function minimalBoundingRectangle(options = {}) {\n const { originalPoints = convexHullFunction.call(this) } = options;\n if (originalPoints.length === 0) {\n return [];\n }\n\n if (originalPoints.length === 1) {\n return [\n originalPoints[0],\n originalPoints[0],\n originalPoints[0],\n originalPoints[0],\n ];\n }\n\n const p = new Array(originalPoints.length);\n\n let minSurface = +Infinity;\n let minSurfaceAngle = 0;\n let mbr;\n\n for (let i = 0; i < p.length; i++) {\n let angle = getAngle(originalPoints[i], originalPoints[(i + 1) % p.length]);\n\n rotate(-angle, originalPoints, p);\n\n // we rotate and translate so that this axe is in the bottom\n let aX = p[i][0];\n let aY = p[i][1];\n let bX = p[(i + 1) % p.length][0];\n let bY = p[(i + 1) % p.length][1];\n\n let tUndefined = true;\n let tMin = 0;\n let tMax = 0;\n let maxWidth = 0;\n for (let j = 0; j < p.length; j++) {\n let cX = p[j][0];\n let cY = p[j][1];\n let t = (cX - aX) / (bX - aX);\n if (tUndefined === true) {\n tUndefined = false;\n tMin = t;\n tMax = t;\n } else {\n if (t < tMin) tMin = t;\n if (t > tMax) tMax = t;\n }\n let width = (-(bX - aX) * cY + bX * aY - bY * aX) / (bX - aX);\n\n if (Math.abs(width) > Math.abs(maxWidth)) maxWidth = width;\n }\n let pMin = [aX + tMin * (bX - aX), aY];\n let pMax = [aX + tMax * (bX - aX), aY];\n\n let currentSurface = Math.abs(maxWidth * (tMin - tMax) * (bX - aX));\n\n if (currentSurface < minSurface) {\n minSurfaceAngle = angle;\n minSurface = currentSurface;\n mbr = [\n pMin,\n pMax,\n [pMax[0], pMax[1] - maxWidth],\n [pMin[0], pMin[1] - maxWidth],\n ];\n }\n }\n rotate(minSurfaceAngle, mbr, mbr);\n return mbr;\n}\n\n// the angle that allows to make the line going through p1 and p2 horizontal\n// this is an optimized version because it assume one vector is horizontal\nfunction getAngle(p1, p2) {\n let diff = difference(p2, p1);\n let vector = normalize(diff);\n let angle = Math.acos(vector[0]);\n if (vector[1] < 0) return -angle;\n return angle;\n}\n","/* eslint-disable import/order */\n\n// filters\nimport absFilter from './filter/abs';\nimport invertFilter from './filter/invert';\nimport flipXFilter from './filter/flipX';\nimport flipYFilter from './filter/flipY';\nimport blurFilter from './filter/blurFilter';\nimport medianFilter from './filter/medianFilter';\nimport gaussianFilter from './filter/gaussianFilter';\nimport sobelFilter from './filter/sobelFilter';\nimport scharrFilter from './filter/scharrFilter';\nimport gradientFilter from './filter/gradientFilter';\nimport levelFilter from './filter/level';\nimport addFilter from './filter/add';\nimport subtractFilter from './filter/subtract';\nimport subtractImage from './filter/subtractImage';\nimport hypotenuseFilter from './filter/hypotenuse';\nimport multiplyFilter from './filter/multiply';\nimport divideFilter from './filter/divide';\nimport backgroundFilter from './filter/background';\n\n// morphology transforms\nimport dilate from './morphology/dilate';\nimport erode from './morphology/erode';\nimport open from './morphology/open';\nimport close from './morphology/close';\nimport topHat from './morphology/topHat';\nimport blackHat from './morphology/blackHat';\nimport morphologicalGradient from './morphology/morphologicalGradient';\n\n// transforms\nimport warpingFourPoints from './transform/warping';\nimport crop from './transform/crop';\nimport cropAlpha from './transform/cropAlpha';\nimport resize from './transform/resize/resize';\nimport hsv from './transform/hsv';\nimport hsl from './transform/hsl';\nimport cmyk from './transform/cmyk';\nimport rgba8 from './transform/rgba8';\nimport grey from './transform/grey';\nimport mask from './transform/mask/mask';\nimport pad from './transform/pad';\nimport colorDepth from './transform/colorDepth';\nimport { rotate, rotateLeft, rotateRight } from './transform/rotate';\nimport insert from './transform/insert';\n\n// utility\nimport setBorder from './utility/setBorder';\nimport split from './utility/split';\nimport getChannel from './utility/getChannel';\nimport combineChannels from './utility/combineChannels';\nimport setChannel from './utility/setChannel';\nimport getSimilarity from './utility/getSimilarity';\nimport getPixelsGrid from './utility/getPixelsGrid';\nimport getBestMatch from './utility/getBestMatch';\nimport getRow from './utility/getRow';\nimport getColumn from './utility/getColumn';\nimport getMatrix from './utility/getMatrix';\nimport setMatrix from './utility/setMatrix';\nimport getPixelsArray from './utility/getPixelsArray';\nimport getIntersection from './utility/getIntersection';\nimport getClosestCommonParent from './utility/getClosestCommonParent';\nimport getThreshold from './utility/getThreshold';\n\n// operators\nimport cannyEdge from './operator/cannyEdge';\nimport convolution from './operator/convolution';\nimport extract from './operator/extract';\nimport floodFill from './operator/floodFill';\nimport paintLabels from './operator/paintLabels';\nimport paintMasks from './operator/paintMasks';\nimport paintPoints from './operator/paintPoints';\nimport paintPolyline from './operator/paintPolyline';\nimport paintPolylines from './operator/paintPolylines';\nimport paintPolygon from './operator/paintPolygon';\nimport paintPolygons from './operator/paintPolygons';\n\n// computers\nimport { getHistogram, getHistograms } from './compute/histogram';\nimport getColorHistogram from './compute/colorHistogram';\nimport getMin from './compute/min';\nimport getMax from './compute/max';\nimport getSum from './compute/sum';\nimport getMoment from './compute/moment';\nimport getLocalMaxima from './compute/localMaxima';\nimport getMean from './compute/mean';\nimport getMedian from './compute/median';\nimport getPoints from './compute/points';\nimport getExtendedPoints from './compute/extendedPoints';\nimport getRelativePosition from './compute/relativePosition';\nimport countAlphaPixels from './compute/countAlphaPixels';\nimport monotoneChainConvexHull from './compute/monotoneChainConvexHull';\nimport minimalBoundingRectangle from './compute/minimalBoundingRectangle';\n\nexport default function extend(Image) {\n let inPlace = { inPlace: true };\n\n Image.extendMethod('invert', invertFilter);\n Image.extendMethod('abs', absFilter);\n Image.extendMethod('level', levelFilter, inPlace);\n Image.extendMethod('add', addFilter, inPlace);\n Image.extendMethod('subtract', subtractFilter, inPlace);\n Image.extendMethod('subtractImage', subtractImage);\n Image.extendMethod('multiply', multiplyFilter, inPlace);\n Image.extendMethod('divide', divideFilter, inPlace);\n Image.extendMethod('hypotenuse', hypotenuseFilter);\n Image.extendMethod('background', backgroundFilter);\n Image.extendMethod('flipX', flipXFilter);\n Image.extendMethod('flipY', flipYFilter);\n\n Image.extendMethod('blurFilter', blurFilter);\n Image.extendMethod('medianFilter', medianFilter);\n Image.extendMethod('gaussianFilter', gaussianFilter);\n Image.extendMethod('sobelFilter', sobelFilter);\n Image.extendMethod('gradientFilter', gradientFilter);\n Image.extendMethod('scharrFilter', scharrFilter);\n\n Image.extendMethod('dilate', dilate);\n Image.extendMethod('erode', erode);\n Image.extendMethod('open', open);\n Image.extendMethod('close', close);\n Image.extendMethod('topHat', topHat);\n Image.extendMethod('blackHat', blackHat);\n Image.extendMethod('morphologicalGradient', morphologicalGradient);\n\n Image.extendMethod('warpingFourPoints', warpingFourPoints);\n Image.extendMethod('crop', crop);\n Image.extendMethod('cropAlpha', cropAlpha);\n Image.extendMethod('resize', resize).extendMethod('scale', resize);\n Image.extendMethod('hsv', hsv);\n Image.extendMethod('hsl', hsl);\n Image.extendMethod('cmyk', cmyk);\n Image.extendMethod('rgba8', rgba8);\n Image.extendMethod('grey', grey).extendMethod('gray', grey);\n Image.extendMethod('mask', mask);\n Image.extendMethod('pad', pad);\n Image.extendMethod('colorDepth', colorDepth);\n Image.extendMethod('setBorder', setBorder, inPlace);\n Image.extendMethod('rotate', rotate);\n Image.extendMethod('rotateLeft', rotateLeft);\n Image.extendMethod('rotateRight', rotateRight);\n Image.extendMethod('insert', insert);\n\n Image.extendMethod('getRow', getRow);\n Image.extendMethod('getColumn', getColumn);\n Image.extendMethod('getMatrix', getMatrix);\n Image.extendMethod('setMatrix', setMatrix);\n Image.extendMethod('getPixelsArray', getPixelsArray);\n Image.extendMethod('getIntersection', getIntersection);\n Image.extendMethod('getClosestCommonParent', getClosestCommonParent);\n Image.extendMethod('getThreshold', getThreshold);\n\n Image.extendMethod('split', split);\n Image.extendMethod('getChannel', getChannel);\n Image.extendMethod('combineChannels', combineChannels);\n Image.extendMethod('setChannel', setChannel);\n Image.extendMethod('getSimilarity', getSimilarity);\n Image.extendMethod('getPixelsGrid', getPixelsGrid);\n Image.extendMethod('getBestMatch', getBestMatch);\n\n Image.extendMethod('cannyEdge', cannyEdge);\n Image.extendMethod('convolution', convolution);\n Image.extendMethod('extract', extract);\n Image.extendMethod('floodFill', floodFill);\n Image.extendMethod('paintLabels', paintLabels, inPlace);\n Image.extendMethod('paintMasks', paintMasks, inPlace);\n Image.extendMethod('paintPoints', paintPoints, inPlace);\n Image.extendMethod('paintPolyline', paintPolyline, inPlace);\n Image.extendMethod('paintPolylines', paintPolylines, inPlace);\n Image.extendMethod('paintPolygon', paintPolygon, inPlace);\n Image.extendMethod('paintPolygons', paintPolygons, inPlace);\n\n Image.extendMethod('countAlphaPixels', countAlphaPixels);\n Image.extendMethod('monotoneChainConvexHull', monotoneChainConvexHull);\n Image.extendMethod('minimalBoundingRectangle', minimalBoundingRectangle);\n Image.extendMethod('getHistogram', getHistogram).extendProperty(\n 'histogram',\n getHistogram,\n );\n Image.extendMethod('getHistograms', getHistograms).extendProperty(\n 'histograms',\n getHistograms,\n );\n Image.extendMethod('getColorHistogram', getColorHistogram).extendProperty(\n 'colorHistogram',\n getColorHistogram,\n );\n Image.extendMethod('getMin', getMin).extendProperty('min', getMin);\n Image.extendMethod('getMax', getMax).extendProperty('max', getMax);\n Image.extendMethod('getSum', getSum).extendProperty('sum', getSum);\n Image.extendMethod('getMoment', getMoment).extendProperty(\n 'moment',\n getMoment,\n );\n Image.extendMethod('getLocalMaxima', getLocalMaxima);\n Image.extendMethod('getMedian', getMedian).extendProperty(\n 'median',\n getMedian,\n );\n Image.extendMethod('getMean', getMean).extendProperty('mean', getMean);\n Image.extendMethod('getPoints', getPoints).extendProperty(\n 'points',\n getPoints,\n );\n Image.extendMethod('getExtendedPoints', getExtendedPoints).extendProperty(\n 'extendedPoints',\n getExtendedPoints,\n );\n Image.extendMethod('getRelativePosition', getRelativePosition);\n}\n","/*\nThe MIT License (MIT)\nCopyright © 2006-2007 Kevin C. Olbrich\nCopyright © 2010-2016 LIM SAS (http://lim.eu) - Julien Sanchez\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :\n typeof define === 'function' && define.amd ? define(factory) :\n (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.Qty = factory());\n}(this, (function () { 'use strict';\n\n /**\n * Tests if a value is a string\n *\n * @param {*} value - Value to test\n *\n * @returns {boolean} true if value is a string, false otherwise\n */\n function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n }\n\n /*\n * Prefer stricter Number.isFinite if currently supported.\n * To be dropped when ES6 is finalized. Obsolete browsers will\n * have to use ES6 polyfills.\n */\n var isFiniteImpl = Number.isFinite || window.isFinite;\n /**\n * Tests if a value is a number\n *\n * @param {*} value - Value to test\n *\n * @returns {boolean} true if value is a number, false otherwise\n */\n function isNumber(value) {\n // Number.isFinite allows not to consider NaN or '1' as numbers\n return isFiniteImpl(value);\n }\n\n /*\n * Identity function\n */\n function identity(value) {\n return value;\n }\n\n /**\n * Returns unique strings from list\n *\n * @param {string[]} strings - array of strings\n *\n *\n * @returns {string[]} a new array of strings without duplicates\n */\n function uniq(strings) {\n var seen = {};\n return strings.filter(function(item) {\n return seen.hasOwnProperty(item) ? false : (seen[item] = true);\n });\n }\n\n function compareArray(array1, array2) {\n if (array2.length !== array1.length) {\n return false;\n }\n for (var i = 0; i < array1.length; i++) {\n if (array2[i].compareArray) {\n if (!array2[i].compareArray(array1[i])) {\n return false;\n }\n }\n if (array2[i] !== array1[i]) {\n return false;\n }\n }\n return true;\n }\n\n function assign(target, properties) {\n Object.keys(properties).forEach(function(key) {\n target[key] = properties[key];\n });\n }\n\n /**\n * Safely multiplies numbers while avoiding floating errors\n * like 0.1 * 0.1 => 0.010000000000000002\n *\n * @param {...number} numbers - numbers to multiply\n *\n * @returns {number} result\n */\n function mulSafe() {\n var result = 1, decimals = 0;\n for (var i = 0; i < arguments.length; i++) {\n var arg = arguments[i];\n decimals = decimals + getFractional(arg);\n result *= arg;\n }\n\n return decimals !== 0 ? round(result, decimals) : result;\n }\n\n /**\n * Safely divides two numbers while avoiding floating errors\n * like 0.3 / 0.05 => 5.999999999999999\n *\n * @returns {number} result\n * @param {number} num Numerator\n * @param {number} den Denominator\n */\n function divSafe(num, den) {\n if (den === 0) {\n throw new Error(\"Divide by zero\");\n }\n\n var factor = Math.pow(10, getFractional(den));\n var invDen = factor / (factor * den);\n\n return mulSafe(num, invDen);\n }\n\n /**\n * Rounds value at the specified number of decimals\n *\n * @param {number} val - value to round\n * @param {number} decimals - number of decimals\n *\n * @returns {number} rounded number\n */\n function round(val, decimals) {\n return Math.round(val * Math.pow(10, decimals)) / Math.pow(10, decimals);\n }\n\n function getFractional(num) {\n // Check for NaNs or Infinities\n if (!isFinite(num)) {\n return 0;\n }\n\n // Faster than parsing strings\n // http://jsperf.com/count-decimals/2\n var count = 0;\n while (num % 1 !== 0) {\n num *= 10;\n count++;\n }\n return count;\n }\n\n /**\n * Custom error type definition\n * @constructor\n */\n function QtyError() {\n var err;\n if (!this) { // Allows to instantiate QtyError without new()\n err = Object.create(QtyError.prototype);\n QtyError.apply(err, arguments);\n return err;\n }\n err = Error.apply(this, arguments);\n this.name = \"QtyError\";\n this.message = err.message;\n this.stack = err.stack;\n }\n QtyError.prototype = Object.create(Error.prototype, {constructor: { value: QtyError }});\n\n /*\n * Throws incompatible units error\n * @param {string} left - units\n * @param {string} right - units incompatible with first argument\n * @throws \"Incompatible units\" error\n */\n function throwIncompatibleUnits(left, right) {\n throw new QtyError(\"Incompatible units: \" + left + \" and \" + right);\n }\n\n var UNITS = {\n /* prefixes */\n \"\" : [[\"googol\"], 1e100, \"prefix\"],\n \"\" : [[\"Ki\",\"Kibi\",\"kibi\"], Math.pow(2,10), \"prefix\"],\n \"\" : [[\"Mi\",\"Mebi\",\"mebi\"], Math.pow(2,20), \"prefix\"],\n \"\" : [[\"Gi\",\"Gibi\",\"gibi\"], Math.pow(2,30), \"prefix\"],\n \"\" : [[\"Ti\",\"Tebi\",\"tebi\"], Math.pow(2,40), \"prefix\"],\n \"\" : [[\"Pi\",\"Pebi\",\"pebi\"], Math.pow(2,50), \"prefix\"],\n \"\" : [[\"Ei\",\"Exi\",\"exi\"], Math.pow(2,60), \"prefix\"],\n \"\" : [[\"Zi\",\"Zebi\",\"zebi\"], Math.pow(2,70), \"prefix\"],\n \"\" : [[\"Yi\",\"Yebi\",\"yebi\"], Math.pow(2,80), \"prefix\"],\n \"\" : [[\"Y\",\"Yotta\",\"yotta\"], 1e24, \"prefix\"],\n \"\" : [[\"Z\",\"Zetta\",\"zetta\"], 1e21, \"prefix\"],\n \"\" : [[\"E\",\"Exa\",\"exa\"], 1e18, \"prefix\"],\n \"\" : [[\"P\",\"Peta\",\"peta\"], 1e15, \"prefix\"],\n \"\" : [[\"T\",\"Tera\",\"tera\"], 1e12, \"prefix\"],\n \"\" : [[\"G\",\"Giga\",\"giga\"], 1e9, \"prefix\"],\n \"\" : [[\"M\",\"Mega\",\"mega\"], 1e6, \"prefix\"],\n \"\" : [[\"k\",\"kilo\"], 1e3, \"prefix\"],\n \"\" : [[\"h\",\"Hecto\",\"hecto\"], 1e2, \"prefix\"],\n \"\" : [[\"da\",\"Deca\",\"deca\",\"deka\"], 1e1, \"prefix\"],\n \"\" : [[\"d\",\"Deci\",\"deci\"], 1e-1, \"prefix\"],\n \"\" : [[\"c\",\"Centi\",\"centi\"], 1e-2, \"prefix\"],\n \"\" : [[\"m\",\"Milli\",\"milli\"], 1e-3, \"prefix\"],\n \"\" : [\n [\"u\",\"\\u03BC\"/*µ as greek letter*/,\"\\u00B5\"/*µ as micro sign*/,\"Micro\",\"mc\",\"micro\"],\n 1e-6,\n \"prefix\"\n ],\n \"\" : [[\"n\",\"Nano\",\"nano\"], 1e-9, \"prefix\"],\n \"\" : [[\"p\",\"Pico\",\"pico\"], 1e-12, \"prefix\"],\n \"\" : [[\"f\",\"Femto\",\"femto\"], 1e-15, \"prefix\"],\n \"\" : [[\"a\",\"Atto\",\"atto\"], 1e-18, \"prefix\"],\n \"\" : [[\"z\",\"Zepto\",\"zepto\"], 1e-21, \"prefix\"],\n \"\" : [[\"y\",\"Yocto\",\"yocto\"], 1e-24, \"prefix\"],\n\n \"<1>\" : [[\"1\", \"<1>\"], 1, \"\"],\n /* length units */\n \"\" : [[\"m\",\"meter\",\"meters\",\"metre\",\"metres\"], 1.0, \"length\", [\"\"] ],\n \"\" : [[\"in\",\"inch\",\"inches\",\"\\\"\"], 0.0254, \"length\", [\"\"]],\n \"\" : [[\"ft\",\"foot\",\"feet\",\"'\"], 0.3048, \"length\", [\"\"]],\n \"\" : [[\"yd\",\"yard\",\"yards\"], 0.9144, \"length\", [\"\"]],\n \"\" : [[\"mi\",\"mile\",\"miles\"], 1609.344, \"length\", [\"\"]],\n \"\" : [[\"nmi\",\"naut-mile\"], 1852, \"length\", [\"\"]],\n \"\": [[\"league\",\"leagues\"], 4828, \"length\", [\"\"]],\n \"\": [[\"furlong\",\"furlongs\"], 201.2, \"length\", [\"\"]],\n \"\" : [[\"rd\",\"rod\",\"rods\"], 5.029, \"length\", [\"\"]],\n \"\" : [[\"mil\",\"mils\"], 0.0000254, \"length\", [\"\"]],\n \"\" :[[\"ang\",\"angstrom\",\"angstroms\"], 1e-10, \"length\", [\"\"]],\n \"\" : [[\"fathom\",\"fathoms\"], 1.829, \"length\", [\"\"]],\n \"\" : [[\"pica\",\"picas\"], 0.00423333333, \"length\", [\"\"]],\n \"\" : [[\"pt\",\"point\",\"points\"], 0.000352777778, \"length\", [\"\"]],\n \"\" : [[\"z\",\"red-shift\", \"redshift\"], 1.302773e26, \"length\", [\"\"]],\n \"\" : [[\"AU\",\"astronomical-unit\"], 149597900000, \"length\", [\"\"]],\n \"\":[[\"ls\",\"light-second\"], 299792500, \"length\", [\"\"]],\n \"\":[[\"lmin\",\"light-minute\"], 17987550000, \"length\", [\"\"]],\n \"\" : [[\"ly\",\"light-year\"], 9460528000000000, \"length\", [\"\"]],\n \"\" : [[\"pc\",\"parsec\",\"parsecs\"], 30856780000000000, \"length\", [\"\"]],\n \"\" : [[\"DM\",\"datamile\"], 1828.8, \"length\", [\"\"]],\n\n /* mass */\n \"\" : [[\"kg\",\"kilogram\",\"kilograms\"], 1.0, \"mass\", [\"\"]],\n \"\" : [[\"u\",\"AMU\",\"amu\"], 1.660538921e-27, \"mass\", [\"\"]],\n \"\" : [[\"Da\",\"Dalton\",\"Daltons\",\"dalton\",\"daltons\"], 1.660538921e-27, \"mass\", [\"\"]],\n \"\" : [[\"slug\",\"slugs\"], 14.5939029, \"mass\", [\"\"]],\n \"\" : [[\"tn\",\"ton\",\"short-ton\"], 907.18474, \"mass\", [\"\"]],\n \"\":[[\"tonne\",\"metric-ton\"], 1000, \"mass\", [\"\"]],\n \"\" : [[\"ct\",\"carat\",\"carats\"], 0.0002, \"mass\", [\"\"]],\n \"\" : [[\"lbs\",\"lb\",\"pound\",\"pounds\",\"#\"], 0.45359237, \"mass\", [\"\"]],\n \"\" : [[\"oz\",\"ounce\",\"ounces\"], 0.0283495231, \"mass\", [\"\"]],\n \"\" : [[\"g\",\"gram\",\"grams\",\"gramme\",\"grammes\"], 1e-3, \"mass\", [\"\"]],\n \"\" : [[\"grain\",\"grains\",\"gr\"], 6.479891e-5, \"mass\", [\"\"]],\n \"\" : [[\"dram\",\"drams\",\"dr\"], 0.0017718452, \"mass\",[\"\"]],\n \"\" : [[\"stone\",\"stones\",\"st\"],6.35029318, \"mass\",[\"\"]],\n\n /* area */\n \"\":[[\"hectare\"], 10000, \"area\", [\"\",\"\"]],\n \"\":[[\"acre\",\"acres\"], 4046.85642, \"area\", [\"\",\"\"]],\n \"\":[[\"sqft\"], 1, \"area\", [\"\",\"\"]],\n\n /* volume */\n \"\" : [[\"l\",\"L\",\"liter\",\"liters\",\"litre\",\"litres\"], 0.001, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"gal\",\"gallon\",\"gallons\"], 0.0037854118, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"galimp\",\"gallon-imp\",\"gallons-imp\"], 0.0045460900, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"qt\",\"quart\",\"quarts\"], 0.00094635295, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"pt\",\"pint\",\"pints\"], 0.000473176475, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"ptimp\",\"pint-imp\",\"pints-imp\"], 5.6826125e-4, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"cu\",\"cup\",\"cups\"], 0.000236588238, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"floz\",\"fluid-ounce\",\"fluid-ounces\"], 2.95735297e-5, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"flozimp\", \"floz-imp\",\"fluid-ounce-imp\",\"fluid-ounces-imp\"], 2.84130625e-5, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"tb\",\"tbsp\",\"tbs\",\"tablespoon\",\"tablespoons\"], 1.47867648e-5, \"volume\", [\"\",\"\",\"\"]],\n \"\": [[\"tsp\",\"teaspoon\",\"teaspoons\"], 4.92892161e-6, \"volume\", [\"\",\"\",\"\"]],\n \"