Encapsulates the result of decoding a barcode within an image.
\n *\n * @author Sean Owen\n */\nvar Result = /** @class */ (function () {\n // public constructor(private text: string,\n // Uint8Array rawBytes,\n // ResultPoconst resultPoints: Int32Array,\n // BarcodeFormat format) {\n // this(text, rawBytes, resultPoints, format, System.currentTimeMillis())\n // }\n // public constructor(text: string,\n // Uint8Array rawBytes,\n // ResultPoconst resultPoints: Int32Array,\n // BarcodeFormat format,\n // long timestamp) {\n // this(text, rawBytes, rawBytes == null ? 0 : 8 * rawBytes.length,\n // resultPoints, format, timestamp)\n // }\n function Result(text, rawBytes, numBits, resultPoints, format, timestamp) {\n if (numBits === void 0) { numBits = rawBytes == null ? 0 : 8 * rawBytes.length; }\n if (timestamp === void 0) { timestamp = System.currentTimeMillis(); }\n this.text = text;\n this.rawBytes = rawBytes;\n this.numBits = numBits;\n this.resultPoints = resultPoints;\n this.format = format;\n this.timestamp = timestamp;\n this.text = text;\n this.rawBytes = rawBytes;\n if (undefined === numBits || null === numBits) {\n this.numBits = (rawBytes === null || rawBytes === undefined) ? 0 : 8 * rawBytes.length;\n }\n else {\n this.numBits = numBits;\n }\n this.resultPoints = resultPoints;\n this.format = format;\n this.resultMetadata = null;\n if (undefined === timestamp || null === timestamp) {\n this.timestamp = System.currentTimeMillis();\n }\n else {\n this.timestamp = timestamp;\n }\n }\n /**\n * @return raw text encoded by the barcode\n */\n Result.prototype.getText = function () {\n return this.text;\n };\n /**\n * @return raw bytes encoded by the barcode, if applicable, otherwise {@code null}\n */\n Result.prototype.getRawBytes = function () {\n return this.rawBytes;\n };\n /**\n * @return how many bits of {@link #getRawBytes()} are valid; typically 8 times its length\n * @since 3.3.0\n */\n Result.prototype.getNumBits = function () {\n return this.numBits;\n };\n /**\n * @return points related to the barcode in the image. These are typically points\n * identifying finder patterns or the corners of the barcode. The exact meaning is\n * specific to the type of barcode that was decoded.\n */\n Result.prototype.getResultPoints = function () {\n return this.resultPoints;\n };\n /**\n * @return {@link BarcodeFormat} representing the format of the barcode that was decoded\n */\n Result.prototype.getBarcodeFormat = function () {\n return this.format;\n };\n /**\n * @return {@link Map} mapping {@link ResultMetadataType} keys to values. May be\n * {@code null}. This contains optional metadata about what was detected about the barcode,\n * like orientation.\n */\n Result.prototype.getResultMetadata = function () {\n return this.resultMetadata;\n };\n Result.prototype.putMetadata = function (type, value) {\n if (this.resultMetadata === null) {\n this.resultMetadata = new Map();\n }\n this.resultMetadata.set(type, value);\n };\n Result.prototype.putAllMetadata = function (metadata) {\n if (metadata !== null) {\n if (this.resultMetadata === null) {\n this.resultMetadata = metadata;\n }\n else {\n this.resultMetadata = new Map(metadata);\n }\n }\n };\n Result.prototype.addResultPoints = function (newPoints) {\n var oldPoints = this.resultPoints;\n if (oldPoints === null) {\n this.resultPoints = newPoints;\n }\n else if (newPoints !== null && newPoints.length > 0) {\n var allPoints = new Array(oldPoints.length + newPoints.length);\n System.arraycopy(oldPoints, 0, allPoints, 0, oldPoints.length);\n System.arraycopy(newPoints, 0, allPoints, oldPoints.length, newPoints.length);\n this.resultPoints = allPoints;\n }\n };\n Result.prototype.getTimestamp = function () {\n return this.timestamp;\n };\n /*@Override*/\n Result.prototype.toString = function () {\n return this.text;\n };\n return Result;\n}());\nexport default Result;\n","/*\n * Copyright 2008 ZXing authors\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/*namespace com.google.zxing {*/\n/**\n * Represents some type of metadata about the result of the decoding that the decoder\n * wishes to communicate back to the caller.\n *\n * @author Sean Owen\n */\nvar ResultMetadataType;\n(function (ResultMetadataType) {\n /**\n * Unspecified, application-specific metadata. Maps to an unspecified {@link Object}.\n */\n ResultMetadataType[ResultMetadataType[\"OTHER\"] = 0] = \"OTHER\";\n /**\n * Denotes the likely approximate orientation of the barcode in the image. This value\n * is given as degrees rotated clockwise from the normal, upright orientation.\n * For example a 1D barcode which was found by reading top-to-bottom would be\n * said to have orientation \"90\". This key maps to an {@link Integer} whose\n * value is in the range [0,360).\n */\n ResultMetadataType[ResultMetadataType[\"ORIENTATION\"] = 1] = \"ORIENTATION\";\n /**\n *2D barcode formats typically encode text, but allow for a sort of 'byte mode'\n * which is sometimes used to encode binary data. While {@link Result} makes available\n * the complete raw bytes in the barcode for these formats, it does not offer the bytes\n * from the byte segments alone.
\n *\n *This maps to a {@link java.util.List} of byte arrays corresponding to the\n * raw bytes in the byte segments in the barcode, in order.
\n */\n ResultMetadataType[ResultMetadataType[\"BYTE_SEGMENTS\"] = 2] = \"BYTE_SEGMENTS\";\n /**\n * Error correction level used, if applicable. The value type depends on the\n * format, but is typically a String.\n */\n ResultMetadataType[ResultMetadataType[\"ERROR_CORRECTION_LEVEL\"] = 3] = \"ERROR_CORRECTION_LEVEL\";\n /**\n * For some periodicals, indicates the issue number as an {@link Integer}.\n */\n ResultMetadataType[ResultMetadataType[\"ISSUE_NUMBER\"] = 4] = \"ISSUE_NUMBER\";\n /**\n * For some products, indicates the suggested retail price in the barcode as a\n * formatted {@link String}.\n */\n ResultMetadataType[ResultMetadataType[\"SUGGESTED_PRICE\"] = 5] = \"SUGGESTED_PRICE\";\n /**\n * For some products, the possible country of manufacture as a {@link String} denoting the\n * ISO country code. Some map to multiple possible countries, like \"US/CA\".\n */\n ResultMetadataType[ResultMetadataType[\"POSSIBLE_COUNTRY\"] = 6] = \"POSSIBLE_COUNTRY\";\n /**\n * For some products, the extension text\n */\n ResultMetadataType[ResultMetadataType[\"UPC_EAN_EXTENSION\"] = 7] = \"UPC_EAN_EXTENSION\";\n /**\n * PDF417-specific metadata\n */\n ResultMetadataType[ResultMetadataType[\"PDF417_EXTRA_METADATA\"] = 8] = \"PDF417_EXTRA_METADATA\";\n /**\n * If the code format supports structured append and the current scanned code is part of one then the\n * sequence number is given with it.\n */\n ResultMetadataType[ResultMetadataType[\"STRUCTURED_APPEND_SEQUENCE\"] = 9] = \"STRUCTURED_APPEND_SEQUENCE\";\n /**\n * If the code format supports structured append and the current scanned code is part of one then the\n * parity is given with it.\n */\n ResultMetadataType[ResultMetadataType[\"STRUCTURED_APPEND_PARITY\"] = 10] = \"STRUCTURED_APPEND_PARITY\";\n})(ResultMetadataType || (ResultMetadataType = {}));\nexport default ResultMetadataType;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing {*/\nimport MathUtils from './common/detector/MathUtils';\nimport Float from './util/Float';\n/**\n *Encapsulates a point of interest in an image containing a barcode. Typically, this\n * would be the location of a finder pattern or the corner of the barcode, for example.
\n *\n * @author Sean Owen\n */\nvar ResultPoint = /** @class */ (function () {\n function ResultPoint(x, y) {\n this.x = x;\n this.y = y;\n }\n ResultPoint.prototype.getX = function () {\n return this.x;\n };\n ResultPoint.prototype.getY = function () {\n return this.y;\n };\n /*@Override*/\n ResultPoint.prototype.equals = function (other) {\n if (other instanceof ResultPoint) {\n var otherPoint = other;\n return this.x === otherPoint.x && this.y === otherPoint.y;\n }\n return false;\n };\n /*@Override*/\n ResultPoint.prototype.hashCode = function () {\n return 31 * Float.floatToIntBits(this.x) + Float.floatToIntBits(this.y);\n };\n /*@Override*/\n ResultPoint.prototype.toString = function () {\n return '(' + this.x + ',' + this.y + ')';\n };\n /**\n * Orders an array of three ResultPoints in an order [A,B,C] such that AB is less than AC\n * and BC is less than AC, and the angle between BC and BA is less than 180 degrees.\n *\n * @param patterns array of three {@code ResultPoint} to order\n */\n ResultPoint.orderBestPatterns = function (patterns) {\n // Find distances between pattern centers\n var zeroOneDistance = this.distance(patterns[0], patterns[1]);\n var oneTwoDistance = this.distance(patterns[1], patterns[2]);\n var zeroTwoDistance = this.distance(patterns[0], patterns[2]);\n var pointA;\n var pointB;\n var pointC;\n // Assume one closest to other two is B; A and C will just be guesses at first\n if (oneTwoDistance >= zeroOneDistance && oneTwoDistance >= zeroTwoDistance) {\n pointB = patterns[0];\n pointA = patterns[1];\n pointC = patterns[2];\n }\n else if (zeroTwoDistance >= oneTwoDistance && zeroTwoDistance >= zeroOneDistance) {\n pointB = patterns[1];\n pointA = patterns[0];\n pointC = patterns[2];\n }\n else {\n pointB = patterns[2];\n pointA = patterns[0];\n pointC = patterns[1];\n }\n // Use cross product to figure out whether A and C are correct or flipped.\n // This asks whether BC x BA has a positive z component, which is the arrangement\n // we want for A, B, C. If it's negative, then we've got it flipped around and\n // should swap A and C.\n if (this.crossProductZ(pointA, pointB, pointC) < 0.0) {\n var temp = pointA;\n pointA = pointC;\n pointC = temp;\n }\n patterns[0] = pointA;\n patterns[1] = pointB;\n patterns[2] = pointC;\n };\n /**\n * @param pattern1 first pattern\n * @param pattern2 second pattern\n * @return distance between two points\n */\n ResultPoint.distance = function (pattern1, pattern2) {\n return MathUtils.distance(pattern1.x, pattern1.y, pattern2.x, pattern2.y);\n };\n /**\n * Returns the z component of the cross product between vectors BC and BA.\n */\n ResultPoint.crossProductZ = function (pointA, pointB, pointC) {\n var bX = pointB.x;\n var bY = pointB.y;\n return ((pointC.x - bX) * (pointA.y - bY)) - ((pointC.y - bY) * (pointA.x - bX));\n };\n return ResultPoint;\n}());\nexport default ResultPoint;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport Exception from './Exception';\n/**\n * Custom Error class of type Exception.\n */\nvar UnsupportedOperationException = /** @class */ (function (_super) {\n __extends(UnsupportedOperationException, _super);\n function UnsupportedOperationException() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n UnsupportedOperationException.kind = 'UnsupportedOperationException';\n return UnsupportedOperationException;\n}(Exception));\nexport default UnsupportedOperationException;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport Exception from './Exception';\n/**\n * Custom Error class of type Exception.\n */\nvar WriterException = /** @class */ (function (_super) {\n __extends(WriterException, _super);\n function WriterException() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n WriterException.kind = 'WriterException';\n return WriterException;\n}(Exception));\nexport default WriterException;\n","/*\n * Copyright 2010 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport DetectorResult from '../common/DetectorResult';\n/**\n *Extends {@link DetectorResult} with more information specific to the Aztec format,\n * like the number of layers and whether it's compact.
\n *\n * @author Sean Owen\n */\nvar AztecDetectorResult = /** @class */ (function (_super) {\n __extends(AztecDetectorResult, _super);\n function AztecDetectorResult(bits, points, compact, nbDatablocks, nbLayers) {\n var _this = _super.call(this, bits, points) || this;\n _this.compact = compact;\n _this.nbDatablocks = nbDatablocks;\n _this.nbLayers = nbLayers;\n return _this;\n }\n AztecDetectorResult.prototype.getNbLayers = function () {\n return this.nbLayers;\n };\n AztecDetectorResult.prototype.getNbDatablocks = function () {\n return this.nbDatablocks;\n };\n AztecDetectorResult.prototype.isCompact = function () {\n return this.compact;\n };\n return AztecDetectorResult;\n}(DetectorResult));\nexport default AztecDetectorResult;\n","/*\n * Copyright 2010 ZXing authors\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 */\nimport Result from '../Result';\nimport BarcodeFormat from '../BarcodeFormat';\nimport DecodeHintType from '../DecodeHintType';\nimport ResultMetadataType from '../ResultMetadataType';\nimport System from '../util/System';\nimport Decoder from './decoder/Decoder';\nimport Detector from './detector/Detector';\n// import java.util.List;\n// import java.util.Map;\n/**\n * This implementation can detect and decode Aztec codes in an image.\n *\n * @author David Olivier\n */\nvar AztecReader = /** @class */ (function () {\n function AztecReader() {\n }\n /**\n * Locates and decodes a Data Matrix code in an image.\n *\n * @return a String representing the content encoded by the Data Matrix code\n * @throws NotFoundException if a Data Matrix code cannot be found\n * @throws FormatException if a Data Matrix code cannot be decoded\n */\n AztecReader.prototype.decode = function (image, hints) {\n if (hints === void 0) { hints = null; }\n var exception = null;\n var detector = new Detector(image.getBlackMatrix());\n var points = null;\n var decoderResult = null;\n try {\n var detectorResult = detector.detectMirror(false);\n points = detectorResult.getPoints();\n this.reportFoundResultPoints(hints, points);\n decoderResult = new Decoder().decode(detectorResult);\n }\n catch (e) {\n exception = e;\n }\n if (decoderResult == null) {\n try {\n var detectorResult = detector.detectMirror(true);\n points = detectorResult.getPoints();\n this.reportFoundResultPoints(hints, points);\n decoderResult = new Decoder().decode(detectorResult);\n }\n catch (e) {\n if (exception != null) {\n throw exception;\n }\n throw e;\n }\n }\n var result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), decoderResult.getNumBits(), points, BarcodeFormat.AZTEC, System.currentTimeMillis());\n var byteSegments = decoderResult.getByteSegments();\n if (byteSegments != null) {\n result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);\n }\n var ecLevel = decoderResult.getECLevel();\n if (ecLevel != null) {\n result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);\n }\n return result;\n };\n AztecReader.prototype.reportFoundResultPoints = function (hints, points) {\n if (hints != null) {\n var rpcb_1 = hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);\n if (rpcb_1 != null) {\n points.forEach(function (point, idx, arr) {\n rpcb_1.foundPossibleResultPoint(point);\n });\n }\n }\n };\n // @Override\n AztecReader.prototype.reset = function () {\n // do nothing\n };\n return AztecReader;\n}());\nexport default AztecReader;\n","/*\n* Copyright 2013 ZXing authors\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// package com.google.zxing.aztec;\n// import com.google.zxing.BarcodeFormat;\nimport BarcodeFormat from '../BarcodeFormat';\n// import com.google.zxing.EncodeHintType;\nimport EncodeHintType from '../EncodeHintType';\n// import com.google.zxing.aztec.encoder.Encoder;\nimport Encoder from './encoder/Encoder';\n// import com.google.zxing.common.BitMatrix;\nimport BitMatrix from '../common/BitMatrix';\n// import java.nio.charset.Charset;\nimport Charset from '../util/Charset';\n// import java.nio.charset.StandardCharsets;\nimport StandardCharsets from '../util/StandardCharsets';\n// import java.util.Map;\nimport Integer from '../util/Integer';\nimport IllegalStateException from '../IllegalStateException';\nimport IllegalArgumentException from '../IllegalArgumentException';\nimport StringUtils from '../common/StringUtils';\n/**\n * Renders an Aztec code as a {@link BitMatrix}.\n */\nvar AztecWriter = /** @class */ (function () {\n function AztecWriter() {\n }\n // @Override\n AztecWriter.prototype.encode = function (contents, format, width, height) {\n return this.encodeWithHints(contents, format, width, height, null);\n };\n // @Override\n AztecWriter.prototype.encodeWithHints = function (contents, format, width, height, hints) {\n var charset = StandardCharsets.ISO_8859_1;\n var eccPercent = Encoder.DEFAULT_EC_PERCENT;\n var layers = Encoder.DEFAULT_AZTEC_LAYERS;\n if (hints != null) {\n if (hints.has(EncodeHintType.CHARACTER_SET)) {\n charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());\n }\n if (hints.has(EncodeHintType.ERROR_CORRECTION)) {\n eccPercent = Integer.parseInt(hints.get(EncodeHintType.ERROR_CORRECTION).toString());\n }\n if (hints.has(EncodeHintType.AZTEC_LAYERS)) {\n layers = Integer.parseInt(hints.get(EncodeHintType.AZTEC_LAYERS).toString());\n }\n }\n return AztecWriter.encodeLayers(contents, format, width, height, charset, eccPercent, layers);\n };\n AztecWriter.encodeLayers = function (contents, format, width, height, charset, eccPercent, layers) {\n if (format !== BarcodeFormat.AZTEC) {\n throw new IllegalArgumentException('Can only encode AZTEC, but got ' + format);\n }\n var aztec = Encoder.encode(StringUtils.getBytes(contents, charset), eccPercent, layers);\n return AztecWriter.renderResult(aztec, width, height);\n };\n AztecWriter.renderResult = function (code, width, height) {\n var input = code.getMatrix();\n if (input == null) {\n throw new IllegalStateException();\n }\n var inputWidth = input.getWidth();\n var inputHeight = input.getHeight();\n var outputWidth = Math.max(width, inputWidth);\n var outputHeight = Math.max(height, inputHeight);\n var multiple = Math.min(outputWidth / inputWidth, outputHeight / inputHeight);\n var leftPadding = (outputWidth - (inputWidth * multiple)) / 2;\n var topPadding = (outputHeight - (inputHeight * multiple)) / 2;\n var output = new BitMatrix(outputWidth, outputHeight);\n for (var inputY /*int*/ = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {\n // Write the contents of this row of the barcode\n for (var inputX /*int*/ = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {\n if (input.get(inputX, inputY)) {\n output.setRegion(outputX, outputY, multiple, multiple);\n }\n }\n }\n return output;\n };\n return AztecWriter;\n}());\nexport default AztecWriter;\n","/*\n * Copyright 2010 ZXing authors\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 */\nimport DecoderResult from '../../common/DecoderResult';\nimport GenericGF from '../../common/reedsolomon/GenericGF';\nimport ReedSolomonDecoder from '../../common/reedsolomon/ReedSolomonDecoder';\nimport IllegalStateException from '../../IllegalStateException';\nimport FormatException from '../../FormatException';\nimport StringUtils from '../../common/StringUtils';\nimport Integer from '../../util/Integer';\n// import java.util.Arrays;\nvar Table;\n(function (Table) {\n Table[Table[\"UPPER\"] = 0] = \"UPPER\";\n Table[Table[\"LOWER\"] = 1] = \"LOWER\";\n Table[Table[\"MIXED\"] = 2] = \"MIXED\";\n Table[Table[\"DIGIT\"] = 3] = \"DIGIT\";\n Table[Table[\"PUNCT\"] = 4] = \"PUNCT\";\n Table[Table[\"BINARY\"] = 5] = \"BINARY\";\n})(Table || (Table = {}));\n/**\n *The main class which implements Aztec Code decoding -- as opposed to locating and extracting\n * the Aztec Code from an image.
\n *\n * @author David Olivier\n */\nvar Decoder = /** @class */ (function () {\n function Decoder() {\n }\n Decoder.prototype.decode = function (detectorResult) {\n this.ddata = detectorResult;\n var matrix = detectorResult.getBits();\n var rawbits = this.extractBits(matrix);\n var correctedBits = this.correctBits(rawbits);\n var rawBytes = Decoder.convertBoolArrayToByteArray(correctedBits);\n var result = Decoder.getEncodedData(correctedBits);\n var decoderResult = new DecoderResult(rawBytes, result, null, null);\n decoderResult.setNumBits(correctedBits.length);\n return decoderResult;\n };\n // This method is used for testing the high-level encoder\n Decoder.highLevelDecode = function (correctedBits) {\n return this.getEncodedData(correctedBits);\n };\n /**\n * Gets the string encoded in the aztec code bits\n *\n * @return the decoded string\n */\n Decoder.getEncodedData = function (correctedBits) {\n var endIndex = correctedBits.length;\n var latchTable = Table.UPPER; // table most recently latched to\n var shiftTable = Table.UPPER; // table to use for the next read\n var result = '';\n var index = 0;\n while (index < endIndex) {\n if (shiftTable === Table.BINARY) {\n if (endIndex - index < 5) {\n break;\n }\n var length_1 = Decoder.readCode(correctedBits, index, 5);\n index += 5;\n if (length_1 === 0) {\n if (endIndex - index < 11) {\n break;\n }\n length_1 = Decoder.readCode(correctedBits, index, 11) + 31;\n index += 11;\n }\n for (var charCount = 0; charCount < length_1; charCount++) {\n if (endIndex - index < 8) {\n index = endIndex; // Force outer loop to exit\n break;\n }\n var code = Decoder.readCode(correctedBits, index, 8);\n result += /*(char)*/ StringUtils.castAsNonUtf8Char(code);\n index += 8;\n }\n // Go back to whatever mode we had been in\n shiftTable = latchTable;\n }\n else {\n var size = shiftTable === Table.DIGIT ? 4 : 5;\n if (endIndex - index < size) {\n break;\n }\n var code = Decoder.readCode(correctedBits, index, size);\n index += size;\n var str = Decoder.getCharacter(shiftTable, code);\n if (str.startsWith('CTRL_')) {\n // Table changes\n // ISO/IEC 24778:2008 prescribes ending a shift sequence in the mode from which it was invoked.\n // That's including when that mode is a shift.\n // Our test case dlusbs.png for issue #642 exercises that.\n latchTable = shiftTable; // Latch the current mode, so as to return to Upper after U/S B/S\n shiftTable = Decoder.getTable(str.charAt(5));\n if (str.charAt(6) === 'L') {\n latchTable = shiftTable;\n }\n }\n else {\n result += str;\n // Go back to whatever mode we had been in\n shiftTable = latchTable;\n }\n }\n }\n return result;\n };\n /**\n * gets the table corresponding to the char passed\n */\n Decoder.getTable = function (t) {\n switch (t) {\n case 'L':\n return Table.LOWER;\n case 'P':\n return Table.PUNCT;\n case 'M':\n return Table.MIXED;\n case 'D':\n return Table.DIGIT;\n case 'B':\n return Table.BINARY;\n case 'U':\n default:\n return Table.UPPER;\n }\n };\n /**\n * Gets the character (or string) corresponding to the passed code in the given table\n *\n * @param table the table used\n * @param code the code of the character\n */\n Decoder.getCharacter = function (table, code) {\n switch (table) {\n case Table.UPPER:\n return Decoder.UPPER_TABLE[code];\n case Table.LOWER:\n return Decoder.LOWER_TABLE[code];\n case Table.MIXED:\n return Decoder.MIXED_TABLE[code];\n case Table.PUNCT:\n return Decoder.PUNCT_TABLE[code];\n case Table.DIGIT:\n return Decoder.DIGIT_TABLE[code];\n default:\n // Should not reach here.\n throw new IllegalStateException('Bad table');\n }\n };\n /**\n *Performs RS error correction on an array of bits.
\n *\n * @return the corrected array\n * @throws FormatException if the input contains too many errors\n */\n Decoder.prototype.correctBits = function (rawbits) {\n var gf;\n var codewordSize;\n if (this.ddata.getNbLayers() <= 2) {\n codewordSize = 6;\n gf = GenericGF.AZTEC_DATA_6;\n }\n else if (this.ddata.getNbLayers() <= 8) {\n codewordSize = 8;\n gf = GenericGF.AZTEC_DATA_8;\n }\n else if (this.ddata.getNbLayers() <= 22) {\n codewordSize = 10;\n gf = GenericGF.AZTEC_DATA_10;\n }\n else {\n codewordSize = 12;\n gf = GenericGF.AZTEC_DATA_12;\n }\n var numDataCodewords = this.ddata.getNbDatablocks();\n var numCodewords = rawbits.length / codewordSize;\n if (numCodewords < numDataCodewords) {\n throw new FormatException();\n }\n var offset = rawbits.length % codewordSize;\n var dataWords = new Int32Array(numCodewords);\n for (var i = 0; i < numCodewords; i++, offset += codewordSize) {\n dataWords[i] = Decoder.readCode(rawbits, offset, codewordSize);\n }\n try {\n var rsDecoder = new ReedSolomonDecoder(gf);\n rsDecoder.decode(dataWords, numCodewords - numDataCodewords);\n }\n catch (ex) {\n throw new FormatException(ex);\n }\n // Now perform the unstuffing operation.\n // First, count how many bits are going to be thrown out as stuffing\n var mask = (1 << codewordSize) - 1;\n var stuffedBits = 0;\n for (var i = 0; i < numDataCodewords; i++) {\n var dataWord = dataWords[i];\n if (dataWord === 0 || dataWord === mask) {\n throw new FormatException();\n }\n else if (dataWord === 1 || dataWord === mask - 1) {\n stuffedBits++;\n }\n }\n // Now, actually unpack the bits and remove the stuffing\n var correctedBits = new Array(numDataCodewords * codewordSize - stuffedBits);\n var index = 0;\n for (var i = 0; i < numDataCodewords; i++) {\n var dataWord = dataWords[i];\n if (dataWord === 1 || dataWord === mask - 1) {\n // next codewordSize-1 bits are all zeros or all ones\n correctedBits.fill(dataWord > 1, index, index + codewordSize - 1);\n // Arrays.fill(correctedBits, index, index + codewordSize - 1, dataWord > 1);\n index += codewordSize - 1;\n }\n else {\n for (var bit = codewordSize - 1; bit >= 0; --bit) {\n correctedBits[index++] = (dataWord & (1 << bit)) !== 0;\n }\n }\n }\n return correctedBits;\n };\n /**\n * Gets the array of bits from an Aztec Code matrix\n *\n * @return the array of bits\n */\n Decoder.prototype.extractBits = function (matrix) {\n var compact = this.ddata.isCompact();\n var layers = this.ddata.getNbLayers();\n var baseMatrixSize = (compact ? 11 : 14) + layers * 4; // not including alignment lines\n var alignmentMap = new Int32Array(baseMatrixSize);\n var rawbits = new Array(this.totalBitsInLayer(layers, compact));\n if (compact) {\n for (var i = 0; i < alignmentMap.length; i++) {\n alignmentMap[i] = i;\n }\n }\n else {\n var matrixSize = baseMatrixSize + 1 + 2 * Integer.truncDivision((Integer.truncDivision(baseMatrixSize, 2) - 1), 15);\n var origCenter = baseMatrixSize / 2;\n var center = Integer.truncDivision(matrixSize, 2);\n for (var i = 0; i < origCenter; i++) {\n var newOffset = i + Integer.truncDivision(i, 15);\n alignmentMap[origCenter - i - 1] = center - newOffset - 1;\n alignmentMap[origCenter + i] = center + newOffset + 1;\n }\n }\n for (var i = 0, rowOffset = 0; i < layers; i++) {\n var rowSize = (layers - i) * 4 + (compact ? 9 : 12);\n // The top-left most point of this layer isA simple, fast array of bits, represented compactly by an array of ints internally.
\n *\n * @author Sean Owen\n */\nvar BitArray /*implements Cloneable*/ = /** @class */ (function () {\n // public constructor() {\n // this.size = 0\n // this.bits = new Int32Array(1)\n // }\n // public constructor(size?: number /*int*/) {\n // if (undefined === size) {\n // this.size = 0\n // } else {\n // this.size = size\n // }\n // this.bits = this.makeArray(size)\n // }\n // For testing only\n function BitArray(size /*int*/, bits) {\n if (undefined === size) {\n this.size = 0;\n this.bits = new Int32Array(1);\n }\n else {\n this.size = size;\n if (undefined === bits || null === bits) {\n this.bits = BitArray.makeArray(size);\n }\n else {\n this.bits = bits;\n }\n }\n }\n BitArray.prototype.getSize = function () {\n return this.size;\n };\n BitArray.prototype.getSizeInBytes = function () {\n return Math.floor((this.size + 7) / 8);\n };\n BitArray.prototype.ensureCapacity = function (size /*int*/) {\n if (size > this.bits.length * 32) {\n var newBits = BitArray.makeArray(size);\n System.arraycopy(this.bits, 0, newBits, 0, this.bits.length);\n this.bits = newBits;\n }\n };\n /**\n * @param i bit to get\n * @return true iff bit i is set\n */\n BitArray.prototype.get = function (i /*int*/) {\n return (this.bits[Math.floor(i / 32)] & (1 << (i & 0x1F))) !== 0;\n };\n /**\n * Sets bit i.\n *\n * @param i bit to set\n */\n BitArray.prototype.set = function (i /*int*/) {\n this.bits[Math.floor(i / 32)] |= 1 << (i & 0x1F);\n };\n /**\n * Flips bit i.\n *\n * @param i bit to set\n */\n BitArray.prototype.flip = function (i /*int*/) {\n this.bits[Math.floor(i / 32)] ^= 1 << (i & 0x1F);\n };\n /**\n * @param from first bit to check\n * @return index of first bit that is set, starting from the given index, or size if none are set\n * at or beyond this given index\n * @see #getNextUnset(int)\n */\n BitArray.prototype.getNextSet = function (from /*int*/) {\n var size = this.size;\n if (from >= size) {\n return size;\n }\n var bits = this.bits;\n var bitsOffset = Math.floor(from / 32);\n var currentBits = bits[bitsOffset];\n // mask off lesser bits first\n currentBits &= ~((1 << (from & 0x1F)) - 1);\n var length = bits.length;\n while (currentBits === 0) {\n if (++bitsOffset === length) {\n return size;\n }\n currentBits = bits[bitsOffset];\n }\n var result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits);\n return result > size ? size : result;\n };\n /**\n * @param from index to start looking for unset bit\n * @return index of next unset bit, or {@code size} if none are unset until the end\n * @see #getNextSet(int)\n */\n BitArray.prototype.getNextUnset = function (from /*int*/) {\n var size = this.size;\n if (from >= size) {\n return size;\n }\n var bits = this.bits;\n var bitsOffset = Math.floor(from / 32);\n var currentBits = ~bits[bitsOffset];\n // mask off lesser bits first\n currentBits &= ~((1 << (from & 0x1F)) - 1);\n var length = bits.length;\n while (currentBits === 0) {\n if (++bitsOffset === length) {\n return size;\n }\n currentBits = ~bits[bitsOffset];\n }\n var result = (bitsOffset * 32) + Integer.numberOfTrailingZeros(currentBits);\n return result > size ? size : result;\n };\n /**\n * Sets a block of 32 bits, starting at bit i.\n *\n * @param i first bit to set\n * @param newBits the new value of the next 32 bits. Note again that the least-significant bit\n * corresponds to bit i, the next-least-significant to i+1, and so on.\n */\n BitArray.prototype.setBulk = function (i /*int*/, newBits /*int*/) {\n this.bits[Math.floor(i / 32)] = newBits;\n };\n /**\n * Sets a range of bits.\n *\n * @param start start of range, inclusive.\n * @param end end of range, exclusive\n */\n BitArray.prototype.setRange = function (start /*int*/, end /*int*/) {\n if (end < start || start < 0 || end > this.size) {\n throw new IllegalArgumentException();\n }\n if (end === start) {\n return;\n }\n end--; // will be easier to treat this as the last actually set bit -- inclusive\n var firstInt = Math.floor(start / 32);\n var lastInt = Math.floor(end / 32);\n var bits = this.bits;\n for (var i = firstInt; i <= lastInt; i++) {\n var firstBit = i > firstInt ? 0 : start & 0x1F;\n var lastBit = i < lastInt ? 31 : end & 0x1F;\n // Ones from firstBit to lastBit, inclusive\n var mask = (2 << lastBit) - (1 << firstBit);\n bits[i] |= mask;\n }\n };\n /**\n * Clears all bits (sets to false).\n */\n BitArray.prototype.clear = function () {\n var max = this.bits.length;\n var bits = this.bits;\n for (var i = 0; i < max; i++) {\n bits[i] = 0;\n }\n };\n /**\n * Efficient method to check if a range of bits is set, or not set.\n *\n * @param start start of range, inclusive.\n * @param end end of range, exclusive\n * @param value if true, checks that bits in range are set, otherwise checks that they are not set\n * @return true iff all bits are set or not set in range, according to value argument\n * @throws IllegalArgumentException if end is less than start or the range is not contained in the array\n */\n BitArray.prototype.isRange = function (start /*int*/, end /*int*/, value) {\n if (end < start || start < 0 || end > this.size) {\n throw new IllegalArgumentException();\n }\n if (end === start) {\n return true; // empty range matches\n }\n end--; // will be easier to treat this as the last actually set bit -- inclusive\n var firstInt = Math.floor(start / 32);\n var lastInt = Math.floor(end / 32);\n var bits = this.bits;\n for (var i = firstInt; i <= lastInt; i++) {\n var firstBit = i > firstInt ? 0 : start & 0x1F;\n var lastBit = i < lastInt ? 31 : end & 0x1F;\n // Ones from firstBit to lastBit, inclusive\n var mask = (2 << lastBit) - (1 << firstBit) & 0xFFFFFFFF;\n // TYPESCRIPTPORT: & 0xFFFFFFFF added to discard anything after 32 bits, as ES has 53 bits\n // Return false if we're looking for 1s and the masked bits[i] isn't all 1s (is: that,\n // equals the mask, or we're looking for 0s and the masked portion is not all 0s\n if ((bits[i] & mask) !== (value ? mask : 0)) {\n return false;\n }\n }\n return true;\n };\n BitArray.prototype.appendBit = function (bit) {\n this.ensureCapacity(this.size + 1);\n if (bit) {\n this.bits[Math.floor(this.size / 32)] |= 1 << (this.size & 0x1F);\n }\n this.size++;\n };\n /**\n * Appends the least-significant bits, from value, in order from most-significant to\n * least-significant. For example, appending 6 bits from 0x000001E will append the bits\n * 0, 1, 1, 1, 1, 0 in that order.\n *\n * @param value {@code int} containing bits to append\n * @param numBits bits from value to append\n */\n BitArray.prototype.appendBits = function (value /*int*/, numBits /*int*/) {\n if (numBits < 0 || numBits > 32) {\n throw new IllegalArgumentException('Num bits must be between 0 and 32');\n }\n this.ensureCapacity(this.size + numBits);\n // const appendBit = this.appendBit;\n for (var numBitsLeft = numBits; numBitsLeft > 0; numBitsLeft--) {\n this.appendBit(((value >> (numBitsLeft - 1)) & 0x01) === 1);\n }\n };\n BitArray.prototype.appendBitArray = function (other) {\n var otherSize = other.size;\n this.ensureCapacity(this.size + otherSize);\n // const appendBit = this.appendBit;\n for (var i = 0; i < otherSize; i++) {\n this.appendBit(other.get(i));\n }\n };\n BitArray.prototype.xor = function (other) {\n if (this.size !== other.size) {\n throw new IllegalArgumentException('Sizes don\\'t match');\n }\n var bits = this.bits;\n for (var i = 0, length_1 = bits.length; i < length_1; i++) {\n // The last int could be incomplete (i.e. not have 32 bits in\n // it) but there is no problem since 0 XOR 0 == 0.\n bits[i] ^= other.bits[i];\n }\n };\n /**\n *\n * @param bitOffset first bit to start writing\n * @param array array to write into. Bytes are written most-significant byte first. This is the opposite\n * of the internal representation, which is exposed by {@link #getBitArray()}\n * @param offset position in array to start writing\n * @param numBytes how many bytes to write\n */\n BitArray.prototype.toBytes = function (bitOffset /*int*/, array, offset /*int*/, numBytes /*int*/) {\n for (var i = 0; i < numBytes; i++) {\n var theByte = 0;\n for (var j = 0; j < 8; j++) {\n if (this.get(bitOffset)) {\n theByte |= 1 << (7 - j);\n }\n bitOffset++;\n }\n array[offset + i] = /*(byte)*/ theByte;\n }\n };\n /**\n * @return underlying array of ints. The first element holds the first 32 bits, and the least\n * significant bit is bit 0.\n */\n BitArray.prototype.getBitArray = function () {\n return this.bits;\n };\n /**\n * Reverses all bits in the array.\n */\n BitArray.prototype.reverse = function () {\n var newBits = new Int32Array(this.bits.length);\n // reverse all int's first\n var len = Math.floor((this.size - 1) / 32);\n var oldBitsLen = len + 1;\n var bits = this.bits;\n for (var i = 0; i < oldBitsLen; i++) {\n var x = bits[i];\n x = ((x >> 1) & 0x55555555) | ((x & 0x55555555) << 1);\n x = ((x >> 2) & 0x33333333) | ((x & 0x33333333) << 2);\n x = ((x >> 4) & 0x0f0f0f0f) | ((x & 0x0f0f0f0f) << 4);\n x = ((x >> 8) & 0x00ff00ff) | ((x & 0x00ff00ff) << 8);\n x = ((x >> 16) & 0x0000ffff) | ((x & 0x0000ffff) << 16);\n newBits[len - i] = /*(int)*/ x;\n }\n // now correct the int's if the bit size isn't a multiple of 32\n if (this.size !== oldBitsLen * 32) {\n var leftOffset = oldBitsLen * 32 - this.size;\n var currentInt = newBits[0] >>> leftOffset;\n for (var i = 1; i < oldBitsLen; i++) {\n var nextInt = newBits[i];\n currentInt |= nextInt << (32 - leftOffset);\n newBits[i - 1] = currentInt;\n currentInt = nextInt >>> leftOffset;\n }\n newBits[oldBitsLen - 1] = currentInt;\n }\n this.bits = newBits;\n };\n BitArray.makeArray = function (size /*int*/) {\n return new Int32Array(Math.floor((size + 31) / 32));\n };\n /*@Override*/\n BitArray.prototype.equals = function (o) {\n if (!(o instanceof BitArray)) {\n return false;\n }\n var other = o;\n return this.size === other.size && Arrays.equals(this.bits, other.bits);\n };\n /*@Override*/\n BitArray.prototype.hashCode = function () {\n return 31 * this.size + Arrays.hashCode(this.bits);\n };\n /*@Override*/\n BitArray.prototype.toString = function () {\n var result = '';\n for (var i = 0, size = this.size; i < size; i++) {\n if ((i & 0x07) === 0) {\n result += ' ';\n }\n result += this.get(i) ? 'X' : '.';\n }\n return result;\n };\n /*@Override*/\n BitArray.prototype.clone = function () {\n return new BitArray(this.size, this.bits.slice());\n };\n /**\n * converts to boolean array.\n */\n BitArray.prototype.toArray = function () {\n var result = [];\n for (var i = 0, size = this.size; i < size; i++) {\n result.push(this.get(i));\n }\n return result;\n };\n return BitArray;\n}());\nexport default BitArray;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.common {*/\n/*import java.util.Arrays;*/\nimport BitArray from './BitArray';\nimport System from '../util/System';\nimport Arrays from '../util/Arrays';\nimport StringBuilder from '../util/StringBuilder';\nimport IllegalArgumentException from '../IllegalArgumentException';\n/**\n *Represents a 2D matrix of bits. In function arguments below, and throughout the common\n * module, x is the column position, and y is the row position. The ordering is always x, y.\n * The origin is at the top-left.
\n *\n *Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins\n * with a new int. This is done intentionally so that we can copy out a row into a BitArray very\n * efficiently.
\n *\n *The ordering of bits is row-major. Within each int, the least significant bits are used first,\n * meaning they represent lower x values. This is compatible with BitArray's implementation.
\n *\n * @author Sean Owen\n * @author dswitkin@google.com (Daniel Switkin)\n */\nvar BitMatrix /*implements Cloneable*/ = /** @class */ (function () {\n /**\n * Creates an empty square {@link BitMatrix}.\n *\n * @param dimension height and width\n */\n // public constructor(dimension: number /*int*/) {\n // this(dimension, dimension)\n // }\n /**\n * Creates an empty {@link BitMatrix}.\n *\n * @param width bit matrix width\n * @param height bit matrix height\n */\n // public constructor(width: number /*int*/, height: number /*int*/) {\n // if (width < 1 || height < 1) {\n // throw new IllegalArgumentException(\"Both dimensions must be greater than 0\")\n // }\n // this.width = width\n // this.height = height\n // this.rowSize = (width + 31) / 32\n // bits = new int[rowSize * height];\n // }\n function BitMatrix(width /*int*/, height /*int*/, rowSize /*int*/, bits) {\n this.width = width;\n this.height = height;\n this.rowSize = rowSize;\n this.bits = bits;\n if (undefined === height || null === height) {\n height = width;\n }\n this.height = height;\n if (width < 1 || height < 1) {\n throw new IllegalArgumentException('Both dimensions must be greater than 0');\n }\n if (undefined === rowSize || null === rowSize) {\n rowSize = Math.floor((width + 31) / 32);\n }\n this.rowSize = rowSize;\n if (undefined === bits || null === bits) {\n this.bits = new Int32Array(this.rowSize * this.height);\n }\n }\n /**\n * Interprets a 2D array of booleans as a {@link BitMatrix}, where \"true\" means an \"on\" bit.\n *\n * @function parse\n * @param image bits of the image, as a row-major 2D array. Elements are arrays representing rows\n * @return {@link BitMatrix} representation of image\n */\n BitMatrix.parseFromBooleanArray = function (image) {\n var height = image.length;\n var width = image[0].length;\n var bits = new BitMatrix(width, height);\n for (var i = 0; i < height; i++) {\n var imageI = image[i];\n for (var j = 0; j < width; j++) {\n if (imageI[j]) {\n bits.set(j, i);\n }\n }\n }\n return bits;\n };\n /**\n *\n * @function parse\n * @param stringRepresentation\n * @param setString\n * @param unsetString\n */\n BitMatrix.parseFromString = function (stringRepresentation, setString, unsetString) {\n if (stringRepresentation === null) {\n throw new IllegalArgumentException('stringRepresentation cannot be null');\n }\n var bits = new Array(stringRepresentation.length);\n var bitsPos = 0;\n var rowStartPos = 0;\n var rowLength = -1;\n var nRows = 0;\n var pos = 0;\n while (pos < stringRepresentation.length) {\n if (stringRepresentation.charAt(pos) === '\\n' ||\n stringRepresentation.charAt(pos) === '\\r') {\n if (bitsPos > rowStartPos) {\n if (rowLength === -1) {\n rowLength = bitsPos - rowStartPos;\n }\n else if (bitsPos - rowStartPos !== rowLength) {\n throw new IllegalArgumentException('row lengths do not match');\n }\n rowStartPos = bitsPos;\n nRows++;\n }\n pos++;\n }\n else if (stringRepresentation.substring(pos, pos + setString.length) === setString) {\n pos += setString.length;\n bits[bitsPos] = true;\n bitsPos++;\n }\n else if (stringRepresentation.substring(pos, pos + unsetString.length) === unsetString) {\n pos += unsetString.length;\n bits[bitsPos] = false;\n bitsPos++;\n }\n else {\n throw new IllegalArgumentException('illegal character encountered: ' + stringRepresentation.substring(pos));\n }\n }\n // no EOL at end?\n if (bitsPos > rowStartPos) {\n if (rowLength === -1) {\n rowLength = bitsPos - rowStartPos;\n }\n else if (bitsPos - rowStartPos !== rowLength) {\n throw new IllegalArgumentException('row lengths do not match');\n }\n nRows++;\n }\n var matrix = new BitMatrix(rowLength, nRows);\n for (var i = 0; i < bitsPos; i++) {\n if (bits[i]) {\n matrix.set(Math.floor(i % rowLength), Math.floor(i / rowLength));\n }\n }\n return matrix;\n };\n /**\n *Gets the requested bit, where true means black.
\n *\n * @param x The horizontal component (i.e. which column)\n * @param y The vertical component (i.e. which row)\n * @return value of given bit in matrix\n */\n BitMatrix.prototype.get = function (x /*int*/, y /*int*/) {\n var offset = y * this.rowSize + Math.floor(x / 32);\n return ((this.bits[offset] >>> (x & 0x1f)) & 1) !== 0;\n };\n /**\n *Sets the given bit to true.
\n *\n * @param x The horizontal component (i.e. which column)\n * @param y The vertical component (i.e. which row)\n */\n BitMatrix.prototype.set = function (x /*int*/, y /*int*/) {\n var offset = y * this.rowSize + Math.floor(x / 32);\n this.bits[offset] |= (1 << (x & 0x1f)) & 0xFFFFFFFF;\n };\n BitMatrix.prototype.unset = function (x /*int*/, y /*int*/) {\n var offset = y * this.rowSize + Math.floor(x / 32);\n this.bits[offset] &= ~((1 << (x & 0x1f)) & 0xFFFFFFFF);\n };\n /**\n *Flips the given bit.
\n *\n * @param x The horizontal component (i.e. which column)\n * @param y The vertical component (i.e. which row)\n */\n BitMatrix.prototype.flip = function (x /*int*/, y /*int*/) {\n var offset = y * this.rowSize + Math.floor(x / 32);\n this.bits[offset] ^= ((1 << (x & 0x1f)) & 0xFFFFFFFF);\n };\n /**\n * Exclusive-or (XOR): Flip the bit in this {@code BitMatrix} if the corresponding\n * mask bit is set.\n *\n * @param mask XOR mask\n */\n BitMatrix.prototype.xor = function (mask) {\n if (this.width !== mask.getWidth() || this.height !== mask.getHeight()\n || this.rowSize !== mask.getRowSize()) {\n throw new IllegalArgumentException('input matrix dimensions do not match');\n }\n var rowArray = new BitArray(Math.floor(this.width / 32) + 1);\n var rowSize = this.rowSize;\n var bits = this.bits;\n for (var y = 0, height = this.height; y < height; y++) {\n var offset = y * rowSize;\n var row = mask.getRow(y, rowArray).getBitArray();\n for (var x = 0; x < rowSize; x++) {\n bits[offset + x] ^= row[x];\n }\n }\n };\n /**\n * Clears all bits (sets to false).\n */\n BitMatrix.prototype.clear = function () {\n var bits = this.bits;\n var max = bits.length;\n for (var i = 0; i < max; i++) {\n bits[i] = 0;\n }\n };\n /**\n *Sets a square region of the bit matrix to true.
\n *\n * @param left The horizontal position to begin at (inclusive)\n * @param top The vertical position to begin at (inclusive)\n * @param width The width of the region\n * @param height The height of the region\n */\n BitMatrix.prototype.setRegion = function (left /*int*/, top /*int*/, width /*int*/, height /*int*/) {\n if (top < 0 || left < 0) {\n throw new IllegalArgumentException('Left and top must be nonnegative');\n }\n if (height < 1 || width < 1) {\n throw new IllegalArgumentException('Height and width must be at least 1');\n }\n var right = left + width;\n var bottom = top + height;\n if (bottom > this.height || right > this.width) {\n throw new IllegalArgumentException('The region must fit inside the matrix');\n }\n var rowSize = this.rowSize;\n var bits = this.bits;\n for (var y = top; y < bottom; y++) {\n var offset = y * rowSize;\n for (var x = left; x < right; x++) {\n bits[offset + Math.floor(x / 32)] |= ((1 << (x & 0x1f)) & 0xFFFFFFFF);\n }\n }\n };\n /**\n * A fast method to retrieve one row of data from the matrix as a BitArray.\n *\n * @param y The row to retrieve\n * @param row An optional caller-allocated BitArray, will be allocated if null or too small\n * @return The resulting BitArray - this reference should always be used even when passing\n * your own row\n */\n BitMatrix.prototype.getRow = function (y /*int*/, row) {\n if (row === null || row === undefined || row.getSize() < this.width) {\n row = new BitArray(this.width);\n }\n else {\n row.clear();\n }\n var rowSize = this.rowSize;\n var bits = this.bits;\n var offset = y * rowSize;\n for (var x = 0; x < rowSize; x++) {\n row.setBulk(x * 32, bits[offset + x]);\n }\n return row;\n };\n /**\n * @param y row to set\n * @param row {@link BitArray} to copy from\n */\n BitMatrix.prototype.setRow = function (y /*int*/, row) {\n System.arraycopy(row.getBitArray(), 0, this.bits, y * this.rowSize, this.rowSize);\n };\n /**\n * Modifies this {@code BitMatrix} to represent the same but rotated 180 degrees\n */\n BitMatrix.prototype.rotate180 = function () {\n var width = this.getWidth();\n var height = this.getHeight();\n var topRow = new BitArray(width);\n var bottomRow = new BitArray(width);\n for (var i = 0, length_1 = Math.floor((height + 1) / 2); i < length_1; i++) {\n topRow = this.getRow(i, topRow);\n bottomRow = this.getRow(height - 1 - i, bottomRow);\n topRow.reverse();\n bottomRow.reverse();\n this.setRow(i, bottomRow);\n this.setRow(height - 1 - i, topRow);\n }\n };\n /**\n * This is useful in detecting the enclosing rectangle of a 'pure' barcode.\n *\n * @return {@code left,top,width,height} enclosing rectangle of all 1 bits, or null if it is all white\n */\n BitMatrix.prototype.getEnclosingRectangle = function () {\n var width = this.width;\n var height = this.height;\n var rowSize = this.rowSize;\n var bits = this.bits;\n var left = width;\n var top = height;\n var right = -1;\n var bottom = -1;\n for (var y = 0; y < height; y++) {\n for (var x32 = 0; x32 < rowSize; x32++) {\n var theBits = bits[y * rowSize + x32];\n if (theBits !== 0) {\n if (y < top) {\n top = y;\n }\n if (y > bottom) {\n bottom = y;\n }\n if (x32 * 32 < left) {\n var bit = 0;\n while (((theBits << (31 - bit)) & 0xFFFFFFFF) === 0) {\n bit++;\n }\n if ((x32 * 32 + bit) < left) {\n left = x32 * 32 + bit;\n }\n }\n if (x32 * 32 + 31 > right) {\n var bit = 31;\n while ((theBits >>> bit) === 0) {\n bit--;\n }\n if ((x32 * 32 + bit) > right) {\n right = x32 * 32 + bit;\n }\n }\n }\n }\n }\n if (right < left || bottom < top) {\n return null;\n }\n return Int32Array.from([left, top, right - left + 1, bottom - top + 1]);\n };\n /**\n * This is useful in detecting a corner of a 'pure' barcode.\n *\n * @return {@code x,y} coordinate of top-left-most 1 bit, or null if it is all white\n */\n BitMatrix.prototype.getTopLeftOnBit = function () {\n var rowSize = this.rowSize;\n var bits = this.bits;\n var bitsOffset = 0;\n while (bitsOffset < bits.length && bits[bitsOffset] === 0) {\n bitsOffset++;\n }\n if (bitsOffset === bits.length) {\n return null;\n }\n var y = bitsOffset / rowSize;\n var x = (bitsOffset % rowSize) * 32;\n var theBits = bits[bitsOffset];\n var bit = 0;\n while (((theBits << (31 - bit)) & 0xFFFFFFFF) === 0) {\n bit++;\n }\n x += bit;\n return Int32Array.from([x, y]);\n };\n BitMatrix.prototype.getBottomRightOnBit = function () {\n var rowSize = this.rowSize;\n var bits = this.bits;\n var bitsOffset = bits.length - 1;\n while (bitsOffset >= 0 && bits[bitsOffset] === 0) {\n bitsOffset--;\n }\n if (bitsOffset < 0) {\n return null;\n }\n var y = Math.floor(bitsOffset / rowSize);\n var x = Math.floor(bitsOffset % rowSize) * 32;\n var theBits = bits[bitsOffset];\n var bit = 31;\n while ((theBits >>> bit) === 0) {\n bit--;\n }\n x += bit;\n return Int32Array.from([x, y]);\n };\n /**\n * @return The width of the matrix\n */\n BitMatrix.prototype.getWidth = function () {\n return this.width;\n };\n /**\n * @return The height of the matrix\n */\n BitMatrix.prototype.getHeight = function () {\n return this.height;\n };\n /**\n * @return The row size of the matrix\n */\n BitMatrix.prototype.getRowSize = function () {\n return this.rowSize;\n };\n /*@Override*/\n BitMatrix.prototype.equals = function (o) {\n if (!(o instanceof BitMatrix)) {\n return false;\n }\n var other = o;\n return this.width === other.width && this.height === other.height && this.rowSize === other.rowSize &&\n Arrays.equals(this.bits, other.bits);\n };\n /*@Override*/\n BitMatrix.prototype.hashCode = function () {\n var hash = this.width;\n hash = 31 * hash + this.width;\n hash = 31 * hash + this.height;\n hash = 31 * hash + this.rowSize;\n hash = 31 * hash + Arrays.hashCode(this.bits);\n return hash;\n };\n /**\n * @return string representation using \"X\" for set and \" \" for unset bits\n */\n /*@Override*/\n // public toString(): string {\n // return toString(\": \"X, \" \")\n // }\n /**\n * @param setString representation of a set bit\n * @param unsetString representation of an unset bit\n * @return string representation of entire matrix utilizing given strings\n */\n // public toString(setString: string = \"X \", unsetString: string = \" \"): string {\n // return this.buildToString(setString, unsetString, \"\\n\")\n // }\n /**\n * @param setString representation of a set bit\n * @param unsetString representation of an unset bit\n * @param lineSeparator newline character in string representation\n * @return string representation of entire matrix utilizing given strings and line separator\n * @deprecated call {@link #toString(String,String)} only, which uses \\n line separator always\n */\n // @Deprecated\n BitMatrix.prototype.toString = function (setString, unsetString, lineSeparator) {\n if (setString === void 0) { setString = 'X '; }\n if (unsetString === void 0) { unsetString = ' '; }\n if (lineSeparator === void 0) { lineSeparator = '\\n'; }\n return this.buildToString(setString, unsetString, lineSeparator);\n };\n BitMatrix.prototype.buildToString = function (setString, unsetString, lineSeparator) {\n var result = new StringBuilder();\n // result.append(lineSeparator);\n for (var y = 0, height = this.height; y < height; y++) {\n for (var x = 0, width = this.width; x < width; x++) {\n result.append(this.get(x, y) ? setString : unsetString);\n }\n result.append(lineSeparator);\n }\n return result.toString();\n };\n /*@Override*/\n BitMatrix.prototype.clone = function () {\n return new BitMatrix(this.width, this.height, this.rowSize, this.bits.slice());\n };\n return BitMatrix;\n}());\nexport default BitMatrix;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.common {*/\nimport IllegalArgumentException from '../IllegalArgumentException';\n/**\n *This provides an easy abstraction to read bits at a time from a sequence of bytes, where the\n * number of bits read is not often a multiple of 8.
\n *\n *This class is thread-safe but not reentrant -- unless the caller modifies the bytes array\n * it passed in, in which case all bets are off.
\n *\n * @author Sean Owen\n */\nvar BitSource = /** @class */ (function () {\n /**\n * @param bytes bytes from which this will read bits. Bits will be read from the first byte first.\n * Bits are read within a byte from most-significant to least-significant bit.\n */\n function BitSource(bytes) {\n this.bytes = bytes;\n this.byteOffset = 0;\n this.bitOffset = 0;\n }\n /**\n * @return index of next bit in current byte which would be read by the next call to {@link #readBits(int)}.\n */\n BitSource.prototype.getBitOffset = function () {\n return this.bitOffset;\n };\n /**\n * @return index of next byte in input byte array which would be read by the next call to {@link #readBits(int)}.\n */\n BitSource.prototype.getByteOffset = function () {\n return this.byteOffset;\n };\n /**\n * @param numBits number of bits to read\n * @return int representing the bits read. The bits will appear as the least-significant\n * bits of the int\n * @throws IllegalArgumentException if numBits isn't in [1,32] or more than is available\n */\n BitSource.prototype.readBits = function (numBits /*int*/) {\n if (numBits < 1 || numBits > 32 || numBits > this.available()) {\n throw new IllegalArgumentException('' + numBits);\n }\n var result = 0;\n var bitOffset = this.bitOffset;\n var byteOffset = this.byteOffset;\n var bytes = this.bytes;\n // First, read remainder from current byte\n if (bitOffset > 0) {\n var bitsLeft = 8 - bitOffset;\n var toRead = numBits < bitsLeft ? numBits : bitsLeft;\n var bitsToNotRead = bitsLeft - toRead;\n var mask = (0xFF >> (8 - toRead)) << bitsToNotRead;\n result = (bytes[byteOffset] & mask) >> bitsToNotRead;\n numBits -= toRead;\n bitOffset += toRead;\n if (bitOffset === 8) {\n bitOffset = 0;\n byteOffset++;\n }\n }\n // Next read whole bytes\n if (numBits > 0) {\n while (numBits >= 8) {\n result = (result << 8) | (bytes[byteOffset] & 0xFF);\n byteOffset++;\n numBits -= 8;\n }\n // Finally read a partial byte\n if (numBits > 0) {\n var bitsToNotRead = 8 - numBits;\n var mask = (0xFF >> bitsToNotRead) << bitsToNotRead;\n result = (result << numBits) | ((bytes[byteOffset] & mask) >> bitsToNotRead);\n bitOffset += numBits;\n }\n }\n this.bitOffset = bitOffset;\n this.byteOffset = byteOffset;\n return result;\n };\n /**\n * @return number of bits that can be read successfully\n */\n BitSource.prototype.available = function () {\n return 8 * (this.bytes.length - this.byteOffset) - this.bitOffset;\n };\n return BitSource;\n}());\nexport default BitSource;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.common {*/\nimport FormatException from '../FormatException';\n/*import java.util.HashMap;*/\n/*import java.util.Map;*/\nexport var CharacterSetValueIdentifiers;\n(function (CharacterSetValueIdentifiers) {\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"Cp437\"] = 0] = \"Cp437\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_1\"] = 1] = \"ISO8859_1\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_2\"] = 2] = \"ISO8859_2\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_3\"] = 3] = \"ISO8859_3\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_4\"] = 4] = \"ISO8859_4\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_5\"] = 5] = \"ISO8859_5\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_6\"] = 6] = \"ISO8859_6\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_7\"] = 7] = \"ISO8859_7\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_8\"] = 8] = \"ISO8859_8\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_9\"] = 9] = \"ISO8859_9\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_10\"] = 10] = \"ISO8859_10\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_11\"] = 11] = \"ISO8859_11\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_13\"] = 12] = \"ISO8859_13\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_14\"] = 13] = \"ISO8859_14\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_15\"] = 14] = \"ISO8859_15\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ISO8859_16\"] = 15] = \"ISO8859_16\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"SJIS\"] = 16] = \"SJIS\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"Cp1250\"] = 17] = \"Cp1250\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"Cp1251\"] = 18] = \"Cp1251\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"Cp1252\"] = 19] = \"Cp1252\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"Cp1256\"] = 20] = \"Cp1256\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"UnicodeBigUnmarked\"] = 21] = \"UnicodeBigUnmarked\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"UTF8\"] = 22] = \"UTF8\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"ASCII\"] = 23] = \"ASCII\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"Big5\"] = 24] = \"Big5\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"GB18030\"] = 25] = \"GB18030\";\n CharacterSetValueIdentifiers[CharacterSetValueIdentifiers[\"EUC_KR\"] = 26] = \"EUC_KR\";\n})(CharacterSetValueIdentifiers || (CharacterSetValueIdentifiers = {}));\n/**\n * Encapsulates a Character Set ECI, according to \"Extended Channel Interpretations\" 5.3.1.1\n * of ISO 18004.\n *\n * @author Sean Owen\n */\nvar CharacterSetECI = /** @class */ (function () {\n function CharacterSetECI(valueIdentifier, valuesParam, name) {\n var e_1, _a;\n var otherEncodingNames = [];\n for (var _i = 3; _i < arguments.length; _i++) {\n otherEncodingNames[_i - 3] = arguments[_i];\n }\n this.valueIdentifier = valueIdentifier;\n this.name = name;\n if (typeof valuesParam === 'number') {\n this.values = Int32Array.from([valuesParam]);\n }\n else {\n this.values = valuesParam;\n }\n this.otherEncodingNames = otherEncodingNames;\n CharacterSetECI.VALUE_IDENTIFIER_TO_ECI.set(valueIdentifier, this);\n CharacterSetECI.NAME_TO_ECI.set(name, this);\n var values = this.values;\n for (var i = 0, length_1 = values.length; i !== length_1; i++) {\n var v = values[i];\n CharacterSetECI.VALUES_TO_ECI.set(v, this);\n }\n try {\n for (var otherEncodingNames_1 = __values(otherEncodingNames), otherEncodingNames_1_1 = otherEncodingNames_1.next(); !otherEncodingNames_1_1.done; otherEncodingNames_1_1 = otherEncodingNames_1.next()) {\n var otherName = otherEncodingNames_1_1.value;\n CharacterSetECI.NAME_TO_ECI.set(otherName, this);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (otherEncodingNames_1_1 && !otherEncodingNames_1_1.done && (_a = otherEncodingNames_1.return)) _a.call(otherEncodingNames_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n // CharacterSetECI(value: number /*int*/) {\n // this(new Int32Array {value})\n // }\n // CharacterSetECI(value: number /*int*/, String... otherEncodingNames) {\n // this.values = new Int32Array {value}\n // this.otherEncodingNames = otherEncodingNames\n // }\n // CharacterSetECI(values: Int32Array, String... otherEncodingNames) {\n // this.values = values\n // this.otherEncodingNames = otherEncodingNames\n // }\n CharacterSetECI.prototype.getValueIdentifier = function () {\n return this.valueIdentifier;\n };\n CharacterSetECI.prototype.getName = function () {\n return this.name;\n };\n CharacterSetECI.prototype.getValue = function () {\n return this.values[0];\n };\n /**\n * @param value character set ECI value\n * @return {@code CharacterSetECI} representing ECI of given value, or null if it is legal but\n * unsupported\n * @throws FormatException if ECI value is invalid\n */\n CharacterSetECI.getCharacterSetECIByValue = function (value /*int*/) {\n if (value < 0 || value >= 900) {\n throw new FormatException('incorect value');\n }\n var characterSet = CharacterSetECI.VALUES_TO_ECI.get(value);\n if (undefined === characterSet) {\n throw new FormatException('incorect value');\n }\n return characterSet;\n };\n /**\n * @param name character set ECI encoding name\n * @return CharacterSetECI representing ECI for character encoding, or null if it is legal\n * but unsupported\n */\n CharacterSetECI.getCharacterSetECIByName = function (name) {\n var characterSet = CharacterSetECI.NAME_TO_ECI.get(name);\n if (undefined === characterSet) {\n throw new FormatException('incorect value');\n }\n return characterSet;\n };\n CharacterSetECI.prototype.equals = function (o) {\n if (!(o instanceof CharacterSetECI)) {\n return false;\n }\n var other = o;\n return this.getName() === other.getName();\n };\n CharacterSetECI.VALUE_IDENTIFIER_TO_ECI = new Map();\n CharacterSetECI.VALUES_TO_ECI = new Map();\n CharacterSetECI.NAME_TO_ECI = new Map();\n // Enum name is a Java encoding valid for java.lang and java.io\n // TYPESCRIPTPORT: changed the main label for ISO as the TextEncoder did not recognized them in the form from java\n // (eg ISO8859_1 must be ISO88591 or ISO8859-1 or ISO-8859-1)\n // later on: well, except 16 wich does not work with ISO885916 so used ISO-8859-1 form for default\n CharacterSetECI.Cp437 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp437, Int32Array.from([0, 2]), 'Cp437');\n CharacterSetECI.ISO8859_1 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_1, Int32Array.from([1, 3]), 'ISO-8859-1', 'ISO88591', 'ISO8859_1');\n CharacterSetECI.ISO8859_2 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_2, 4, 'ISO-8859-2', 'ISO88592', 'ISO8859_2');\n CharacterSetECI.ISO8859_3 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_3, 5, 'ISO-8859-3', 'ISO88593', 'ISO8859_3');\n CharacterSetECI.ISO8859_4 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_4, 6, 'ISO-8859-4', 'ISO88594', 'ISO8859_4');\n CharacterSetECI.ISO8859_5 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_5, 7, 'ISO-8859-5', 'ISO88595', 'ISO8859_5');\n CharacterSetECI.ISO8859_6 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_6, 8, 'ISO-8859-6', 'ISO88596', 'ISO8859_6');\n CharacterSetECI.ISO8859_7 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_7, 9, 'ISO-8859-7', 'ISO88597', 'ISO8859_7');\n CharacterSetECI.ISO8859_8 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_8, 10, 'ISO-8859-8', 'ISO88598', 'ISO8859_8');\n CharacterSetECI.ISO8859_9 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_9, 11, 'ISO-8859-9', 'ISO88599', 'ISO8859_9');\n CharacterSetECI.ISO8859_10 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_10, 12, 'ISO-8859-10', 'ISO885910', 'ISO8859_10');\n CharacterSetECI.ISO8859_11 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_11, 13, 'ISO-8859-11', 'ISO885911', 'ISO8859_11');\n CharacterSetECI.ISO8859_13 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_13, 15, 'ISO-8859-13', 'ISO885913', 'ISO8859_13');\n CharacterSetECI.ISO8859_14 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_14, 16, 'ISO-8859-14', 'ISO885914', 'ISO8859_14');\n CharacterSetECI.ISO8859_15 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_15, 17, 'ISO-8859-15', 'ISO885915', 'ISO8859_15');\n CharacterSetECI.ISO8859_16 = new CharacterSetECI(CharacterSetValueIdentifiers.ISO8859_16, 18, 'ISO-8859-16', 'ISO885916', 'ISO8859_16');\n CharacterSetECI.SJIS = new CharacterSetECI(CharacterSetValueIdentifiers.SJIS, 20, 'SJIS', 'Shift_JIS');\n CharacterSetECI.Cp1250 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp1250, 21, 'Cp1250', 'windows-1250');\n CharacterSetECI.Cp1251 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp1251, 22, 'Cp1251', 'windows-1251');\n CharacterSetECI.Cp1252 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp1252, 23, 'Cp1252', 'windows-1252');\n CharacterSetECI.Cp1256 = new CharacterSetECI(CharacterSetValueIdentifiers.Cp1256, 24, 'Cp1256', 'windows-1256');\n CharacterSetECI.UnicodeBigUnmarked = new CharacterSetECI(CharacterSetValueIdentifiers.UnicodeBigUnmarked, 25, 'UnicodeBigUnmarked', 'UTF-16BE', 'UnicodeBig');\n CharacterSetECI.UTF8 = new CharacterSetECI(CharacterSetValueIdentifiers.UTF8, 26, 'UTF8', 'UTF-8');\n CharacterSetECI.ASCII = new CharacterSetECI(CharacterSetValueIdentifiers.ASCII, Int32Array.from([27, 170]), 'ASCII', 'US-ASCII');\n CharacterSetECI.Big5 = new CharacterSetECI(CharacterSetValueIdentifiers.Big5, 28, 'Big5');\n CharacterSetECI.GB18030 = new CharacterSetECI(CharacterSetValueIdentifiers.GB18030, 29, 'GB18030', 'GB2312', 'EUC_CN', 'GBK');\n CharacterSetECI.EUC_KR = new CharacterSetECI(CharacterSetValueIdentifiers.EUC_KR, 30, 'EUC_KR', 'EUC-KR');\n return CharacterSetECI;\n}());\nexport default CharacterSetECI;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.common {*/\n/*import java.util.List;*/\n/**\n *Encapsulates the result of decoding a matrix of bits. This typically\n * applies to 2D barcode formats. For now it contains the raw bytes obtained,\n * as well as a String interpretation of those bytes, if applicable.
\n *\n * @author Sean Owen\n */\nvar DecoderResult = /** @class */ (function () {\n // public constructor(rawBytes: Uint8Array,\n // text: string,\n // ListEncapsulates the result of detecting a barcode in an image. This includes the raw\n * matrix of black/white pixels corresponding to the barcode, and possibly points of interest\n * in the image, like the location of finder patterns or corners of the barcode in the image.
\n *\n * @author Sean Owen\n */\nvar DetectorResult = /** @class */ (function () {\n function DetectorResult(bits, points) {\n this.bits = bits;\n this.points = points;\n }\n DetectorResult.prototype.getBits = function () {\n return this.bits;\n };\n DetectorResult.prototype.getPoints = function () {\n return this.points;\n };\n return DetectorResult;\n}());\nexport default DetectorResult;\n","/**\n * Set of CharsetEncoders for a given input string\n *\n * Invariants:\n * - The list contains only encoders from CharacterSetECI (list is shorter then the list of encoders available on\n * the platform for which ECI values are defined).\n * - The list contains encoders at least one encoder for every character in the input.\n * - The first encoder in the list is always the ISO-8859-1 encoder even of no character in the input can be encoded\n * by it.\n * - If the input contains a character that is not in ISO-8859-1 then the last two entries in the list will be the\n * UTF-8 encoder and the UTF-16BE encoder.\n *\n * @author Alex Geller\n */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport Charset from '../util/Charset';\nimport StandardCharsets from '../util/StandardCharsets';\nimport StringEncoding from '../util/StringEncoding';\nimport StringUtils from './StringUtils';\nvar CharsetEncoder = /** @class */ (function () {\n function CharsetEncoder(charset) {\n this.charset = charset;\n this.name = charset.name;\n }\n CharsetEncoder.prototype.canEncode = function (c) {\n try {\n return StringEncoding.encode(c, this.charset) != null;\n }\n catch (ex) {\n return false;\n }\n };\n return CharsetEncoder;\n}());\nvar ECIEncoderSet = /** @class */ (function () {\n /**\n * Constructs an encoder set\n *\n * @param stringToEncode the string that needs to be encoded\n * @param priorityCharset The preferred {@link Charset} or null.\n * @param fnc1 fnc1 denotes the character in the input that represents the FNC1 character or -1 for a non-GS1 bar\n * code. When specified, it is considered an error to pass it as argument to the methods canEncode() or encode().\n */\n function ECIEncoderSet(stringToEncode, priorityCharset, fnc1) {\n var e_1, _a, e_2, _b, e_3, _c;\n this.ENCODERS = [\n 'IBM437',\n 'ISO-8859-2',\n 'ISO-8859-3',\n 'ISO-8859-4',\n 'ISO-8859-5',\n 'ISO-8859-6',\n 'ISO-8859-7',\n 'ISO-8859-8',\n 'ISO-8859-9',\n 'ISO-8859-10',\n 'ISO-8859-11',\n 'ISO-8859-13',\n 'ISO-8859-14',\n 'ISO-8859-15',\n 'ISO-8859-16',\n 'windows-1250',\n 'windows-1251',\n 'windows-1252',\n 'windows-1256',\n 'Shift_JIS',\n ].map(function (name) { return new CharsetEncoder(Charset.forName(name)); });\n this.encoders = [];\n var neededEncoders = [];\n // we always need the ISO-8859-1 encoder. It is the default encoding\n neededEncoders.push(new CharsetEncoder(StandardCharsets.ISO_8859_1));\n var needUnicodeEncoder = priorityCharset != null && priorityCharset.name.startsWith('UTF');\n // Walk over the input string and see if all characters can be encoded with the list of encoders\n for (var i = 0; i < stringToEncode.length; i++) {\n var canEncode = false;\n try {\n for (var neededEncoders_1 = (e_1 = void 0, __values(neededEncoders)), neededEncoders_1_1 = neededEncoders_1.next(); !neededEncoders_1_1.done; neededEncoders_1_1 = neededEncoders_1.next()) {\n var encoder = neededEncoders_1_1.value;\n var singleCharacter = stringToEncode.charAt(i);\n var c = singleCharacter.charCodeAt(0);\n if (c === fnc1 || encoder.canEncode(singleCharacter)) {\n canEncode = true;\n break;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (neededEncoders_1_1 && !neededEncoders_1_1.done && (_a = neededEncoders_1.return)) _a.call(neededEncoders_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n if (!canEncode) {\n try {\n // for the character at position i we don't yet have an encoder in the list\n for (var _d = (e_2 = void 0, __values(this.ENCODERS)), _e = _d.next(); !_e.done; _e = _d.next()) {\n var encoder = _e.value;\n if (encoder.canEncode(stringToEncode.charAt(i))) {\n // Good, we found an encoder that can encode the character. We add him to the list and continue scanning\n // the input\n neededEncoders.push(encoder);\n canEncode = true;\n break;\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_e && !_e.done && (_b = _d.return)) _b.call(_d);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n if (!canEncode) {\n // The character is not encodeable by any of the single byte encoders so we remember that we will need a\n // Unicode encoder.\n needUnicodeEncoder = true;\n }\n }\n if (neededEncoders.length === 1 && !needUnicodeEncoder) {\n // the entire input can be encoded by the ISO-8859-1 encoder\n this.encoders = [neededEncoders[0]];\n }\n else {\n // we need more than one single byte encoder or we need a Unicode encoder.\n // In this case we append a UTF-8 and UTF-16 encoder to the list\n this.encoders = [];\n var index = 0;\n try {\n for (var neededEncoders_2 = __values(neededEncoders), neededEncoders_2_1 = neededEncoders_2.next(); !neededEncoders_2_1.done; neededEncoders_2_1 = neededEncoders_2.next()) {\n var encoder = neededEncoders_2_1.value;\n this.encoders[index++] = encoder;\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (neededEncoders_2_1 && !neededEncoders_2_1.done && (_c = neededEncoders_2.return)) _c.call(neededEncoders_2);\n }\n finally { if (e_3) throw e_3.error; }\n }\n // this.encoders[index] = new CharsetEncoder(StandardCharsets.UTF_8);\n // this.encoders[index + 1] = new CharsetEncoder(StandardCharsets.UTF_16BE);\n }\n // Compute priorityEncoderIndex by looking up priorityCharset in encoders\n var priorityEncoderIndexValue = -1;\n if (priorityCharset != null) {\n for (var i = 0; i < this.encoders.length; i++) {\n if (this.encoders[i] != null &&\n priorityCharset.name === this.encoders[i].name) {\n priorityEncoderIndexValue = i;\n break;\n }\n }\n }\n this.priorityEncoderIndex = priorityEncoderIndexValue;\n // invariants\n // if(this?.encoders?.[0].name !== StandardCharsets.ISO_8859_1)){\n // throw new Error(\"ISO-8859-1 must be the first encoder\");\n // }\n }\n ECIEncoderSet.prototype.length = function () {\n return this.encoders.length;\n };\n ECIEncoderSet.prototype.getCharsetName = function (index) {\n if (!(index < this.length())) {\n throw new Error('index must be less than length');\n }\n return this.encoders[index].name;\n };\n ECIEncoderSet.prototype.getCharset = function (index) {\n if (!(index < this.length())) {\n throw new Error('index must be less than length');\n }\n return this.encoders[index].charset;\n };\n ECIEncoderSet.prototype.getECIValue = function (encoderIndex) {\n return this.encoders[encoderIndex].charset.getValueIdentifier();\n };\n /*\n * returns -1 if no priority charset was defined\n */\n ECIEncoderSet.prototype.getPriorityEncoderIndex = function () {\n return this.priorityEncoderIndex;\n };\n ECIEncoderSet.prototype.canEncode = function (c, encoderIndex) {\n if (!(encoderIndex < this.length())) {\n throw new Error('index must be less than length');\n }\n return true;\n };\n ECIEncoderSet.prototype.encode = function (c, encoderIndex) {\n if (!(encoderIndex < this.length())) {\n throw new Error('index must be less than length');\n }\n return StringEncoding.encode(StringUtils.getCharAt(c), this.encoders[encoderIndex].name);\n };\n return ECIEncoderSet;\n}());\nexport { ECIEncoderSet };\n","/*\n * Copyright 2009 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/*namespace com.google.zxing.common {*/\nimport Binarizer from '../Binarizer';\nimport BitArray from './BitArray';\nimport BitMatrix from './BitMatrix';\nimport NotFoundException from '../NotFoundException';\n/**\n * This Binarizer implementation uses the old ZXing global histogram approach. It is suitable\n * for low-end mobile devices which don't have enough CPU or memory to use a local thresholding\n * algorithm. However, because it picks a global black point, it cannot handle difficult shadows\n * and gradients.\n *\n * Faster mobile devices and all desktop applications should probably use HybridBinarizer instead.\n *\n * @author dswitkin@google.com (Daniel Switkin)\n * @author Sean Owen\n */\nvar GlobalHistogramBinarizer = /** @class */ (function (_super) {\n __extends(GlobalHistogramBinarizer, _super);\n function GlobalHistogramBinarizer(source) {\n var _this = _super.call(this, source) || this;\n _this.luminances = GlobalHistogramBinarizer.EMPTY;\n _this.buckets = new Int32Array(GlobalHistogramBinarizer.LUMINANCE_BUCKETS);\n return _this;\n }\n // Applies simple sharpening to the row data to improve performance of the 1D Readers.\n /*@Override*/\n GlobalHistogramBinarizer.prototype.getBlackRow = function (y /*int*/, row) {\n var source = this.getLuminanceSource();\n var width = source.getWidth();\n if (row === undefined || row === null || row.getSize() < width) {\n row = new BitArray(width);\n }\n else {\n row.clear();\n }\n this.initArrays(width);\n var localLuminances = source.getRow(y, this.luminances);\n var localBuckets = this.buckets;\n for (var x = 0; x < width; x++) {\n localBuckets[(localLuminances[x] & 0xff) >> GlobalHistogramBinarizer.LUMINANCE_SHIFT]++;\n }\n var blackPoint = GlobalHistogramBinarizer.estimateBlackPoint(localBuckets);\n if (width < 3) {\n // Special case for very small images\n for (var x = 0; x < width; x++) {\n if ((localLuminances[x] & 0xff) < blackPoint) {\n row.set(x);\n }\n }\n }\n else {\n var left = localLuminances[0] & 0xff;\n var center = localLuminances[1] & 0xff;\n for (var x = 1; x < width - 1; x++) {\n var right = localLuminances[x + 1] & 0xff;\n // A simple -1 4 -1 box filter with a weight of 2.\n if (((center * 4) - left - right) / 2 < blackPoint) {\n row.set(x);\n }\n left = center;\n center = right;\n }\n }\n return row;\n };\n // Does not sharpen the data, as this call is intended to only be used by 2D Readers.\n /*@Override*/\n GlobalHistogramBinarizer.prototype.getBlackMatrix = function () {\n var source = this.getLuminanceSource();\n var width = source.getWidth();\n var height = source.getHeight();\n var matrix = new BitMatrix(width, height);\n // Quickly calculates the histogram by sampling four rows from the image. This proved to be\n // more robust on the blackbox tests than sampling a diagonal as we used to do.\n this.initArrays(width);\n var localBuckets = this.buckets;\n for (var y = 1; y < 5; y++) {\n var row = Math.floor((height * y) / 5);\n var localLuminances_1 = source.getRow(row, this.luminances);\n var right = Math.floor((width * 4) / 5);\n for (var x = Math.floor(width / 5); x < right; x++) {\n var pixel = localLuminances_1[x] & 0xff;\n localBuckets[pixel >> GlobalHistogramBinarizer.LUMINANCE_SHIFT]++;\n }\n }\n var blackPoint = GlobalHistogramBinarizer.estimateBlackPoint(localBuckets);\n // We delay reading the entire image luminance until the black point estimation succeeds.\n // Although we end up reading four rows twice, it is consistent with our motto of\n // \"fail quickly\" which is necessary for continuous scanning.\n var localLuminances = source.getMatrix();\n for (var y = 0; y < height; y++) {\n var offset = y * width;\n for (var x = 0; x < width; x++) {\n var pixel = localLuminances[offset + x] & 0xff;\n if (pixel < blackPoint) {\n matrix.set(x, y);\n }\n }\n }\n return matrix;\n };\n /*@Override*/\n GlobalHistogramBinarizer.prototype.createBinarizer = function (source) {\n return new GlobalHistogramBinarizer(source);\n };\n GlobalHistogramBinarizer.prototype.initArrays = function (luminanceSize /*int*/) {\n if (this.luminances.length < luminanceSize) {\n this.luminances = new Uint8ClampedArray(luminanceSize);\n }\n var buckets = this.buckets;\n for (var x = 0; x < GlobalHistogramBinarizer.LUMINANCE_BUCKETS; x++) {\n buckets[x] = 0;\n }\n };\n GlobalHistogramBinarizer.estimateBlackPoint = function (buckets) {\n // Find the tallest peak in the histogram.\n var numBuckets = buckets.length;\n var maxBucketCount = 0;\n var firstPeak = 0;\n var firstPeakSize = 0;\n for (var x = 0; x < numBuckets; x++) {\n if (buckets[x] > firstPeakSize) {\n firstPeak = x;\n firstPeakSize = buckets[x];\n }\n if (buckets[x] > maxBucketCount) {\n maxBucketCount = buckets[x];\n }\n }\n // Find the second-tallest peak which is somewhat far from the tallest peak.\n var secondPeak = 0;\n var secondPeakScore = 0;\n for (var x = 0; x < numBuckets; x++) {\n var distanceToBiggest = x - firstPeak;\n // Encourage more distant second peaks by multiplying by square of distance.\n var score = buckets[x] * distanceToBiggest * distanceToBiggest;\n if (score > secondPeakScore) {\n secondPeak = x;\n secondPeakScore = score;\n }\n }\n // Make sure firstPeak corresponds to the black peak.\n if (firstPeak > secondPeak) {\n var temp = firstPeak;\n firstPeak = secondPeak;\n secondPeak = temp;\n }\n // If there is too little contrast in the image to pick a meaningful black point, throw rather\n // than waste time trying to decode the image, and risk false positives.\n if (secondPeak - firstPeak <= numBuckets / 16) {\n throw new NotFoundException();\n }\n // Find a valley between them that is low and closer to the white peak.\n var bestValley = secondPeak - 1;\n var bestValleyScore = -1;\n for (var x = secondPeak - 1; x > firstPeak; x--) {\n var fromFirst = x - firstPeak;\n var score = fromFirst * fromFirst * (secondPeak - x) * (maxBucketCount - buckets[x]);\n if (score > bestValleyScore) {\n bestValley = x;\n bestValleyScore = score;\n }\n }\n return bestValley << GlobalHistogramBinarizer.LUMINANCE_SHIFT;\n };\n GlobalHistogramBinarizer.LUMINANCE_BITS = 5;\n GlobalHistogramBinarizer.LUMINANCE_SHIFT = 8 - GlobalHistogramBinarizer.LUMINANCE_BITS;\n GlobalHistogramBinarizer.LUMINANCE_BUCKETS = 1 << GlobalHistogramBinarizer.LUMINANCE_BITS;\n GlobalHistogramBinarizer.EMPTY = Uint8ClampedArray.from([0]);\n return GlobalHistogramBinarizer;\n}(Binarizer));\nexport default GlobalHistogramBinarizer;\n","/*\n * Copyright 2007 ZXing authors\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 */\nimport NotFoundException from '../NotFoundException';\n/**\n * Implementations of this class can, given locations of finder patterns for a QR code in an\n * image, sample the right points in the image to reconstruct the QR code, accounting for\n * perspective distortion. It is abstracted since it is relatively expensive and should be allowed\n * to take advantage of platform-specific optimized implementations, like Sun's Java Advanced\n * Imaging library, but which may not be available in other environments such as J2ME, and vice\n * versa.\n *\n * The implementation used can be controlled by calling {@link #setGridSampler(GridSampler)}\n * with an instance of a class which implements this interface.\n *\n * @author Sean Owen\n */\nvar GridSampler = /** @class */ (function () {\n function GridSampler() {\n }\n /**\n *Checks a set of points that have been transformed to sample points on an image against\n * the image's dimensions to see if the point are even within the image.
\n *\n *This method will actually \"nudge\" the endpoints back onto the image if they are found to be\n * barely (less than 1 pixel) off the image. This accounts for imperfect detection of finder\n * patterns in an image where the QR Code runs all the way to the image border.
\n *\n *For efficiency, the method will check points from either end of the line until one is found\n * to be within the image. Because the set of points are assumed to be linear, this is valid.
\n *\n * @param image image into which the points should map\n * @param points actual points in x1,y1,...,xn,yn form\n * @throws NotFoundException if an endpoint is lies outside the image boundaries\n */\n GridSampler.checkAndNudgePoints = function (image, points) {\n var width = image.getWidth();\n var height = image.getHeight();\n // Check and nudge points from start until we see some that are OK:\n var nudged = true;\n for (var offset = 0; offset < points.length && nudged; offset += 2) {\n var x = Math.floor(points[offset]);\n var y = Math.floor(points[offset + 1]);\n if (x < -1 || x > width || y < -1 || y > height) {\n throw new NotFoundException();\n }\n nudged = false;\n if (x === -1) {\n points[offset] = 0.0;\n nudged = true;\n }\n else if (x === width) {\n points[offset] = width - 1;\n nudged = true;\n }\n if (y === -1) {\n points[offset + 1] = 0.0;\n nudged = true;\n }\n else if (y === height) {\n points[offset + 1] = height - 1;\n nudged = true;\n }\n }\n // Check and nudge points from end:\n nudged = true;\n for (var offset = points.length - 2; offset >= 0 && nudged; offset -= 2) {\n var x = Math.floor(points[offset]);\n var y = Math.floor(points[offset + 1]);\n if (x < -1 || x > width || y < -1 || y > height) {\n throw new NotFoundException();\n }\n nudged = false;\n if (x === -1) {\n points[offset] = 0.0;\n nudged = true;\n }\n else if (x === width) {\n points[offset] = width - 1;\n nudged = true;\n }\n if (y === -1) {\n points[offset + 1] = 0.0;\n nudged = true;\n }\n else if (y === height) {\n points[offset + 1] = height - 1;\n nudged = true;\n }\n }\n };\n return GridSampler;\n}());\nexport default GridSampler;\n","import DefaultGridSampler from './DefaultGridSampler';\nvar GridSamplerInstance = /** @class */ (function () {\n function GridSamplerInstance() {\n }\n /**\n * Sets the implementation of GridSampler used by the library. One global\n * instance is stored, which may sound problematic. But, the implementation provided\n * ought to be appropriate for the entire platform, and all uses of this library\n * in the whole lifetime of the JVM. For instance, an Android activity can swap in\n * an implementation that takes advantage of native platform libraries.\n *\n * @param newGridSampler The platform-specific object to install.\n */\n GridSamplerInstance.setGridSampler = function (newGridSampler) {\n GridSamplerInstance.gridSampler = newGridSampler;\n };\n /**\n * @return the current implementation of GridSampler\n */\n GridSamplerInstance.getInstance = function () {\n return GridSamplerInstance.gridSampler;\n };\n GridSamplerInstance.gridSampler = new DefaultGridSampler();\n return GridSamplerInstance;\n}());\nexport default GridSamplerInstance;\n","/*\n * Copyright 2009 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport GlobalHistogramBinarizer from './GlobalHistogramBinarizer';\nimport BitMatrix from './BitMatrix';\n/**\n * This class implements a local thresholding algorithm, which while slower than the\n * GlobalHistogramBinarizer, is fairly efficient for what it does. It is designed for\n * high frequency images of barcodes with black data on white backgrounds. For this application,\n * it does a much better job than a global blackpoint with severe shadows and gradients.\n * However it tends to produce artifacts on lower frequency images and is therefore not\n * a good general purpose binarizer for uses outside ZXing.\n *\n * This class extends GlobalHistogramBinarizer, using the older histogram approach for 1D readers,\n * and the newer local approach for 2D readers. 1D decoding using a per-row histogram is already\n * inherently local, and only fails for horizontal gradients. We can revisit that problem later,\n * but for now it was not a win to use local blocks for 1D.\n *\n * This Binarizer is the default for the unit tests and the recommended class for library users.\n *\n * @author dswitkin@google.com (Daniel Switkin)\n */\nvar HybridBinarizer = /** @class */ (function (_super) {\n __extends(HybridBinarizer, _super);\n function HybridBinarizer(source) {\n var _this = _super.call(this, source) || this;\n _this.matrix = null;\n return _this;\n }\n /**\n * Calculates the final BitMatrix once for all requests. This could be called once from the\n * constructor instead, but there are some advantages to doing it lazily, such as making\n * profiling easier, and not doing heavy lifting when callers don't expect it.\n */\n /*@Override*/\n HybridBinarizer.prototype.getBlackMatrix = function () {\n if (this.matrix !== null) {\n return this.matrix;\n }\n var source = this.getLuminanceSource();\n var width = source.getWidth();\n var height = source.getHeight();\n if (width >= HybridBinarizer.MINIMUM_DIMENSION && height >= HybridBinarizer.MINIMUM_DIMENSION) {\n var luminances = source.getMatrix();\n var subWidth = width >> HybridBinarizer.BLOCK_SIZE_POWER;\n if ((width & HybridBinarizer.BLOCK_SIZE_MASK) !== 0) {\n subWidth++;\n }\n var subHeight = height >> HybridBinarizer.BLOCK_SIZE_POWER;\n if ((height & HybridBinarizer.BLOCK_SIZE_MASK) !== 0) {\n subHeight++;\n }\n var blackPoints = HybridBinarizer.calculateBlackPoints(luminances, subWidth, subHeight, width, height);\n var newMatrix = new BitMatrix(width, height);\n HybridBinarizer.calculateThresholdForBlock(luminances, subWidth, subHeight, width, height, blackPoints, newMatrix);\n this.matrix = newMatrix;\n }\n else {\n // If the image is too small, fall back to the global histogram approach.\n this.matrix = _super.prototype.getBlackMatrix.call(this);\n }\n return this.matrix;\n };\n /*@Override*/\n HybridBinarizer.prototype.createBinarizer = function (source) {\n return new HybridBinarizer(source);\n };\n /**\n * For each block in the image, calculate the average black point using a 5x5 grid\n * of the blocks around it. Also handles the corner cases (fractional blocks are computed based\n * on the last pixels in the row/column which are also used in the previous block).\n */\n HybridBinarizer.calculateThresholdForBlock = function (luminances, subWidth /*int*/, subHeight /*int*/, width /*int*/, height /*int*/, blackPoints, matrix) {\n var maxYOffset = height - HybridBinarizer.BLOCK_SIZE;\n var maxXOffset = width - HybridBinarizer.BLOCK_SIZE;\n for (var y = 0; y < subHeight; y++) {\n var yoffset = y << HybridBinarizer.BLOCK_SIZE_POWER;\n if (yoffset > maxYOffset) {\n yoffset = maxYOffset;\n }\n var top_1 = HybridBinarizer.cap(y, 2, subHeight - 3);\n for (var x = 0; x < subWidth; x++) {\n var xoffset = x << HybridBinarizer.BLOCK_SIZE_POWER;\n if (xoffset > maxXOffset) {\n xoffset = maxXOffset;\n }\n var left = HybridBinarizer.cap(x, 2, subWidth - 3);\n var sum = 0;\n for (var z = -2; z <= 2; z++) {\n var blackRow = blackPoints[top_1 + z];\n sum += blackRow[left - 2] + blackRow[left - 1] + blackRow[left] + blackRow[left + 1] + blackRow[left + 2];\n }\n var average = sum / 25;\n HybridBinarizer.thresholdBlock(luminances, xoffset, yoffset, average, width, matrix);\n }\n }\n };\n HybridBinarizer.cap = function (value /*int*/, min /*int*/, max /*int*/) {\n return value < min ? min : value > max ? max : value;\n };\n /**\n * Applies a single threshold to a block of pixels.\n */\n HybridBinarizer.thresholdBlock = function (luminances, xoffset /*int*/, yoffset /*int*/, threshold /*int*/, stride /*int*/, matrix) {\n for (var y = 0, offset = yoffset * stride + xoffset; y < HybridBinarizer.BLOCK_SIZE; y++, offset += stride) {\n for (var x = 0; x < HybridBinarizer.BLOCK_SIZE; x++) {\n // Comparison needs to be <= so that black == 0 pixels are black even if the threshold is 0.\n if ((luminances[offset + x] & 0xFF) <= threshold) {\n matrix.set(xoffset + x, yoffset + y);\n }\n }\n }\n };\n /**\n * Calculates a single black point for each block of pixels and saves it away.\n * See the following thread for a discussion of this algorithm:\n * http://groups.google.com/group/zxing/browse_thread/thread/d06efa2c35a7ddc0\n */\n HybridBinarizer.calculateBlackPoints = function (luminances, subWidth /*int*/, subHeight /*int*/, width /*int*/, height /*int*/) {\n var maxYOffset = height - HybridBinarizer.BLOCK_SIZE;\n var maxXOffset = width - HybridBinarizer.BLOCK_SIZE;\n // tslint:disable-next-line:whitespace\n var blackPoints = new Array(subHeight); // subWidth\n for (var y = 0; y < subHeight; y++) {\n blackPoints[y] = new Int32Array(subWidth);\n var yoffset = y << HybridBinarizer.BLOCK_SIZE_POWER;\n if (yoffset > maxYOffset) {\n yoffset = maxYOffset;\n }\n for (var x = 0; x < subWidth; x++) {\n var xoffset = x << HybridBinarizer.BLOCK_SIZE_POWER;\n if (xoffset > maxXOffset) {\n xoffset = maxXOffset;\n }\n var sum = 0;\n var min = 0xFF;\n var max = 0;\n for (var yy = 0, offset = yoffset * width + xoffset; yy < HybridBinarizer.BLOCK_SIZE; yy++, offset += width) {\n for (var xx = 0; xx < HybridBinarizer.BLOCK_SIZE; xx++) {\n var pixel = luminances[offset + xx] & 0xFF;\n sum += pixel;\n // still looking for good contrast\n if (pixel < min) {\n min = pixel;\n }\n if (pixel > max) {\n max = pixel;\n }\n }\n // short-circuit min/max tests once dynamic range is met\n if (max - min > HybridBinarizer.MIN_DYNAMIC_RANGE) {\n // finish the rest of the rows quickly\n for (yy++, offset += width; yy < HybridBinarizer.BLOCK_SIZE; yy++, offset += width) {\n for (var xx = 0; xx < HybridBinarizer.BLOCK_SIZE; xx++) {\n sum += luminances[offset + xx] & 0xFF;\n }\n }\n }\n }\n // The default estimate is the average of the values in the block.\n var average = sum >> (HybridBinarizer.BLOCK_SIZE_POWER * 2);\n if (max - min <= HybridBinarizer.MIN_DYNAMIC_RANGE) {\n // If variation within the block is low, assume this is a block with only light or only\n // dark pixels. In that case we do not want to use the average, as it would divide this\n // low contrast area into black and white pixels, essentially creating data out of noise.\n //\n // The default assumption is that the block is light/background. Since no estimate for\n // the level of dark pixels exists locally, use half the min for the block.\n average = min / 2;\n if (y > 0 && x > 0) {\n // Correct the \"white background\" assumption for blocks that have neighbors by comparing\n // the pixels in this block to the previously calculated black points. This is based on\n // the fact that dark barcode symbology is always surrounded by some amount of light\n // background for which reasonable black point estimates were made. The bp estimated at\n // the boundaries is used for the interior.\n // The (min < bp) is arbitrary but works better than other heuristics that were tried.\n var averageNeighborBlackPoint = (blackPoints[y - 1][x] + (2 * blackPoints[y][x - 1]) + blackPoints[y - 1][x - 1]) / 4;\n if (min < averageNeighborBlackPoint) {\n average = averageNeighborBlackPoint;\n }\n }\n }\n blackPoints[y][x] = average;\n }\n }\n return blackPoints;\n };\n // This class uses 5x5 blocks to compute local luminance, where each block is 8x8 pixels.\n // So this is the smallest dimension in each axis we can accept.\n HybridBinarizer.BLOCK_SIZE_POWER = 3;\n HybridBinarizer.BLOCK_SIZE = 1 << HybridBinarizer.BLOCK_SIZE_POWER; // ...0100...00\n HybridBinarizer.BLOCK_SIZE_MASK = HybridBinarizer.BLOCK_SIZE - 1; // ...0011...11\n HybridBinarizer.MINIMUM_DIMENSION = HybridBinarizer.BLOCK_SIZE * 5;\n HybridBinarizer.MIN_DYNAMIC_RANGE = 24;\n return HybridBinarizer;\n}(GlobalHistogramBinarizer));\nexport default HybridBinarizer;\n","import { ECIEncoderSet } from './ECIEncoderSet';\nimport Integer from '../util/Integer';\nimport StringBuilder from '../util/StringBuilder';\nvar COST_PER_ECI = 3; // approximated (latch + 2 codewords)\nvar MinimalECIInput = /** @class */ (function () {\n /**\n * Constructs a minimal input\n *\n * @param stringToEncode the character string to encode\n * @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm\n * chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority\n * charset to encode any character in the input that can be encoded by it if the charset is among the\n * supported charsets.\n * @param fnc1 denotes the character in the input that represents the FNC1 character or -1 if this is not GS1\n * input.\n */\n function MinimalECIInput(stringToEncode, priorityCharset, fnc1) {\n this.fnc1 = fnc1;\n var encoderSet = new ECIEncoderSet(stringToEncode, priorityCharset, fnc1);\n if (encoderSet.length() === 1) {\n // optimization for the case when all can be encoded without ECI in ISO-8859-1\n for (var i = 0; i < this.bytes.length; i++) {\n var c = stringToEncode.charAt(i).charCodeAt(0);\n this.bytes[i] = c === fnc1 ? 1000 : c;\n }\n }\n else {\n this.bytes = this.encodeMinimally(stringToEncode, encoderSet, fnc1);\n }\n }\n MinimalECIInput.prototype.getFNC1Character = function () {\n return this.fnc1;\n };\n /**\n * Returns the length of this input. The length is the number\n * of {@code byte}s, FNC1 characters or ECIs in the sequence.\n *\n * @return the number of {@code char}s in this sequence\n */\n MinimalECIInput.prototype.length = function () {\n return this.bytes.length;\n };\n MinimalECIInput.prototype.haveNCharacters = function (index, n) {\n if (index + n - 1 >= this.bytes.length) {\n return false;\n }\n for (var i = 0; i < n; i++) {\n if (this.isECI(index + i)) {\n return false;\n }\n }\n return true;\n };\n /**\n * Returns the {@code byte} value at the specified index. An index ranges from zero\n * to {@code length() - 1}. The first {@code byte} value of the sequence is at\n * index zero, the next at index one, and so on, as for array\n * indexing.\n *\n * @param index the index of the {@code byte} value to be returned\n *\n * @return the specified {@code byte} value as character or the FNC1 character\n *\n * @throws IndexOutOfBoundsException\n * if the {@code index} argument is negative or not less than\n * {@code length()}\n * @throws IllegalArgumentException\n * if the value at the {@code index} argument is an ECI (@see #isECI)\n */\n MinimalECIInput.prototype.charAt = function (index) {\n if (index < 0 || index >= this.length()) {\n throw new Error('' + index);\n }\n if (this.isECI(index)) {\n throw new Error('value at ' + index + ' is not a character but an ECI');\n }\n return this.isFNC1(index) ? this.fnc1 : this.bytes[index];\n };\n /**\n * Returns a {@code CharSequence} that is a subsequence of this sequence.\n * The subsequence starts with the {@code char} value at the specified index and\n * ends with the {@code char} value at index {@code end - 1}. The length\n * (in {@code char}s) of the\n * returned sequence is {@code end - start}, so if {@code start == end}\n * then an empty sequence is returned.\n *\n * @param start the start index, inclusive\n * @param end the end index, exclusive\n *\n * @return the specified subsequence\n *\n * @throws IndexOutOfBoundsException\n * if {@code start} or {@code end} are negative,\n * if {@code end} is greater than {@code length()},\n * or if {@code start} is greater than {@code end}\n * @throws IllegalArgumentException\n * if a value in the range {@code start}-{@code end} is an ECI (@see #isECI)\n */\n MinimalECIInput.prototype.subSequence = function (start, end) {\n if (start < 0 || start > end || end > this.length()) {\n throw new Error('' + start);\n }\n var result = new StringBuilder();\n for (var i = start; i < end; i++) {\n if (this.isECI(i)) {\n throw new Error('value at ' + i + ' is not a character but an ECI');\n }\n result.append(this.charAt(i));\n }\n return result.toString();\n };\n /**\n * Determines if a value is an ECI\n *\n * @param index the index of the value\n *\n * @return true if the value at position {@code index} is an ECI\n *\n * @throws IndexOutOfBoundsException\n * if the {@code index} argument is negative or not less than\n * {@code length()}\n */\n MinimalECIInput.prototype.isECI = function (index) {\n if (index < 0 || index >= this.length()) {\n throw new Error('' + index);\n }\n return this.bytes[index] > 255 && this.bytes[index] <= 999;\n };\n /**\n * Determines if a value is the FNC1 character\n *\n * @param index the index of the value\n *\n * @return true if the value at position {@code index} is the FNC1 character\n *\n * @throws IndexOutOfBoundsException\n * if the {@code index} argument is negative or not less than\n * {@code length()}\n */\n MinimalECIInput.prototype.isFNC1 = function (index) {\n if (index < 0 || index >= this.length()) {\n throw new Error('' + index);\n }\n return this.bytes[index] === 1000;\n };\n /**\n * Returns the {@code int} ECI value at the specified index. An index ranges from zero\n * to {@code length() - 1}. The first {@code byte} value of the sequence is at\n * index zero, the next at index one, and so on, as for array\n * indexing.\n *\n * @param index the index of the {@code int} value to be returned\n *\n * @return the specified {@code int} ECI value.\n * The ECI specified the encoding of all bytes with a higher index until the\n * next ECI or until the end of the input if no other ECI follows.\n *\n * @throws IndexOutOfBoundsException\n * if the {@code index} argument is negative or not less than\n * {@code length()}\n * @throws IllegalArgumentException\n * if the value at the {@code index} argument is not an ECI (@see #isECI)\n */\n MinimalECIInput.prototype.getECIValue = function (index) {\n if (index < 0 || index >= this.length()) {\n throw new Error('' + index);\n }\n if (!this.isECI(index)) {\n throw new Error('value at ' + index + ' is not an ECI but a character');\n }\n return this.bytes[index] - 256;\n };\n MinimalECIInput.prototype.addEdge = function (edges, to, edge) {\n if (edges[to][edge.encoderIndex] == null ||\n edges[to][edge.encoderIndex].cachedTotalSize > edge.cachedTotalSize) {\n edges[to][edge.encoderIndex] = edge;\n }\n };\n MinimalECIInput.prototype.addEdges = function (stringToEncode, encoderSet, edges, from, previous, fnc1) {\n var ch = stringToEncode.charAt(from).charCodeAt(0);\n var start = 0;\n var end = encoderSet.length();\n if (encoderSet.getPriorityEncoderIndex() >= 0 &&\n (ch === fnc1 ||\n encoderSet.canEncode(ch, encoderSet.getPriorityEncoderIndex()))) {\n start = encoderSet.getPriorityEncoderIndex();\n end = start + 1;\n }\n for (var i = start; i < end; i++) {\n if (ch === fnc1 || encoderSet.canEncode(ch, i)) {\n this.addEdge(edges, from + 1, new InputEdge(ch, encoderSet, i, previous, fnc1));\n }\n }\n };\n MinimalECIInput.prototype.encodeMinimally = function (stringToEncode, encoderSet, fnc1) {\n var inputLength = stringToEncode.length;\n // Array that represents vertices. There is a vertex for every character and encoding.\n var edges = new InputEdge[inputLength + 1][encoderSet.length()]();\n this.addEdges(stringToEncode, encoderSet, edges, 0, null, fnc1);\n for (var i = 1; i <= inputLength; i++) {\n for (var j = 0; j < encoderSet.length(); j++) {\n if (edges[i][j] != null && i < inputLength) {\n this.addEdges(stringToEncode, encoderSet, edges, i, edges[i][j], fnc1);\n }\n }\n // optimize memory by removing edges that have been passed.\n for (var j = 0; j < encoderSet.length(); j++) {\n edges[i - 1][j] = null;\n }\n }\n var minimalJ = -1;\n var minimalSize = Integer.MAX_VALUE;\n for (var j = 0; j < encoderSet.length(); j++) {\n if (edges[inputLength][j] != null) {\n var edge = edges[inputLength][j];\n if (edge.cachedTotalSize < minimalSize) {\n minimalSize = edge.cachedTotalSize;\n minimalJ = j;\n }\n }\n }\n if (minimalJ < 0) {\n throw new Error('Failed to encode \"' + stringToEncode + '\"');\n }\n var intsAL = [];\n var current = edges[inputLength][minimalJ];\n while (current != null) {\n if (current.isFNC1()) {\n intsAL.unshift(1000);\n }\n else {\n var bytes = encoderSet.encode(current.c, current.encoderIndex);\n for (var i = bytes.length - 1; i >= 0; i--) {\n intsAL.unshift(bytes[i] & 0xff);\n }\n }\n var previousEncoderIndex = current.previous === null ? 0 : current.previous.encoderIndex;\n if (previousEncoderIndex !== current.encoderIndex) {\n intsAL.unshift(256 + encoderSet.getECIValue(current.encoderIndex));\n }\n current = current.previous;\n }\n var ints = [];\n for (var i = 0; i < ints.length; i++) {\n ints[i] = intsAL[i];\n }\n return ints;\n };\n return MinimalECIInput;\n}());\nexport { MinimalECIInput };\nvar InputEdge = /** @class */ (function () {\n function InputEdge(c, encoderSet, encoderIndex, previous, fnc1) {\n this.c = c;\n this.encoderSet = encoderSet;\n this.encoderIndex = encoderIndex;\n this.previous = previous;\n this.fnc1 = fnc1;\n this.c = c === fnc1 ? 1000 : c;\n var size = this.isFNC1() ? 1 : encoderSet.encode(c, encoderIndex).length;\n var previousEncoderIndex = previous === null ? 0 : previous.encoderIndex;\n if (previousEncoderIndex !== encoderIndex) {\n size += COST_PER_ECI;\n }\n if (previous != null) {\n size += previous.cachedTotalSize;\n }\n this.cachedTotalSize = size;\n }\n InputEdge.prototype.isFNC1 = function () {\n return this.c === 1000;\n };\n return InputEdge;\n}());\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.common {*/\n/**\n *This class implements a perspective transform in two dimensions. Given four source and four\n * destination points, it will compute the transformation implied between them. The code is based\n * directly upon section 3.4.2 of George Wolberg's \"Digital Image Warping\"; see pages 54-56.
\n *\n * @author Sean Owen\n */\nvar PerspectiveTransform = /** @class */ (function () {\n function PerspectiveTransform(a11 /*float*/, a21 /*float*/, a31 /*float*/, a12 /*float*/, a22 /*float*/, a32 /*float*/, a13 /*float*/, a23 /*float*/, a33 /*float*/) {\n this.a11 = a11;\n this.a21 = a21;\n this.a31 = a31;\n this.a12 = a12;\n this.a22 = a22;\n this.a32 = a32;\n this.a13 = a13;\n this.a23 = a23;\n this.a33 = a33;\n }\n PerspectiveTransform.quadrilateralToQuadrilateral = function (x0 /*float*/, y0 /*float*/, x1 /*float*/, y1 /*float*/, x2 /*float*/, y2 /*float*/, x3 /*float*/, y3 /*float*/, x0p /*float*/, y0p /*float*/, x1p /*float*/, y1p /*float*/, x2p /*float*/, y2p /*float*/, x3p /*float*/, y3p /*float*/) {\n var qToS = PerspectiveTransform.quadrilateralToSquare(x0, y0, x1, y1, x2, y2, x3, y3);\n var sToQ = PerspectiveTransform.squareToQuadrilateral(x0p, y0p, x1p, y1p, x2p, y2p, x3p, y3p);\n return sToQ.times(qToS);\n };\n PerspectiveTransform.prototype.transformPoints = function (points) {\n var max = points.length;\n var a11 = this.a11;\n var a12 = this.a12;\n var a13 = this.a13;\n var a21 = this.a21;\n var a22 = this.a22;\n var a23 = this.a23;\n var a31 = this.a31;\n var a32 = this.a32;\n var a33 = this.a33;\n for (var i = 0; i < max; i += 2) {\n var x = points[i];\n var y = points[i + 1];\n var denominator = a13 * x + a23 * y + a33;\n points[i] = (a11 * x + a21 * y + a31) / denominator;\n points[i + 1] = (a12 * x + a22 * y + a32) / denominator;\n }\n };\n PerspectiveTransform.prototype.transformPointsWithValues = function (xValues, yValues) {\n var a11 = this.a11;\n var a12 = this.a12;\n var a13 = this.a13;\n var a21 = this.a21;\n var a22 = this.a22;\n var a23 = this.a23;\n var a31 = this.a31;\n var a32 = this.a32;\n var a33 = this.a33;\n var n = xValues.length;\n for (var i = 0; i < n; i++) {\n var x = xValues[i];\n var y = yValues[i];\n var denominator = a13 * x + a23 * y + a33;\n xValues[i] = (a11 * x + a21 * y + a31) / denominator;\n yValues[i] = (a12 * x + a22 * y + a32) / denominator;\n }\n };\n PerspectiveTransform.squareToQuadrilateral = function (x0 /*float*/, y0 /*float*/, x1 /*float*/, y1 /*float*/, x2 /*float*/, y2 /*float*/, x3 /*float*/, y3 /*float*/) {\n var dx3 = x0 - x1 + x2 - x3;\n var dy3 = y0 - y1 + y2 - y3;\n if (dx3 === 0.0 && dy3 === 0.0) {\n // Affine\n return new PerspectiveTransform(x1 - x0, x2 - x1, x0, y1 - y0, y2 - y1, y0, 0.0, 0.0, 1.0);\n }\n else {\n var dx1 = x1 - x2;\n var dx2 = x3 - x2;\n var dy1 = y1 - y2;\n var dy2 = y3 - y2;\n var denominator = dx1 * dy2 - dx2 * dy1;\n var a13 = (dx3 * dy2 - dx2 * dy3) / denominator;\n var a23 = (dx1 * dy3 - dx3 * dy1) / denominator;\n return new PerspectiveTransform(x1 - x0 + a13 * x1, x3 - x0 + a23 * x3, x0, y1 - y0 + a13 * y1, y3 - y0 + a23 * y3, y0, a13, a23, 1.0);\n }\n };\n PerspectiveTransform.quadrilateralToSquare = function (x0 /*float*/, y0 /*float*/, x1 /*float*/, y1 /*float*/, x2 /*float*/, y2 /*float*/, x3 /*float*/, y3 /*float*/) {\n // Here, the adjoint serves as the inverse:\n return PerspectiveTransform.squareToQuadrilateral(x0, y0, x1, y1, x2, y2, x3, y3).buildAdjoint();\n };\n PerspectiveTransform.prototype.buildAdjoint = function () {\n // Adjoint is the transpose of the cofactor matrix:\n return new PerspectiveTransform(this.a22 * this.a33 - this.a23 * this.a32, this.a23 * this.a31 - this.a21 * this.a33, this.a21 * this.a32 - this.a22 * this.a31, this.a13 * this.a32 - this.a12 * this.a33, this.a11 * this.a33 - this.a13 * this.a31, this.a12 * this.a31 - this.a11 * this.a32, this.a12 * this.a23 - this.a13 * this.a22, this.a13 * this.a21 - this.a11 * this.a23, this.a11 * this.a22 - this.a12 * this.a21);\n };\n PerspectiveTransform.prototype.times = function (other) {\n return new PerspectiveTransform(this.a11 * other.a11 + this.a21 * other.a12 + this.a31 * other.a13, this.a11 * other.a21 + this.a21 * other.a22 + this.a31 * other.a23, this.a11 * other.a31 + this.a21 * other.a32 + this.a31 * other.a33, this.a12 * other.a11 + this.a22 * other.a12 + this.a32 * other.a13, this.a12 * other.a21 + this.a22 * other.a22 + this.a32 * other.a23, this.a12 * other.a31 + this.a22 * other.a32 + this.a32 * other.a33, this.a13 * other.a11 + this.a23 * other.a12 + this.a33 * other.a13, this.a13 * other.a21 + this.a23 * other.a22 + this.a33 * other.a23, this.a13 * other.a31 + this.a23 * other.a32 + this.a33 * other.a33);\n };\n return PerspectiveTransform;\n}());\nexport default PerspectiveTransform;\n","/*\n * Copyright (C) 2010 ZXing authors\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/*namespace com.google.zxing.common {*/\n/*import java.nio.charset.Charset;*/\n/*import java.util.Map;*/\nimport DecodeHintType from '../DecodeHintType';\nimport CharacterSetECI from './CharacterSetECI';\nimport StringEncoding from '../util/StringEncoding';\n/**\n * Common string-related functions.\n *\n * @author Sean Owen\n * @author Alex Dupre\n */\nvar StringUtils = /** @class */ (function () {\n function StringUtils() {\n }\n // SHIFT_JIS.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING) ||\n // EUC_JP.equalsIgnoreCase(PLATFORM_DEFAULT_ENCODING);\n StringUtils.castAsNonUtf8Char = function (code, encoding) {\n if (encoding === void 0) { encoding = null; }\n // ISO 8859-1 is the Java default as UTF-8 is JavaScripts\n // you can see this method as a Java version of String.fromCharCode\n var e = encoding ? encoding.getName() : this.ISO88591;\n // use passed format (fromCharCode will return UTF8 encoding)\n return StringEncoding.decode(new Uint8Array([code]), e);\n };\n /**\n * @param bytes bytes encoding a string, whose encoding should be guessed\n * @param hints decode hints if applicable\n * @return name of guessed encoding; at the moment will only guess one of:\n * {@link #SHIFT_JIS}, {@link #UTF8}, {@link #ISO88591}, or the platform\n * default encoding if none of these can possibly be correct\n */\n StringUtils.guessEncoding = function (bytes, hints) {\n if (hints !== null && hints !== undefined && undefined !== hints.get(DecodeHintType.CHARACTER_SET)) {\n return hints.get(DecodeHintType.CHARACTER_SET).toString();\n }\n // For now, merely tries to distinguish ISO-8859-1, UTF-8 and Shift_JIS,\n // which should be by far the most common encodings.\n var length = bytes.length;\n var canBeISO88591 = true;\n var canBeShiftJIS = true;\n var canBeUTF8 = true;\n var utf8BytesLeft = 0;\n // int utf8LowChars = 0\n var utf2BytesChars = 0;\n var utf3BytesChars = 0;\n var utf4BytesChars = 0;\n var sjisBytesLeft = 0;\n // int sjisLowChars = 0\n var sjisKatakanaChars = 0;\n // int sjisDoubleBytesChars = 0\n var sjisCurKatakanaWordLength = 0;\n var sjisCurDoubleBytesWordLength = 0;\n var sjisMaxKatakanaWordLength = 0;\n var sjisMaxDoubleBytesWordLength = 0;\n // int isoLowChars = 0\n // int isoHighChars = 0\n var isoHighOther = 0;\n var utf8bom = bytes.length > 3 &&\n bytes[0] === /*(byte) */ 0xEF &&\n bytes[1] === /*(byte) */ 0xBB &&\n bytes[2] === /*(byte) */ 0xBF;\n for (var i = 0; i < length && (canBeISO88591 || canBeShiftJIS || canBeUTF8); i++) {\n var value = bytes[i] & 0xFF;\n // UTF-8 stuff\n if (canBeUTF8) {\n if (utf8BytesLeft > 0) {\n if ((value & 0x80) === 0) {\n canBeUTF8 = false;\n }\n else {\n utf8BytesLeft--;\n }\n }\n else if ((value & 0x80) !== 0) {\n if ((value & 0x40) === 0) {\n canBeUTF8 = false;\n }\n else {\n utf8BytesLeft++;\n if ((value & 0x20) === 0) {\n utf2BytesChars++;\n }\n else {\n utf8BytesLeft++;\n if ((value & 0x10) === 0) {\n utf3BytesChars++;\n }\n else {\n utf8BytesLeft++;\n if ((value & 0x08) === 0) {\n utf4BytesChars++;\n }\n else {\n canBeUTF8 = false;\n }\n }\n }\n }\n } // else {\n // utf8LowChars++\n // }\n }\n // ISO-8859-1 stuff\n if (canBeISO88591) {\n if (value > 0x7F && value < 0xA0) {\n canBeISO88591 = false;\n }\n else if (value > 0x9F) {\n if (value < 0xC0 || value === 0xD7 || value === 0xF7) {\n isoHighOther++;\n } // else {\n // isoHighChars++\n // }\n } // else {\n // isoLowChars++\n // }\n }\n // Shift_JIS stuff\n if (canBeShiftJIS) {\n if (sjisBytesLeft > 0) {\n if (value < 0x40 || value === 0x7F || value > 0xFC) {\n canBeShiftJIS = false;\n }\n else {\n sjisBytesLeft--;\n }\n }\n else if (value === 0x80 || value === 0xA0 || value > 0xEF) {\n canBeShiftJIS = false;\n }\n else if (value > 0xA0 && value < 0xE0) {\n sjisKatakanaChars++;\n sjisCurDoubleBytesWordLength = 0;\n sjisCurKatakanaWordLength++;\n if (sjisCurKatakanaWordLength > sjisMaxKatakanaWordLength) {\n sjisMaxKatakanaWordLength = sjisCurKatakanaWordLength;\n }\n }\n else if (value > 0x7F) {\n sjisBytesLeft++;\n // sjisDoubleBytesChars++\n sjisCurKatakanaWordLength = 0;\n sjisCurDoubleBytesWordLength++;\n if (sjisCurDoubleBytesWordLength > sjisMaxDoubleBytesWordLength) {\n sjisMaxDoubleBytesWordLength = sjisCurDoubleBytesWordLength;\n }\n }\n else {\n // sjisLowChars++\n sjisCurKatakanaWordLength = 0;\n sjisCurDoubleBytesWordLength = 0;\n }\n }\n }\n if (canBeUTF8 && utf8BytesLeft > 0) {\n canBeUTF8 = false;\n }\n if (canBeShiftJIS && sjisBytesLeft > 0) {\n canBeShiftJIS = false;\n }\n // Easy -- if there is BOM or at least 1 valid not-single byte character (and no evidence it can't be UTF-8), done\n if (canBeUTF8 && (utf8bom || utf2BytesChars + utf3BytesChars + utf4BytesChars > 0)) {\n return StringUtils.UTF8;\n }\n // Easy -- if assuming Shift_JIS or at least 3 valid consecutive not-ascii characters (and no evidence it can't be), done\n if (canBeShiftJIS && (StringUtils.ASSUME_SHIFT_JIS || sjisMaxKatakanaWordLength >= 3 || sjisMaxDoubleBytesWordLength >= 3)) {\n return StringUtils.SHIFT_JIS;\n }\n // Distinguishing Shift_JIS and ISO-8859-1 can be a little tough for short words. The crude heuristic is:\n // - If we saw\n // - only two consecutive katakana chars in the whole text, or\n // - at least 10% of bytes that could be \"upper\" not-alphanumeric Latin1,\n // - then we conclude Shift_JIS, else ISO-8859-1\n if (canBeISO88591 && canBeShiftJIS) {\n return (sjisMaxKatakanaWordLength === 2 && sjisKatakanaChars === 2) || isoHighOther * 10 >= length\n ? StringUtils.SHIFT_JIS : StringUtils.ISO88591;\n }\n // Otherwise, try in order ISO-8859-1, Shift JIS, UTF-8 and fall back to default platform encoding\n if (canBeISO88591) {\n return StringUtils.ISO88591;\n }\n if (canBeShiftJIS) {\n return StringUtils.SHIFT_JIS;\n }\n if (canBeUTF8) {\n return StringUtils.UTF8;\n }\n // Otherwise, we take a wild guess with platform encoding\n return StringUtils.PLATFORM_DEFAULT_ENCODING;\n };\n /**\n *\n * @see https://stackoverflow.com/a/13439711/4367683\n *\n * @param append The new string to append.\n * @param args Argumets values to be formated.\n */\n StringUtils.format = function (append) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n var i = -1;\n function callback(exp, p0, p1, p2, p3, p4) {\n if (exp === '%%')\n return '%';\n if (args[++i] === undefined)\n return undefined;\n exp = p2 ? parseInt(p2.substr(1)) : undefined;\n var base = p3 ? parseInt(p3.substr(1)) : undefined;\n var val;\n switch (p4) {\n case 's':\n val = args[i];\n break;\n case 'c':\n val = args[i][0];\n break;\n case 'f':\n val = parseFloat(args[i]).toFixed(exp);\n break;\n case 'p':\n val = parseFloat(args[i]).toPrecision(exp);\n break;\n case 'e':\n val = parseFloat(args[i]).toExponential(exp);\n break;\n case 'x':\n val = parseInt(args[i]).toString(base ? base : 16);\n break;\n case 'd':\n val = parseFloat(parseInt(args[i], base ? base : 10).toPrecision(exp)).toFixed(0);\n break;\n }\n val = typeof val === 'object' ? JSON.stringify(val) : (+val).toString(base);\n var size = parseInt(p1); /* padding size */\n var ch = p1 && (p1[0] + '') === '0' ? '0' : ' '; /* isnull? */\n while (val.length < size)\n val = p0 !== undefined ? val + ch : ch + val; /* isminus? */\n return val;\n }\n var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;\n return append.replace(regex, callback);\n };\n /**\n *\n */\n StringUtils.getBytes = function (str, encoding) {\n return StringEncoding.encode(str, encoding);\n };\n /**\n * Returns the charcode at the specified index or at index zero.\n */\n StringUtils.getCharCode = function (str, index) {\n if (index === void 0) { index = 0; }\n return str.charCodeAt(index);\n };\n /**\n * Returns char for given charcode\n */\n StringUtils.getCharAt = function (charCode) {\n return String.fromCharCode(charCode);\n };\n StringUtils.SHIFT_JIS = CharacterSetECI.SJIS.getName(); // \"SJIS\"\n StringUtils.GB2312 = 'GB2312';\n StringUtils.ISO88591 = CharacterSetECI.ISO8859_1.getName(); // \"ISO8859_1\"\n StringUtils.EUC_JP = 'EUC_JP';\n StringUtils.UTF8 = CharacterSetECI.UTF8.getName(); // \"UTF8\"\n StringUtils.PLATFORM_DEFAULT_ENCODING = StringUtils.UTF8; // \"UTF8\"//Charset.defaultCharset().name()\n StringUtils.ASSUME_SHIFT_JIS = false;\n return StringUtils;\n}());\nexport default StringUtils;\n","/*\n * Copyright 2012 ZXing authors\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/*namespace com.google.zxing.common.detector {*/\n/**\n * General math-related and numeric utility functions.\n */\nvar MathUtils = /** @class */ (function () {\n function MathUtils() {\n }\n /**\n * Ends up being a bit faster than {@link Math#round(float)}. This merely rounds its\n * argument to the nearest int, where x.5 rounds up to x+1. Semantics of this shortcut\n * differ slightly from {@link Math#round(float)} in that half rounds down for negative\n * values. -2.5 rounds to -3, not -2. For purposes here it makes no difference.\n *\n * @param d real value to round\n * @return nearest {@code int}\n */\n MathUtils.round = function (d /*float*/) {\n if (isNaN(d))\n return 0;\n if (d <= Number.MIN_SAFE_INTEGER)\n return Number.MIN_SAFE_INTEGER;\n if (d >= Number.MAX_SAFE_INTEGER)\n return Number.MAX_SAFE_INTEGER;\n return /*(int) */ (d + (d < 0.0 ? -0.5 : 0.5)) | 0;\n };\n // TYPESCRIPTPORT: maybe remove round method and call directly Math.round, it looks like it doesn't make sense for js\n /**\n * @param aX point A x coordinate\n * @param aY point A y coordinate\n * @param bX point B x coordinate\n * @param bY point B y coordinate\n * @return Euclidean distance between points A and B\n */\n MathUtils.distance = function (aX /*float|int*/, aY /*float|int*/, bX /*float|int*/, bY /*float|int*/) {\n var xDiff = aX - bX;\n var yDiff = aY - bY;\n return /*(float) */ Math.sqrt(xDiff * xDiff + yDiff * yDiff);\n };\n /**\n * @param aX point A x coordinate\n * @param aY point A y coordinate\n * @param bX point B x coordinate\n * @param bY point B y coordinate\n * @return Euclidean distance between points A and B\n */\n // public static distance(aX: number /*int*/, aY: number /*int*/, bX: number /*int*/, bY: number /*int*/): float {\n // const xDiff = aX - bX\n // const yDiff = aY - bY\n // return (float) Math.sqrt(xDiff * xDiff + yDiff * yDiff);\n // }\n /**\n * @param array values to sum\n * @return sum of values in array\n */\n MathUtils.sum = function (array) {\n var count = 0;\n for (var i = 0, length_1 = array.length; i !== length_1; i++) {\n var a = array[i];\n count += a;\n }\n return count;\n };\n return MathUtils;\n}());\nexport default MathUtils;\n","/*\n * Copyright 2010 ZXing authors\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/*namespace com.google.zxing.common.detector {*/\nimport ResultPoint from '../../ResultPoint';\nimport MathUtils from './MathUtils';\nimport NotFoundException from '../../NotFoundException';\n/**\n *\n * Detects a candidate barcode-like rectangular region within an image. It\n * starts around the center of the image, increases the size of the candidate\n * region until it finds a white rectangular region. By keeping track of the\n * last black points it encountered, it determines the corners of the barcode.\n *
\n *\n * @author David Olivier\n */\nvar WhiteRectangleDetector = /** @class */ (function () {\n // public constructor(private image: BitMatrix) /*throws NotFoundException*/ {\n // this(image, INIT_SIZE, image.getWidth() / 2, image.getHeight() / 2)\n // }\n /**\n * @param image barcode image to find a rectangle in\n * @param initSize initial size of search area around center\n * @param x x position of search center\n * @param y y position of search center\n * @throws NotFoundException if image is too small to accommodate {@code initSize}\n */\n function WhiteRectangleDetector(image, initSize /*int*/, x /*int*/, y /*int*/) {\n this.image = image;\n this.height = image.getHeight();\n this.width = image.getWidth();\n if (undefined === initSize || null === initSize) {\n initSize = WhiteRectangleDetector.INIT_SIZE;\n }\n if (undefined === x || null === x) {\n x = image.getWidth() / 2 | 0;\n }\n if (undefined === y || null === y) {\n y = image.getHeight() / 2 | 0;\n }\n var halfsize = initSize / 2 | 0;\n this.leftInit = x - halfsize;\n this.rightInit = x + halfsize;\n this.upInit = y - halfsize;\n this.downInit = y + halfsize;\n if (this.upInit < 0 || this.leftInit < 0 || this.downInit >= this.height || this.rightInit >= this.width) {\n throw new NotFoundException();\n }\n }\n /**\n *\n * Detects a candidate barcode-like rectangular region within an image. It\n * starts around the center of the image, increases the size of the candidate\n * region until it finds a white rectangular region.\n *
\n *\n * @return {@link ResultPoint}[] describing the corners of the rectangular\n * region. The first and last points are opposed on the diagonal, as\n * are the second and third. The first point will be the topmost\n * point and the last, the bottommost. The second point will be\n * leftmost and the third, the rightmost\n * @throws NotFoundException if no Data Matrix Code can be found\n */\n WhiteRectangleDetector.prototype.detect = function () {\n var left = this.leftInit;\n var right = this.rightInit;\n var up = this.upInit;\n var down = this.downInit;\n var sizeExceeded = false;\n var aBlackPointFoundOnBorder = true;\n var atLeastOneBlackPointFoundOnBorder = false;\n var atLeastOneBlackPointFoundOnRight = false;\n var atLeastOneBlackPointFoundOnBottom = false;\n var atLeastOneBlackPointFoundOnLeft = false;\n var atLeastOneBlackPointFoundOnTop = false;\n var width = this.width;\n var height = this.height;\n while (aBlackPointFoundOnBorder) {\n aBlackPointFoundOnBorder = false;\n // .....\n // . |\n // .....\n var rightBorderNotWhite = true;\n while ((rightBorderNotWhite || !atLeastOneBlackPointFoundOnRight) && right < width) {\n rightBorderNotWhite = this.containsBlackPoint(up, down, right, false);\n if (rightBorderNotWhite) {\n right++;\n aBlackPointFoundOnBorder = true;\n atLeastOneBlackPointFoundOnRight = true;\n }\n else if (!atLeastOneBlackPointFoundOnRight) {\n right++;\n }\n }\n if (right >= width) {\n sizeExceeded = true;\n break;\n }\n // .....\n // . .\n // .___.\n var bottomBorderNotWhite = true;\n while ((bottomBorderNotWhite || !atLeastOneBlackPointFoundOnBottom) && down < height) {\n bottomBorderNotWhite = this.containsBlackPoint(left, right, down, true);\n if (bottomBorderNotWhite) {\n down++;\n aBlackPointFoundOnBorder = true;\n atLeastOneBlackPointFoundOnBottom = true;\n }\n else if (!atLeastOneBlackPointFoundOnBottom) {\n down++;\n }\n }\n if (down >= height) {\n sizeExceeded = true;\n break;\n }\n // .....\n // | .\n // .....\n var leftBorderNotWhite = true;\n while ((leftBorderNotWhite || !atLeastOneBlackPointFoundOnLeft) && left >= 0) {\n leftBorderNotWhite = this.containsBlackPoint(up, down, left, false);\n if (leftBorderNotWhite) {\n left--;\n aBlackPointFoundOnBorder = true;\n atLeastOneBlackPointFoundOnLeft = true;\n }\n else if (!atLeastOneBlackPointFoundOnLeft) {\n left--;\n }\n }\n if (left < 0) {\n sizeExceeded = true;\n break;\n }\n // .___.\n // . .\n // .....\n var topBorderNotWhite = true;\n while ((topBorderNotWhite || !atLeastOneBlackPointFoundOnTop) && up >= 0) {\n topBorderNotWhite = this.containsBlackPoint(left, right, up, true);\n if (topBorderNotWhite) {\n up--;\n aBlackPointFoundOnBorder = true;\n atLeastOneBlackPointFoundOnTop = true;\n }\n else if (!atLeastOneBlackPointFoundOnTop) {\n up--;\n }\n }\n if (up < 0) {\n sizeExceeded = true;\n break;\n }\n if (aBlackPointFoundOnBorder) {\n atLeastOneBlackPointFoundOnBorder = true;\n }\n }\n if (!sizeExceeded && atLeastOneBlackPointFoundOnBorder) {\n var maxSize = right - left;\n var z = null;\n for (var i = 1; z === null && i < maxSize; i++) {\n z = this.getBlackPointOnSegment(left, down - i, left + i, down);\n }\n if (z == null) {\n throw new NotFoundException();\n }\n var t = null;\n // go down right\n for (var i = 1; t === null && i < maxSize; i++) {\n t = this.getBlackPointOnSegment(left, up + i, left + i, up);\n }\n if (t == null) {\n throw new NotFoundException();\n }\n var x = null;\n // go down left\n for (var i = 1; x === null && i < maxSize; i++) {\n x = this.getBlackPointOnSegment(right, up + i, right - i, up);\n }\n if (x == null) {\n throw new NotFoundException();\n }\n var y = null;\n // go up left\n for (var i = 1; y === null && i < maxSize; i++) {\n y = this.getBlackPointOnSegment(right, down - i, right - i, down);\n }\n if (y == null) {\n throw new NotFoundException();\n }\n return this.centerEdges(y, z, x, t);\n }\n else {\n throw new NotFoundException();\n }\n };\n WhiteRectangleDetector.prototype.getBlackPointOnSegment = function (aX /*float*/, aY /*float*/, bX /*float*/, bY /*float*/) {\n var dist = MathUtils.round(MathUtils.distance(aX, aY, bX, bY));\n var xStep = (bX - aX) / dist;\n var yStep = (bY - aY) / dist;\n var image = this.image;\n for (var i = 0; i < dist; i++) {\n var x = MathUtils.round(aX + i * xStep);\n var y = MathUtils.round(aY + i * yStep);\n if (image.get(x, y)) {\n return new ResultPoint(x, y);\n }\n }\n return null;\n };\n /**\n * recenters the points of a constant distance towards the center\n *\n * @param y bottom most point\n * @param z left most point\n * @param x right most point\n * @param t top most point\n * @return {@link ResultPoint}[] describing the corners of the rectangular\n * region. The first and last points are opposed on the diagonal, as\n * are the second and third. The first point will be the topmost\n * point and the last, the bottommost. The second point will be\n * leftmost and the third, the rightmost\n */\n WhiteRectangleDetector.prototype.centerEdges = function (y, z, x, t) {\n //\n // t t\n // z x\n // x OR z\n // y y\n //\n var yi = y.getX();\n var yj = y.getY();\n var zi = z.getX();\n var zj = z.getY();\n var xi = x.getX();\n var xj = x.getY();\n var ti = t.getX();\n var tj = t.getY();\n var CORR = WhiteRectangleDetector.CORR;\n if (yi < this.width / 2.0) {\n return [\n new ResultPoint(ti - CORR, tj + CORR),\n new ResultPoint(zi + CORR, zj + CORR),\n new ResultPoint(xi - CORR, xj - CORR),\n new ResultPoint(yi + CORR, yj - CORR)\n ];\n }\n else {\n return [\n new ResultPoint(ti + CORR, tj + CORR),\n new ResultPoint(zi + CORR, zj - CORR),\n new ResultPoint(xi - CORR, xj + CORR),\n new ResultPoint(yi - CORR, yj - CORR)\n ];\n }\n };\n /**\n * Determines whether a segment contains a black point\n *\n * @param a min value of the scanned coordinate\n * @param b max value of the scanned coordinate\n * @param fixed value of fixed coordinate\n * @param horizontal set to true if scan must be horizontal, false if vertical\n * @return true if a black point has been found, else false.\n */\n WhiteRectangleDetector.prototype.containsBlackPoint = function (a /*int*/, b /*int*/, fixed /*int*/, horizontal) {\n var image = this.image;\n if (horizontal) {\n for (var x = a; x <= b; x++) {\n if (image.get(x, fixed)) {\n return true;\n }\n }\n }\n else {\n for (var y = a; y <= b; y++) {\n if (image.get(fixed, y)) {\n return true;\n }\n }\n }\n return false;\n };\n WhiteRectangleDetector.INIT_SIZE = 10;\n WhiteRectangleDetector.CORR = 1;\n return WhiteRectangleDetector;\n}());\nexport default WhiteRectangleDetector;\n","/*\n * Copyright 2007 ZXing authors\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 */\nimport IllegalArgumentException from '../../IllegalArgumentException';\n/**\n *This class contains utility methods for performing mathematical operations over\n * the Galois Fields. Operations use a given primitive polynomial in calculations.
\n *\n *Throughout this package, elements of the GF are represented as an {@code int}\n * for convenience and speed (but at the cost of memory).\n *
\n *\n * @author Sean Owen\n * @author David Olivier\n */\nvar AbstractGenericGF = /** @class */ (function () {\n function AbstractGenericGF() {\n }\n /**\n * @return 2 to the power of a in GF(size)\n */\n AbstractGenericGF.prototype.exp = function (a) {\n return this.expTable[a];\n };\n /**\n * @return base 2 log of a in GF(size)\n */\n AbstractGenericGF.prototype.log = function (a /*int*/) {\n if (a === 0) {\n throw new IllegalArgumentException();\n }\n return this.logTable[a];\n };\n /**\n * Implements both addition and subtraction -- they are the same in GF(size).\n *\n * @return sum/difference of a and b\n */\n AbstractGenericGF.addOrSubtract = function (a /*int*/, b /*int*/) {\n return a ^ b;\n };\n return AbstractGenericGF;\n}());\nexport default AbstractGenericGF;\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/*namespace com.google.zxing.common.reedsolomon {*/\nimport GenericGFPoly from './GenericGFPoly';\nimport AbstractGenericGF from './AbstractGenericGF';\nimport Integer from '../../util/Integer';\nimport IllegalArgumentException from '../../IllegalArgumentException';\nimport ArithmeticException from '../../ArithmeticException';\n/**\n *This class contains utility methods for performing mathematical operations over\n * the Galois Fields. Operations use a given primitive polynomial in calculations.
\n *\n *Throughout this package, elements of the GF are represented as an {@code int}\n * for convenience and speed (but at the cost of memory).\n *
\n *\n * @author Sean Owen\n * @author David Olivier\n */\nvar GenericGF = /** @class */ (function (_super) {\n __extends(GenericGF, _super);\n /**\n * Create a representation of GF(size) using the given primitive polynomial.\n *\n * @param primitive irreducible polynomial whose coefficients are represented by\n * the bits of an int, where the least-significant bit represents the constant\n * coefficient\n * @param size the size of the field\n * @param b the factor b in the generator polynomial can be 0- or 1-based\n * (g(x) = (x+a^b)(x+a^(b+1))...(x+a^(b+2t-1))).\n * In most cases it should be 1, but for QR code it is 0.\n */\n function GenericGF(primitive /*int*/, size /*int*/, generatorBase /*int*/) {\n var _this = _super.call(this) || this;\n _this.primitive = primitive;\n _this.size = size;\n _this.generatorBase = generatorBase;\n var expTable = new Int32Array(size);\n var x = 1;\n for (var i = 0; i < size; i++) {\n expTable[i] = x;\n x *= 2; // we're assuming the generator alpha is 2\n if (x >= size) {\n x ^= primitive;\n x &= size - 1;\n }\n }\n _this.expTable = expTable;\n var logTable = new Int32Array(size);\n for (var i = 0; i < size - 1; i++) {\n logTable[expTable[i]] = i;\n }\n _this.logTable = logTable;\n // logTable[0] == 0 but this should never be used\n _this.zero = new GenericGFPoly(_this, Int32Array.from([0]));\n _this.one = new GenericGFPoly(_this, Int32Array.from([1]));\n return _this;\n }\n GenericGF.prototype.getZero = function () {\n return this.zero;\n };\n GenericGF.prototype.getOne = function () {\n return this.one;\n };\n /**\n * @return the monomial representing coefficient * x^degree\n */\n GenericGF.prototype.buildMonomial = function (degree /*int*/, coefficient /*int*/) {\n if (degree < 0) {\n throw new IllegalArgumentException();\n }\n if (coefficient === 0) {\n return this.zero;\n }\n var coefficients = new Int32Array(degree + 1);\n coefficients[0] = coefficient;\n return new GenericGFPoly(this, coefficients);\n };\n /**\n * @return multiplicative inverse of a\n */\n GenericGF.prototype.inverse = function (a /*int*/) {\n if (a === 0) {\n throw new ArithmeticException();\n }\n return this.expTable[this.size - this.logTable[a] - 1];\n };\n /**\n * @return product of a and b in GF(size)\n */\n GenericGF.prototype.multiply = function (a /*int*/, b /*int*/) {\n if (a === 0 || b === 0) {\n return 0;\n }\n return this.expTable[(this.logTable[a] + this.logTable[b]) % (this.size - 1)];\n };\n GenericGF.prototype.getSize = function () {\n return this.size;\n };\n GenericGF.prototype.getGeneratorBase = function () {\n return this.generatorBase;\n };\n /*@Override*/\n GenericGF.prototype.toString = function () {\n return ('GF(0x' + Integer.toHexString(this.primitive) + ',' + this.size + ')');\n };\n GenericGF.prototype.equals = function (o) {\n return o === this;\n };\n GenericGF.AZTEC_DATA_12 = new GenericGF(0x1069, 4096, 1); // x^12 + x^6 + x^5 + x^3 + 1\n GenericGF.AZTEC_DATA_10 = new GenericGF(0x409, 1024, 1); // x^10 + x^3 + 1\n GenericGF.AZTEC_DATA_6 = new GenericGF(0x43, 64, 1); // x^6 + x + 1\n GenericGF.AZTEC_PARAM = new GenericGF(0x13, 16, 1); // x^4 + x + 1\n GenericGF.QR_CODE_FIELD_256 = new GenericGF(0x011d, 256, 0); // x^8 + x^4 + x^3 + x^2 + 1\n GenericGF.DATA_MATRIX_FIELD_256 = new GenericGF(0x012d, 256, 1); // x^8 + x^5 + x^3 + x^2 + 1\n GenericGF.AZTEC_DATA_8 = GenericGF.DATA_MATRIX_FIELD_256;\n GenericGF.MAXICODE_FIELD_64 = GenericGF.AZTEC_DATA_6;\n return GenericGF;\n}(AbstractGenericGF));\nexport default GenericGF;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.common.reedsolomon {*/\nimport AbstractGenericGF from './AbstractGenericGF';\nimport System from '../../util/System';\nimport IllegalArgumentException from '../../IllegalArgumentException';\n/**\n *Represents a polynomial whose coefficients are elements of a GF.\n * Instances of this class are immutable.
\n *\n *Much credit is due to William Rucklidge since portions of this code are an indirect\n * port of his C++ Reed-Solomon implementation.
\n *\n * @author Sean Owen\n */\nvar GenericGFPoly = /** @class */ (function () {\n /**\n * @param field the {@link GenericGF} instance representing the field to use\n * to perform computations\n * @param coefficients coefficients as ints representing elements of GF(size), arranged\n * from most significant (highest-power term) coefficient to least significant\n * @throws IllegalArgumentException if argument is null or empty,\n * or if leading coefficient is 0 and this is not a\n * constant polynomial (that is, it is not the monomial \"0\")\n */\n function GenericGFPoly(field, coefficients) {\n if (coefficients.length === 0) {\n throw new IllegalArgumentException();\n }\n this.field = field;\n var coefficientsLength = coefficients.length;\n if (coefficientsLength > 1 && coefficients[0] === 0) {\n // Leading term must be non-zero for anything except the constant polynomial \"0\"\n var firstNonZero = 1;\n while (firstNonZero < coefficientsLength && coefficients[firstNonZero] === 0) {\n firstNonZero++;\n }\n if (firstNonZero === coefficientsLength) {\n this.coefficients = Int32Array.from([0]);\n }\n else {\n this.coefficients = new Int32Array(coefficientsLength - firstNonZero);\n System.arraycopy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length);\n }\n }\n else {\n this.coefficients = coefficients;\n }\n }\n GenericGFPoly.prototype.getCoefficients = function () {\n return this.coefficients;\n };\n /**\n * @return degree of this polynomial\n */\n GenericGFPoly.prototype.getDegree = function () {\n return this.coefficients.length - 1;\n };\n /**\n * @return true iff this polynomial is the monomial \"0\"\n */\n GenericGFPoly.prototype.isZero = function () {\n return this.coefficients[0] === 0;\n };\n /**\n * @return coefficient of x^degree term in this polynomial\n */\n GenericGFPoly.prototype.getCoefficient = function (degree /*int*/) {\n return this.coefficients[this.coefficients.length - 1 - degree];\n };\n /**\n * @return evaluation of this polynomial at a given point\n */\n GenericGFPoly.prototype.evaluateAt = function (a /*int*/) {\n if (a === 0) {\n // Just return the x^0 coefficient\n return this.getCoefficient(0);\n }\n var coefficients = this.coefficients;\n var result;\n if (a === 1) {\n // Just the sum of the coefficients\n result = 0;\n for (var i = 0, length_1 = coefficients.length; i !== length_1; i++) {\n var coefficient = coefficients[i];\n result = AbstractGenericGF.addOrSubtract(result, coefficient);\n }\n return result;\n }\n result = coefficients[0];\n var size = coefficients.length;\n var field = this.field;\n for (var i = 1; i < size; i++) {\n result = AbstractGenericGF.addOrSubtract(field.multiply(a, result), coefficients[i]);\n }\n return result;\n };\n GenericGFPoly.prototype.addOrSubtract = function (other) {\n if (!this.field.equals(other.field)) {\n throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');\n }\n if (this.isZero()) {\n return other;\n }\n if (other.isZero()) {\n return this;\n }\n var smallerCoefficients = this.coefficients;\n var largerCoefficients = other.coefficients;\n if (smallerCoefficients.length > largerCoefficients.length) {\n var temp = smallerCoefficients;\n smallerCoefficients = largerCoefficients;\n largerCoefficients = temp;\n }\n var sumDiff = new Int32Array(largerCoefficients.length);\n var lengthDiff = largerCoefficients.length - smallerCoefficients.length;\n // Copy high-order terms only found in higher-degree polynomial's coefficients\n System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff);\n for (var i = lengthDiff; i < largerCoefficients.length; i++) {\n sumDiff[i] = AbstractGenericGF.addOrSubtract(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);\n }\n return new GenericGFPoly(this.field, sumDiff);\n };\n GenericGFPoly.prototype.multiply = function (other) {\n if (!this.field.equals(other.field)) {\n throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');\n }\n if (this.isZero() || other.isZero()) {\n return this.field.getZero();\n }\n var aCoefficients = this.coefficients;\n var aLength = aCoefficients.length;\n var bCoefficients = other.coefficients;\n var bLength = bCoefficients.length;\n var product = new Int32Array(aLength + bLength - 1);\n var field = this.field;\n for (var i = 0; i < aLength; i++) {\n var aCoeff = aCoefficients[i];\n for (var j = 0; j < bLength; j++) {\n product[i + j] = AbstractGenericGF.addOrSubtract(product[i + j], field.multiply(aCoeff, bCoefficients[j]));\n }\n }\n return new GenericGFPoly(field, product);\n };\n GenericGFPoly.prototype.multiplyScalar = function (scalar /*int*/) {\n if (scalar === 0) {\n return this.field.getZero();\n }\n if (scalar === 1) {\n return this;\n }\n var size = this.coefficients.length;\n var field = this.field;\n var product = new Int32Array(size);\n var coefficients = this.coefficients;\n for (var i = 0; i < size; i++) {\n product[i] = field.multiply(coefficients[i], scalar);\n }\n return new GenericGFPoly(field, product);\n };\n GenericGFPoly.prototype.multiplyByMonomial = function (degree /*int*/, coefficient /*int*/) {\n if (degree < 0) {\n throw new IllegalArgumentException();\n }\n if (coefficient === 0) {\n return this.field.getZero();\n }\n var coefficients = this.coefficients;\n var size = coefficients.length;\n var product = new Int32Array(size + degree);\n var field = this.field;\n for (var i = 0; i < size; i++) {\n product[i] = field.multiply(coefficients[i], coefficient);\n }\n return new GenericGFPoly(field, product);\n };\n GenericGFPoly.prototype.divide = function (other) {\n if (!this.field.equals(other.field)) {\n throw new IllegalArgumentException('GenericGFPolys do not have same GenericGF field');\n }\n if (other.isZero()) {\n throw new IllegalArgumentException('Divide by 0');\n }\n var field = this.field;\n var quotient = field.getZero();\n var remainder = this;\n var denominatorLeadingTerm = other.getCoefficient(other.getDegree());\n var inverseDenominatorLeadingTerm = field.inverse(denominatorLeadingTerm);\n while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) {\n var degreeDifference = remainder.getDegree() - other.getDegree();\n var scale = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm);\n var term = other.multiplyByMonomial(degreeDifference, scale);\n var iterationQuotient = field.buildMonomial(degreeDifference, scale);\n quotient = quotient.addOrSubtract(iterationQuotient);\n remainder = remainder.addOrSubtract(term);\n }\n return [quotient, remainder];\n };\n /*@Override*/\n GenericGFPoly.prototype.toString = function () {\n var result = '';\n for (var degree = this.getDegree(); degree >= 0; degree--) {\n var coefficient = this.getCoefficient(degree);\n if (coefficient !== 0) {\n if (coefficient < 0) {\n result += ' - ';\n coefficient = -coefficient;\n }\n else {\n if (result.length > 0) {\n result += ' + ';\n }\n }\n if (degree === 0 || coefficient !== 1) {\n var alphaPower = this.field.log(coefficient);\n if (alphaPower === 0) {\n result += '1';\n }\n else if (alphaPower === 1) {\n result += 'a';\n }\n else {\n result += 'a^';\n result += alphaPower;\n }\n }\n if (degree !== 0) {\n if (degree === 1) {\n result += 'x';\n }\n else {\n result += 'x^';\n result += degree;\n }\n }\n }\n }\n return result;\n };\n return GenericGFPoly;\n}());\nexport default GenericGFPoly;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.common.reedsolomon {*/\nimport GenericGF from './GenericGF';\nimport GenericGFPoly from './GenericGFPoly';\nimport ReedSolomonException from '../../ReedSolomonException';\nimport IllegalStateException from '../../IllegalStateException';\n/**\n *Implements Reed-Solomon decoding, as the name implies.
\n *\n *The algorithm will not be explained here, but the following references were helpful\n * in creating this implementation:
\n *\n *Much credit is due to William Rucklidge since portions of this code are an indirect\n * port of his C++ Reed-Solomon implementation.
\n *\n * @author Sean Owen\n * @author William Rucklidge\n * @author sanfordsquires\n */\nvar ReedSolomonDecoder = /** @class */ (function () {\n function ReedSolomonDecoder(field) {\n this.field = field;\n }\n /**\n *Decodes given set of received codewords, which include both data and error-correction\n * codewords. Really, this means it uses Reed-Solomon to detect and correct errors, in-place,\n * in the input.
\n *\n * @param received data and error-correction codewords\n * @param twoS number of error-correction codewords available\n * @throws ReedSolomonException if decoding fails for any reason\n */\n ReedSolomonDecoder.prototype.decode = function (received, twoS /*int*/) {\n var field = this.field;\n var poly = new GenericGFPoly(field, received);\n var syndromeCoefficients = new Int32Array(twoS);\n var noError = true;\n for (var i = 0; i < twoS; i++) {\n var evalResult = poly.evaluateAt(field.exp(i + field.getGeneratorBase()));\n syndromeCoefficients[syndromeCoefficients.length - 1 - i] = evalResult;\n if (evalResult !== 0) {\n noError = false;\n }\n }\n if (noError) {\n return;\n }\n var syndrome = new GenericGFPoly(field, syndromeCoefficients);\n var sigmaOmega = this.runEuclideanAlgorithm(field.buildMonomial(twoS, 1), syndrome, twoS);\n var sigma = sigmaOmega[0];\n var omega = sigmaOmega[1];\n var errorLocations = this.findErrorLocations(sigma);\n var errorMagnitudes = this.findErrorMagnitudes(omega, errorLocations);\n for (var i = 0; i < errorLocations.length; i++) {\n var position = received.length - 1 - field.log(errorLocations[i]);\n if (position < 0) {\n throw new ReedSolomonException('Bad error location');\n }\n received[position] = GenericGF.addOrSubtract(received[position], errorMagnitudes[i]);\n }\n };\n ReedSolomonDecoder.prototype.runEuclideanAlgorithm = function (a, b, R /*int*/) {\n // Assume a's degree is >= b's\n if (a.getDegree() < b.getDegree()) {\n var temp = a;\n a = b;\n b = temp;\n }\n var field = this.field;\n var rLast = a;\n var r = b;\n var tLast = field.getZero();\n var t = field.getOne();\n // Run Euclidean algorithm until r's degree is less than R/2\n while (r.getDegree() >= (R / 2 | 0)) {\n var rLastLast = rLast;\n var tLastLast = tLast;\n rLast = r;\n tLast = t;\n // Divide rLastLast by rLast, with quotient in q and remainder in r\n if (rLast.isZero()) {\n // Oops, Euclidean algorithm already terminated?\n throw new ReedSolomonException('r_{i-1} was zero');\n }\n r = rLastLast;\n var q = field.getZero();\n var denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());\n var dltInverse = field.inverse(denominatorLeadingTerm);\n while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {\n var degreeDiff = r.getDegree() - rLast.getDegree();\n var scale = field.multiply(r.getCoefficient(r.getDegree()), dltInverse);\n q = q.addOrSubtract(field.buildMonomial(degreeDiff, scale));\n r = r.addOrSubtract(rLast.multiplyByMonomial(degreeDiff, scale));\n }\n t = q.multiply(tLast).addOrSubtract(tLastLast);\n if (r.getDegree() >= rLast.getDegree()) {\n throw new IllegalStateException('Division algorithm failed to reduce polynomial?');\n }\n }\n var sigmaTildeAtZero = t.getCoefficient(0);\n if (sigmaTildeAtZero === 0) {\n throw new ReedSolomonException('sigmaTilde(0) was zero');\n }\n var inverse = field.inverse(sigmaTildeAtZero);\n var sigma = t.multiplyScalar(inverse);\n var omega = r.multiplyScalar(inverse);\n return [sigma, omega];\n };\n ReedSolomonDecoder.prototype.findErrorLocations = function (errorLocator) {\n // This is a direct application of Chien's search\n var numErrors = errorLocator.getDegree();\n if (numErrors === 1) { // shortcut\n return Int32Array.from([errorLocator.getCoefficient(1)]);\n }\n var result = new Int32Array(numErrors);\n var e = 0;\n var field = this.field;\n for (var i = 1; i < field.getSize() && e < numErrors; i++) {\n if (errorLocator.evaluateAt(i) === 0) {\n result[e] = field.inverse(i);\n e++;\n }\n }\n if (e !== numErrors) {\n throw new ReedSolomonException('Error locator degree does not match number of roots');\n }\n return result;\n };\n ReedSolomonDecoder.prototype.findErrorMagnitudes = function (errorEvaluator, errorLocations) {\n // This is directly applying Forney's Formula\n var s = errorLocations.length;\n var result = new Int32Array(s);\n var field = this.field;\n for (var i = 0; i < s; i++) {\n var xiInverse = field.inverse(errorLocations[i]);\n var denominator = 1;\n for (var j = 0; j < s; j++) {\n if (i !== j) {\n // denominator = field.multiply(denominator,\n // GenericGF.addOrSubtract(1, field.multiply(errorLocations[j], xiInverse)))\n // Above should work but fails on some Apple and Linux JDKs due to a Hotspot bug.\n // Below is a funny-looking workaround from Steven Parkes\n var term = field.multiply(errorLocations[j], xiInverse);\n var termPlus1 = (term & 0x1) === 0 ? term | 1 : term & ~1;\n denominator = field.multiply(denominator, termPlus1);\n }\n }\n result[i] = field.multiply(errorEvaluator.evaluateAt(xiInverse), field.inverse(denominator));\n if (field.getGeneratorBase() !== 0) {\n result[i] = field.multiply(result[i], xiInverse);\n }\n }\n return result;\n };\n return ReedSolomonDecoder;\n}());\nexport default ReedSolomonDecoder;\n","/*\n * Copyright 2008 ZXing authors\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 */\nimport GenericGFPoly from './GenericGFPoly';\nimport System from '../../util/System';\nimport IllegalArgumentException from '../../IllegalArgumentException';\n/**\n *Implements Reed-Solomon encoding, as the name implies.
\n *\n * @author Sean Owen\n * @author William Rucklidge\n */\nvar ReedSolomonEncoder = /** @class */ (function () {\n /**\n * A reed solomon error-correcting encoding constructor is created by\n * passing as Galois Field with of size equal to the number of code\n * words (symbols) in the alphabet (the number of values in each\n * element of arrays that are encoded/decoded).\n * @param field A galois field with a number of elements equal to the size\n * of the alphabet of symbols to encode.\n */\n function ReedSolomonEncoder(field) {\n this.field = field;\n this.cachedGenerators = [];\n this.cachedGenerators.push(new GenericGFPoly(field, Int32Array.from([1])));\n }\n ReedSolomonEncoder.prototype.buildGenerator = function (degree /*int*/) {\n var cachedGenerators = this.cachedGenerators;\n if (degree >= cachedGenerators.length) {\n var lastGenerator = cachedGenerators[cachedGenerators.length - 1];\n var field = this.field;\n for (var d = cachedGenerators.length; d <= degree; d++) {\n var nextGenerator = lastGenerator.multiply(new GenericGFPoly(field, Int32Array.from([1, field.exp(d - 1 + field.getGeneratorBase())])));\n cachedGenerators.push(nextGenerator);\n lastGenerator = nextGenerator;\n }\n }\n return cachedGenerators[degree];\n };\n /**\n *Encode a sequence of code words (symbols) using Reed-Solomon to allow decoders\n * to detect and correct errors that may have been introduced when the resulting\n * data is stored or transmitted.
\n *\n * @param toEncode array used for both and output. Caller initializes the array with\n * the code words (symbols) to be encoded followed by empty elements allocated to make\n * space for error-correction code words in the encoded output. The array contains\n * the encdoded output when encode returns. Code words are encoded as numbers from\n * 0 to n-1, where n is the number of possible code words (symbols), as determined\n * by the size of the Galois Field passed in the constructor of this object.\n * @param ecBytes the number of elements reserved in the array (first parameter)\n * to store error-correction code words. Thus, the number of code words (symbols)\n * to encode in the first parameter is thus toEncode.length - ecBytes.\n * Note, the use of \"bytes\" in the name of this parameter is misleading, as there may\n * be more or fewer than 256 symbols being encoded, as determined by the number of\n * elements in the Galois Field passed as a constructor to this object.\n * @throws IllegalArgumentException thrown in response to validation errros.\n */\n ReedSolomonEncoder.prototype.encode = function (toEncode, ecBytes /*int*/) {\n if (ecBytes === 0) {\n throw new IllegalArgumentException('No error correction bytes');\n }\n var dataBytes = toEncode.length - ecBytes;\n if (dataBytes <= 0) {\n throw new IllegalArgumentException('No data bytes provided');\n }\n var generator = this.buildGenerator(ecBytes);\n var infoCoefficients = new Int32Array(dataBytes);\n System.arraycopy(toEncode, 0, infoCoefficients, 0, dataBytes);\n var info = new GenericGFPoly(this.field, infoCoefficients);\n info = info.multiplyByMonomial(ecBytes, 1);\n var remainder = info.divide(generator)[1];\n var coefficients = remainder.getCoefficients();\n var numZeroCoefficients = ecBytes - coefficients.length;\n for (var i = 0; i < numZeroCoefficients; i++) {\n toEncode[dataBytes + i] = 0;\n }\n System.arraycopy(coefficients, 0, toEncode, dataBytes + numZeroCoefficients, coefficients.length);\n };\n return ReedSolomonEncoder;\n}());\nexport default ReedSolomonEncoder;\n","import BarcodeFormat from '../BarcodeFormat';\nimport BitMatrix from '../common/BitMatrix';\nimport DecodeHintType from '../DecodeHintType';\nimport NotFoundException from '../NotFoundException';\nimport Result from '../Result';\nimport ResultMetadataType from '../ResultMetadataType';\nimport System from '../util/System';\nimport Decoder from './decoder/Decoder';\nimport Detector from './detector/Detector';\n/*\n * Copyright 2007 ZXing authors\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 * This implementation can detect and decode Data Matrix codes in an image.\n *\n * @author bbrown@google.com (Brian Brown)\n */\nvar DataMatrixReader = /** @class */ (function () {\n function DataMatrixReader() {\n this.decoder = new Decoder();\n }\n /**\n * Locates and decodes a Data Matrix code in an image.\n *\n * @return a String representing the content encoded by the Data Matrix code\n * @throws NotFoundException if a Data Matrix code cannot be found\n * @throws FormatException if a Data Matrix code cannot be decoded\n * @throws ChecksumException if error correction fails\n */\n // @Override\n // public Result decode(BinaryBitmap image) throws NotFoundException, ChecksumException, FormatException {\n // return decode(image, null);\n // }\n // @Override\n DataMatrixReader.prototype.decode = function (image, hints) {\n if (hints === void 0) { hints = null; }\n var decoderResult;\n var points;\n if (hints != null && hints.has(DecodeHintType.PURE_BARCODE)) {\n var bits = DataMatrixReader.extractPureBits(image.getBlackMatrix());\n decoderResult = this.decoder.decode(bits);\n points = DataMatrixReader.NO_POINTS;\n }\n else {\n var detectorResult = new Detector(image.getBlackMatrix()).detect();\n decoderResult = this.decoder.decode(detectorResult.getBits());\n points = detectorResult.getPoints();\n }\n var rawBytes = decoderResult.getRawBytes();\n var result = new Result(decoderResult.getText(), rawBytes, 8 * rawBytes.length, points, BarcodeFormat.DATA_MATRIX, System.currentTimeMillis());\n var byteSegments = decoderResult.getByteSegments();\n if (byteSegments != null) {\n result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);\n }\n var ecLevel = decoderResult.getECLevel();\n if (ecLevel != null) {\n result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);\n }\n return result;\n };\n // @Override\n DataMatrixReader.prototype.reset = function () {\n // do nothing\n };\n /**\n * This method detects a code in a \"pure\" image -- that is, pure monochrome image\n * which contains only an unrotated, unskewed, image of a code, with some white border\n * around it. This is a specialized method that works exceptionally fast in this special\n * case.\n *\n * @see com.google.zxing.qrcode.QRCodeReader#extractPureBits(BitMatrix)\n */\n DataMatrixReader.extractPureBits = function (image) {\n var leftTopBlack = image.getTopLeftOnBit();\n var rightBottomBlack = image.getBottomRightOnBit();\n if (leftTopBlack == null || rightBottomBlack == null) {\n throw new NotFoundException();\n }\n var moduleSize = this.moduleSize(leftTopBlack, image);\n var top = leftTopBlack[1];\n var bottom = rightBottomBlack[1];\n var left = leftTopBlack[0];\n var right = rightBottomBlack[0];\n var matrixWidth = (right - left + 1) / moduleSize;\n var matrixHeight = (bottom - top + 1) / moduleSize;\n if (matrixWidth <= 0 || matrixHeight <= 0) {\n throw new NotFoundException();\n }\n // Push in the \"border\" by half the module width so that we start\n // sampling in the middle of the module. Just in case the image is a\n // little off, this will help recover.\n var nudge = moduleSize / 2;\n top += nudge;\n left += nudge;\n // Now just read off the bits\n var bits = new BitMatrix(matrixWidth, matrixHeight);\n for (var y = 0; y < matrixHeight; y++) {\n var iOffset = top + y * moduleSize;\n for (var x = 0; x < matrixWidth; x++) {\n if (image.get(left + x * moduleSize, iOffset)) {\n bits.set(x, y);\n }\n }\n }\n return bits;\n };\n DataMatrixReader.moduleSize = function (leftTopBlack, image) {\n var width = image.getWidth();\n var x = leftTopBlack[0];\n var y = leftTopBlack[1];\n while (x < width && image.get(x, y)) {\n x++;\n }\n if (x === width) {\n throw new NotFoundException();\n }\n var moduleSize = x - leftTopBlack[0];\n if (moduleSize === 0) {\n throw new NotFoundException();\n }\n return moduleSize;\n };\n DataMatrixReader.NO_POINTS = [];\n return DataMatrixReader;\n}());\nexport default DataMatrixReader;\n","import BarcodeFormat from '../BarcodeFormat';\nimport BitMatrix from '../common/BitMatrix';\nimport EncodeHintType from '../EncodeHintType';\nimport ByteMatrix from '../qrcode/encoder/ByteMatrix';\nimport Charset from '../util/Charset';\nimport { DefaultPlacement, ErrorCorrection, HighLevelEncoder, MinimalEncoder, SymbolInfo, } from './encoder';\nvar DataMatrixWriter = /** @class */ (function () {\n function DataMatrixWriter() {\n }\n DataMatrixWriter.prototype.encode = function (contents, format, width, height, hints) {\n if (hints === void 0) { hints = null; }\n if (contents.trim() === '') {\n throw new Error('Found empty contents');\n }\n if (format !== BarcodeFormat.DATA_MATRIX) {\n throw new Error('Can only encode DATA_MATRIX, but got ' + format);\n }\n if (width < 0 || height < 0) {\n throw new Error('Requested dimensions can\\'t be negative: ' + width + 'x' + height);\n }\n // Try to get force shape & min / max size\n var shape = 0 /* FORCE_NONE */;\n var minSize = null;\n var maxSize = null;\n if (hints != null) {\n var requestedShape = hints.get(EncodeHintType.DATA_MATRIX_SHAPE);\n if (requestedShape != null) {\n shape = requestedShape;\n }\n var requestedMinSize = hints.get(EncodeHintType.MIN_SIZE);\n if (requestedMinSize != null) {\n minSize = requestedMinSize;\n }\n var requestedMaxSize = hints.get(EncodeHintType.MAX_SIZE);\n if (requestedMaxSize != null) {\n maxSize = requestedMaxSize;\n }\n }\n // 1. step: Data encodation\n var encoded;\n var hasCompactionHint = hints != null &&\n hints.has(EncodeHintType.DATA_MATRIX_COMPACT) &&\n Boolean(hints.get(EncodeHintType.DATA_MATRIX_COMPACT).toString());\n if (hasCompactionHint) {\n var hasGS1FormatHint = hints.has(EncodeHintType.GS1_FORMAT) &&\n Boolean(hints.get(EncodeHintType.GS1_FORMAT).toString());\n var charset = null;\n var hasEncodingHint = hints.has(EncodeHintType.CHARACTER_SET);\n if (hasEncodingHint) {\n charset = Charset.forName(hints.get(EncodeHintType.CHARACTER_SET).toString());\n }\n encoded = MinimalEncoder.encodeHighLevel(contents, charset, hasGS1FormatHint ? 0x1d : -1, shape);\n }\n else {\n var hasForceC40Hint = hints != null &&\n hints.has(EncodeHintType.FORCE_C40) &&\n Boolean(hints.get(EncodeHintType.FORCE_C40).toString());\n encoded = HighLevelEncoder.encodeHighLevel(contents, shape, minSize, maxSize, hasForceC40Hint);\n }\n var symbolInfo = SymbolInfo.lookup(encoded.length, shape, minSize, maxSize, true);\n // 2. step: ECC generation\n var codewords = ErrorCorrection.encodeECC200(encoded, symbolInfo);\n // 3. step: Module placement in Matrix\n var placement = new DefaultPlacement(codewords, symbolInfo.getSymbolDataWidth(), symbolInfo.getSymbolDataHeight());\n placement.place();\n // 4. step: low-level encoding\n return this.encodeLowLevel(placement, symbolInfo, width, height);\n };\n /**\n * Encode the given symbol info to a bit matrix.\n *\n * @param placement The DataMatrix placement.\n * @param symbolInfo The symbol info to encode.\n * @return The bit matrix generated.\n */\n DataMatrixWriter.prototype.encodeLowLevel = function (placement, symbolInfo, width, height) {\n var symbolWidth = symbolInfo.getSymbolDataWidth();\n var symbolHeight = symbolInfo.getSymbolDataHeight();\n var matrix = new ByteMatrix(symbolInfo.getSymbolWidth(), symbolInfo.getSymbolHeight());\n var matrixY = 0;\n for (var y = 0; y < symbolHeight; y++) {\n // Fill the top edge with alternate 0 / 1\n var matrixX = void 0;\n if (y % symbolInfo.matrixHeight === 0) {\n matrixX = 0;\n for (var x = 0; x < symbolInfo.getSymbolWidth(); x++) {\n matrix.setBoolean(matrixX, matrixY, x % 2 === 0);\n matrixX++;\n }\n matrixY++;\n }\n matrixX = 0;\n for (var x = 0; x < symbolWidth; x++) {\n // Fill the right edge with full 1\n if (x % symbolInfo.matrixWidth === 0) {\n matrix.setBoolean(matrixX, matrixY, true);\n matrixX++;\n }\n matrix.setBoolean(matrixX, matrixY, placement.getBit(x, y));\n matrixX++;\n // Fill the right edge with alternate 0 / 1\n if (x % symbolInfo.matrixWidth === symbolInfo.matrixWidth - 1) {\n matrix.setBoolean(matrixX, matrixY, y % 2 === 0);\n matrixX++;\n }\n }\n matrixY++;\n // Fill the bottom edge with full 1\n if (y % symbolInfo.matrixHeight === symbolInfo.matrixHeight - 1) {\n matrixX = 0;\n for (var x = 0; x < symbolInfo.getSymbolWidth(); x++) {\n matrix.setBoolean(matrixX, matrixY, true);\n matrixX++;\n }\n matrixY++;\n }\n }\n return this.convertByteMatrixToBitMatrix(matrix, width, height);\n };\n /**\n * Convert the ByteMatrix to BitMatrix.\n *\n * @param reqHeight The requested height of the image (in pixels) with the Datamatrix code\n * @param reqWidth The requested width of the image (in pixels) with the Datamatrix code\n * @param matrix The input matrix.\n * @return The output matrix.\n */\n DataMatrixWriter.prototype.convertByteMatrixToBitMatrix = function (matrix, reqWidth, reqHeight) {\n var matrixWidth = matrix.getWidth();\n var matrixHeight = matrix.getHeight();\n var outputWidth = Math.max(reqWidth, matrixWidth);\n var outputHeight = Math.max(reqHeight, matrixHeight);\n var multiple = Math.min(outputWidth / matrixWidth, outputHeight / matrixHeight);\n var leftPadding = (outputWidth - matrixWidth * multiple) / 2;\n var topPadding = (outputHeight - matrixHeight * multiple) / 2;\n var output;\n // remove padding if requested width and height are too small\n if (reqHeight < matrixHeight || reqWidth < matrixWidth) {\n leftPadding = 0;\n topPadding = 0;\n output = new BitMatrix(matrixWidth, matrixHeight);\n }\n else {\n output = new BitMatrix(reqWidth, reqHeight);\n }\n output.clear();\n for (var inputY = 0, outputY = topPadding; inputY < matrixHeight; inputY++, outputY += multiple) {\n // Write the contents of this row of the bytematrix\n for (var inputX = 0, outputX = leftPadding; inputX < matrixWidth; inputX++, outputX += multiple) {\n if (matrix.get(inputX, inputY) === 1) {\n output.setRegion(outputX, outputY, multiple, multiple);\n }\n }\n }\n return output;\n };\n return DataMatrixWriter;\n}());\nexport default DataMatrixWriter;\n","import BitMatrix from '../../common/BitMatrix';\nimport Version from './Version';\nimport FormatException from '../../FormatException';\nimport IllegalArgumentException from '../../IllegalArgumentException';\n/*\n * Copyright 2007 ZXing authors\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 * @author bbrown@google.com (Brian Brown)\n */\nvar BitMatrixParser = /** @class */ (function () {\n /**\n * @param bitMatrix {@link BitMatrix} to parse\n * @throws FormatException if dimension is < 8 or > 144 or not 0 mod 2\n */\n function BitMatrixParser(bitMatrix) {\n var dimension = bitMatrix.getHeight();\n if (dimension < 8 || dimension > 144 || (dimension & 0x01) !== 0) {\n throw new FormatException();\n }\n this.version = BitMatrixParser.readVersion(bitMatrix);\n this.mappingBitMatrix = this.extractDataRegion(bitMatrix);\n this.readMappingMatrix = new BitMatrix(this.mappingBitMatrix.getWidth(), this.mappingBitMatrix.getHeight());\n }\n BitMatrixParser.prototype.getVersion = function () {\n return this.version;\n };\n /**\n *Creates the version object based on the dimension of the original bit matrix from\n * the datamatrix code.
\n *\n *See ISO 16022:2006 Table 7 - ECC 200 symbol attributes
\n *\n * @param bitMatrix Original {@link BitMatrix} including alignment patterns\n * @return {@link Version} encapsulating the Data Matrix Code's \"version\"\n * @throws FormatException if the dimensions of the mapping matrix are not valid\n * Data Matrix dimensions.\n */\n BitMatrixParser.readVersion = function (bitMatrix) {\n var numRows = bitMatrix.getHeight();\n var numColumns = bitMatrix.getWidth();\n return Version.getVersionForDimensions(numRows, numColumns);\n };\n /**\n *Reads the bits in the {@link BitMatrix} representing the mapping matrix (No alignment patterns)\n * in the correct order in order to reconstitute the codewords bytes contained within the\n * Data Matrix Code.
\n *\n * @return bytes encoded within the Data Matrix Code\n * @throws FormatException if the exact number of bytes expected is not read\n */\n BitMatrixParser.prototype.readCodewords = function () {\n var result = new Int8Array(this.version.getTotalCodewords());\n var resultOffset = 0;\n var row = 4;\n var column = 0;\n var numRows = this.mappingBitMatrix.getHeight();\n var numColumns = this.mappingBitMatrix.getWidth();\n var corner1Read = false;\n var corner2Read = false;\n var corner3Read = false;\n var corner4Read = false;\n // Read all of the codewords\n do {\n // Check the four corner cases\n if ((row === numRows) && (column === 0) && !corner1Read) {\n result[resultOffset++] = this.readCorner1(numRows, numColumns) & 0xff;\n row -= 2;\n column += 2;\n corner1Read = true;\n }\n else if ((row === numRows - 2) && (column === 0) && ((numColumns & 0x03) !== 0) && !corner2Read) {\n result[resultOffset++] = this.readCorner2(numRows, numColumns) & 0xff;\n row -= 2;\n column += 2;\n corner2Read = true;\n }\n else if ((row === numRows + 4) && (column === 2) && ((numColumns & 0x07) === 0) && !corner3Read) {\n result[resultOffset++] = this.readCorner3(numRows, numColumns) & 0xff;\n row -= 2;\n column += 2;\n corner3Read = true;\n }\n else if ((row === numRows - 2) && (column === 0) && ((numColumns & 0x07) === 4) && !corner4Read) {\n result[resultOffset++] = this.readCorner4(numRows, numColumns) & 0xff;\n row -= 2;\n column += 2;\n corner4Read = true;\n }\n else {\n // Sweep upward diagonally to the right\n do {\n if ((row < numRows) && (column >= 0) && !this.readMappingMatrix.get(column, row)) {\n result[resultOffset++] = this.readUtah(row, column, numRows, numColumns) & 0xff;\n }\n row -= 2;\n column += 2;\n } while ((row >= 0) && (column < numColumns));\n row += 1;\n column += 3;\n // Sweep downward diagonally to the left\n do {\n if ((row >= 0) && (column < numColumns) && !this.readMappingMatrix.get(column, row)) {\n result[resultOffset++] = this.readUtah(row, column, numRows, numColumns) & 0xff;\n }\n row += 2;\n column -= 2;\n } while ((row < numRows) && (column >= 0));\n row += 3;\n column += 1;\n }\n } while ((row < numRows) || (column < numColumns));\n if (resultOffset !== this.version.getTotalCodewords()) {\n throw new FormatException();\n }\n return result;\n };\n /**\n *Reads a bit of the mapping matrix accounting for boundary wrapping.
\n *\n * @param row Row to read in the mapping matrix\n * @param column Column to read in the mapping matrix\n * @param numRows Number of rows in the mapping matrix\n * @param numColumns Number of columns in the mapping matrix\n * @return value of the given bit in the mapping matrix\n */\n BitMatrixParser.prototype.readModule = function (row, column, numRows, numColumns) {\n // Adjust the row and column indices based on boundary wrapping\n if (row < 0) {\n row += numRows;\n column += 4 - ((numRows + 4) & 0x07);\n }\n if (column < 0) {\n column += numColumns;\n row += 4 - ((numColumns + 4) & 0x07);\n }\n this.readMappingMatrix.set(column, row);\n return this.mappingBitMatrix.get(column, row);\n };\n /**\n *Reads the 8 bits of the standard Utah-shaped pattern.
\n *\n *See ISO 16022:2006, 5.8.1 Figure 6
\n *\n * @param row Current row in the mapping matrix, anchored at the 8th bit (LSB) of the pattern\n * @param column Current column in the mapping matrix, anchored at the 8th bit (LSB) of the pattern\n * @param numRows Number of rows in the mapping matrix\n * @param numColumns Number of columns in the mapping matrix\n * @return byte from the utah shape\n */\n BitMatrixParser.prototype.readUtah = function (row, column, numRows, numColumns) {\n var currentByte = 0;\n if (this.readModule(row - 2, column - 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(row - 2, column - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(row - 1, column - 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(row - 1, column - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(row - 1, column, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(row, column - 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(row, column - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(row, column, numRows, numColumns)) {\n currentByte |= 1;\n }\n return currentByte;\n };\n /**\n *Reads the 8 bits of the special corner condition 1.
\n *\n *See ISO 16022:2006, Figure F.3
\n *\n * @param numRows Number of rows in the mapping matrix\n * @param numColumns Number of columns in the mapping matrix\n * @return byte from the Corner condition 1\n */\n BitMatrixParser.prototype.readCorner1 = function (numRows, numColumns) {\n var currentByte = 0;\n if (this.readModule(numRows - 1, 0, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(numRows - 1, 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(numRows - 1, 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(1, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(2, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(3, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n return currentByte;\n };\n /**\n *Reads the 8 bits of the special corner condition 2.
\n *\n *See ISO 16022:2006, Figure F.4
\n *\n * @param numRows Number of rows in the mapping matrix\n * @param numColumns Number of columns in the mapping matrix\n * @return byte from the Corner condition 2\n */\n BitMatrixParser.prototype.readCorner2 = function (numRows, numColumns) {\n var currentByte = 0;\n if (this.readModule(numRows - 3, 0, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(numRows - 2, 0, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(numRows - 1, 0, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 4, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 3, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(1, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n return currentByte;\n };\n /**\n *Reads the 8 bits of the special corner condition 3.
\n *\n *See ISO 16022:2006, Figure F.5
\n *\n * @param numRows Number of rows in the mapping matrix\n * @param numColumns Number of columns in the mapping matrix\n * @return byte from the Corner condition 3\n */\n BitMatrixParser.prototype.readCorner3 = function (numRows, numColumns) {\n var currentByte = 0;\n if (this.readModule(numRows - 1, 0, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(numRows - 1, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 3, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(1, numColumns - 3, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(1, numColumns - 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(1, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n return currentByte;\n };\n /**\n *Reads the 8 bits of the special corner condition 4.
\n *\n *See ISO 16022:2006, Figure F.6
\n *\n * @param numRows Number of rows in the mapping matrix\n * @param numColumns Number of columns in the mapping matrix\n * @return byte from the Corner condition 4\n */\n BitMatrixParser.prototype.readCorner4 = function (numRows, numColumns) {\n var currentByte = 0;\n if (this.readModule(numRows - 3, 0, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(numRows - 2, 0, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(numRows - 1, 0, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 2, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(0, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(1, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(2, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n currentByte <<= 1;\n if (this.readModule(3, numColumns - 1, numRows, numColumns)) {\n currentByte |= 1;\n }\n return currentByte;\n };\n /**\n *Extracts the data region from a {@link BitMatrix} that contains\n * alignment patterns.
\n *\n * @param bitMatrix Original {@link BitMatrix} with alignment patterns\n * @return BitMatrix that has the alignment patterns removed\n */\n BitMatrixParser.prototype.extractDataRegion = function (bitMatrix) {\n var symbolSizeRows = this.version.getSymbolSizeRows();\n var symbolSizeColumns = this.version.getSymbolSizeColumns();\n if (bitMatrix.getHeight() !== symbolSizeRows) {\n throw new IllegalArgumentException('Dimension of bitMatrix must match the version size');\n }\n var dataRegionSizeRows = this.version.getDataRegionSizeRows();\n var dataRegionSizeColumns = this.version.getDataRegionSizeColumns();\n var numDataRegionsRow = symbolSizeRows / dataRegionSizeRows | 0;\n var numDataRegionsColumn = symbolSizeColumns / dataRegionSizeColumns | 0;\n var sizeDataRegionRow = numDataRegionsRow * dataRegionSizeRows;\n var sizeDataRegionColumn = numDataRegionsColumn * dataRegionSizeColumns;\n var bitMatrixWithoutAlignment = new BitMatrix(sizeDataRegionColumn, sizeDataRegionRow);\n for (var dataRegionRow = 0; dataRegionRow < numDataRegionsRow; ++dataRegionRow) {\n var dataRegionRowOffset = dataRegionRow * dataRegionSizeRows;\n for (var dataRegionColumn = 0; dataRegionColumn < numDataRegionsColumn; ++dataRegionColumn) {\n var dataRegionColumnOffset = dataRegionColumn * dataRegionSizeColumns;\n for (var i = 0; i < dataRegionSizeRows; ++i) {\n var readRowOffset = dataRegionRow * (dataRegionSizeRows + 2) + 1 + i;\n var writeRowOffset = dataRegionRowOffset + i;\n for (var j = 0; j < dataRegionSizeColumns; ++j) {\n var readColumnOffset = dataRegionColumn * (dataRegionSizeColumns + 2) + 1 + j;\n if (bitMatrix.get(readColumnOffset, readRowOffset)) {\n var writeColumnOffset = dataRegionColumnOffset + j;\n bitMatrixWithoutAlignment.set(writeColumnOffset, writeRowOffset);\n }\n }\n }\n }\n }\n return bitMatrixWithoutAlignment;\n };\n return BitMatrixParser;\n}());\nexport default BitMatrixParser;\n","var __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport IllegalArgumentException from '../../IllegalArgumentException';\n/*\n * Copyright 2008 ZXing authors\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 *Encapsulates a block of data within a Data Matrix Code. Data Matrix Codes may split their data into\n * multiple blocks, each of which is a unit of data and error-correction codewords. Each\n * is represented by an instance of this class.
\n *\n * @author bbrown@google.com (Brian Brown)\n */\nvar DataBlock = /** @class */ (function () {\n function DataBlock(numDataCodewords, codewords) {\n this.numDataCodewords = numDataCodewords;\n this.codewords = codewords;\n }\n /**\n *When Data Matrix Codes use multiple data blocks, they actually interleave the bytes of each of them.\n * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This\n * method will separate the data into original blocks.
\n *\n * @param rawCodewords bytes as read directly from the Data Matrix Code\n * @param version version of the Data Matrix Code\n * @return DataBlocks containing original bytes, \"de-interleaved\" from representation in the\n * Data Matrix Code\n */\n DataBlock.getDataBlocks = function (rawCodewords, version) {\n var e_1, _a, e_2, _b;\n // Figure out the number and size of data blocks used by this version\n var ecBlocks = version.getECBlocks();\n // First count the total number of data blocks\n var totalBlocks = 0;\n var ecBlockArray = ecBlocks.getECBlocks();\n try {\n for (var ecBlockArray_1 = __values(ecBlockArray), ecBlockArray_1_1 = ecBlockArray_1.next(); !ecBlockArray_1_1.done; ecBlockArray_1_1 = ecBlockArray_1.next()) {\n var ecBlock = ecBlockArray_1_1.value;\n totalBlocks += ecBlock.getCount();\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (ecBlockArray_1_1 && !ecBlockArray_1_1.done && (_a = ecBlockArray_1.return)) _a.call(ecBlockArray_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Now establish DataBlocks of the appropriate size and number of data codewords\n var result = new Array(totalBlocks);\n var numResultBlocks = 0;\n try {\n for (var ecBlockArray_2 = __values(ecBlockArray), ecBlockArray_2_1 = ecBlockArray_2.next(); !ecBlockArray_2_1.done; ecBlockArray_2_1 = ecBlockArray_2.next()) {\n var ecBlock = ecBlockArray_2_1.value;\n for (var i = 0; i < ecBlock.getCount(); i++) {\n var numDataCodewords = ecBlock.getDataCodewords();\n var numBlockCodewords = ecBlocks.getECCodewords() + numDataCodewords;\n result[numResultBlocks++] = new DataBlock(numDataCodewords, new Uint8Array(numBlockCodewords));\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (ecBlockArray_2_1 && !ecBlockArray_2_1.done && (_b = ecBlockArray_2.return)) _b.call(ecBlockArray_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n // All blocks have the same amount of data, except that the last n\n // (where n may be 0) have 1 less byte. Figure out where these start.\n // TODO(bbrown): There is only one case where there is a difference for Data Matrix for size 144\n var longerBlocksTotalCodewords = result[0].codewords.length;\n // int shorterBlocksTotalCodewords = longerBlocksTotalCodewords - 1;\n var longerBlocksNumDataCodewords = longerBlocksTotalCodewords - ecBlocks.getECCodewords();\n var shorterBlocksNumDataCodewords = longerBlocksNumDataCodewords - 1;\n // The last elements of result may be 1 element shorter for 144 matrix\n // first fill out as many elements as all of them have minus 1\n var rawCodewordsOffset = 0;\n for (var i = 0; i < shorterBlocksNumDataCodewords; i++) {\n for (var j = 0; j < numResultBlocks; j++) {\n result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];\n }\n }\n // Fill out the last data block in the longer ones\n var specialVersion = version.getVersionNumber() === 24;\n var numLongerBlocks = specialVersion ? 8 : numResultBlocks;\n for (var j = 0; j < numLongerBlocks; j++) {\n result[j].codewords[longerBlocksNumDataCodewords - 1] = rawCodewords[rawCodewordsOffset++];\n }\n // Now add in error correction blocks\n var max = result[0].codewords.length;\n for (var i = longerBlocksNumDataCodewords; i < max; i++) {\n for (var j = 0; j < numResultBlocks; j++) {\n var jOffset = specialVersion ? (j + 8) % numResultBlocks : j;\n var iOffset = specialVersion && jOffset > 7 ? i - 1 : i;\n result[jOffset].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];\n }\n }\n if (rawCodewordsOffset !== rawCodewords.length) {\n throw new IllegalArgumentException();\n }\n return result;\n };\n DataBlock.prototype.getNumDataCodewords = function () {\n return this.numDataCodewords;\n };\n DataBlock.prototype.getCodewords = function () {\n return this.codewords;\n };\n return DataBlock;\n}());\nexport default DataBlock;\n","import DecoderResult from '../../common/DecoderResult';\nimport BitSource from '../../common/BitSource';\nimport StringBuilder from '../../util/StringBuilder';\nimport StringEncoding from '../../util/StringEncoding';\nimport StringUtils from '../../common/StringUtils';\nimport FormatException from '../../FormatException';\nimport IllegalStateException from '../../IllegalStateException';\n/*\n * Copyright 2008 ZXing authors\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 */\nvar Mode;\n(function (Mode) {\n Mode[Mode[\"PAD_ENCODE\"] = 0] = \"PAD_ENCODE\";\n Mode[Mode[\"ASCII_ENCODE\"] = 1] = \"ASCII_ENCODE\";\n Mode[Mode[\"C40_ENCODE\"] = 2] = \"C40_ENCODE\";\n Mode[Mode[\"TEXT_ENCODE\"] = 3] = \"TEXT_ENCODE\";\n Mode[Mode[\"ANSIX12_ENCODE\"] = 4] = \"ANSIX12_ENCODE\";\n Mode[Mode[\"EDIFACT_ENCODE\"] = 5] = \"EDIFACT_ENCODE\";\n Mode[Mode[\"BASE256_ENCODE\"] = 6] = \"BASE256_ENCODE\";\n})(Mode || (Mode = {}));\n/**\n *Data Matrix Codes can encode text as bits in one of several modes, and can use multiple modes\n * in one Data Matrix Code. This class decodes the bits back into text.
\n *\n *See ISO 16022:2006, 5.2.1 - 5.2.9.2
\n *\n * @author bbrown@google.com (Brian Brown)\n * @author Sean Owen\n */\nvar DecodedBitStreamParser = /** @class */ (function () {\n function DecodedBitStreamParser() {\n }\n DecodedBitStreamParser.decode = function (bytes) {\n var bits = new BitSource(bytes);\n var result = new StringBuilder();\n var resultTrailer = new StringBuilder();\n var byteSegments = new Array();\n var mode = Mode.ASCII_ENCODE;\n do {\n if (mode === Mode.ASCII_ENCODE) {\n mode = this.decodeAsciiSegment(bits, result, resultTrailer);\n }\n else {\n switch (mode) {\n case Mode.C40_ENCODE:\n this.decodeC40Segment(bits, result);\n break;\n case Mode.TEXT_ENCODE:\n this.decodeTextSegment(bits, result);\n break;\n case Mode.ANSIX12_ENCODE:\n this.decodeAnsiX12Segment(bits, result);\n break;\n case Mode.EDIFACT_ENCODE:\n this.decodeEdifactSegment(bits, result);\n break;\n case Mode.BASE256_ENCODE:\n this.decodeBase256Segment(bits, result, byteSegments);\n break;\n default:\n throw new FormatException();\n }\n mode = Mode.ASCII_ENCODE;\n }\n } while (mode !== Mode.PAD_ENCODE && bits.available() > 0);\n if (resultTrailer.length() > 0) {\n result.append(resultTrailer.toString());\n }\n return new DecoderResult(bytes, result.toString(), byteSegments.length === 0 ? null : byteSegments, null);\n };\n /**\n * See ISO 16022:2006, 5.2.3 and Annex C, Table C.2\n */\n DecodedBitStreamParser.decodeAsciiSegment = function (bits, result, resultTrailer) {\n var upperShift = false;\n do {\n var oneByte = bits.readBits(8);\n if (oneByte === 0) {\n throw new FormatException();\n }\n else if (oneByte <= 128) { // ASCII data (ASCII value + 1)\n if (upperShift) {\n oneByte += 128;\n // upperShift = false;\n }\n result.append(String.fromCharCode(oneByte - 1));\n return Mode.ASCII_ENCODE;\n }\n else if (oneByte === 129) { // Pad\n return Mode.PAD_ENCODE;\n }\n else if (oneByte <= 229) { // 2-digit data 00-99 (Numeric Value + 130)\n var value = oneByte - 130;\n if (value < 10) { // pad with '0' for single digit values\n result.append('0');\n }\n result.append('' + value);\n }\n else {\n switch (oneByte) {\n case 230: // Latch to C40 encodation\n return Mode.C40_ENCODE;\n case 231: // Latch to Base 256 encodation\n return Mode.BASE256_ENCODE;\n case 232: // FNC1\n result.append(String.fromCharCode(29)); // translate as ASCII 29\n break;\n case 233: // Structured Append\n case 234: // Reader Programming\n // Ignore these symbols for now\n // throw ReaderException.getInstance();\n break;\n case 235: // Upper Shift (shift to Extended ASCII)\n upperShift = true;\n break;\n case 236: // 05 Macro\n result.append('[)>\\u001E05\\u001D');\n resultTrailer.insert(0, '\\u001E\\u0004');\n break;\n case 237: // 06 Macro\n result.append('[)>\\u001E06\\u001D');\n resultTrailer.insert(0, '\\u001E\\u0004');\n break;\n case 238: // Latch to ANSI X12 encodation\n return Mode.ANSIX12_ENCODE;\n case 239: // Latch to Text encodation\n return Mode.TEXT_ENCODE;\n case 240: // Latch to EDIFACT encodation\n return Mode.EDIFACT_ENCODE;\n case 241: // ECI Character\n // TODO(bbrown): I think we need to support ECI\n // throw ReaderException.getInstance();\n // Ignore this symbol for now\n break;\n default:\n // Not to be used in ASCII encodation\n // but work around encoders that end with 254, latch back to ASCII\n if (oneByte !== 254 || bits.available() !== 0) {\n throw new FormatException();\n }\n break;\n }\n }\n } while (bits.available() > 0);\n return Mode.ASCII_ENCODE;\n };\n /**\n * See ISO 16022:2006, 5.2.5 and Annex C, Table C.1\n */\n DecodedBitStreamParser.decodeC40Segment = function (bits, result) {\n // Three C40 values are encoded in a 16-bit value as\n // (1600 * C1) + (40 * C2) + C3 + 1\n // TODO(bbrown): The Upper Shift with C40 doesn't work in the 4 value scenario all the time\n var upperShift = false;\n var cValues = [];\n var shift = 0;\n do {\n // If there is only one byte left then it will be encoded as ASCII\n if (bits.available() === 8) {\n return;\n }\n var firstByte = bits.readBits(8);\n if (firstByte === 254) { // Unlatch codeword\n return;\n }\n this.parseTwoBytes(firstByte, bits.readBits(8), cValues);\n for (var i = 0; i < 3; i++) {\n var cValue = cValues[i];\n switch (shift) {\n case 0:\n if (cValue < 3) {\n shift = cValue + 1;\n }\n else if (cValue < this.C40_BASIC_SET_CHARS.length) {\n var c40char = this.C40_BASIC_SET_CHARS[cValue];\n if (upperShift) {\n result.append(String.fromCharCode(c40char.charCodeAt(0) + 128));\n upperShift = false;\n }\n else {\n result.append(c40char);\n }\n }\n else {\n throw new FormatException();\n }\n break;\n case 1:\n if (upperShift) {\n result.append(String.fromCharCode(cValue + 128));\n upperShift = false;\n }\n else {\n result.append(String.fromCharCode(cValue));\n }\n shift = 0;\n break;\n case 2:\n if (cValue < this.C40_SHIFT2_SET_CHARS.length) {\n var c40char = this.C40_SHIFT2_SET_CHARS[cValue];\n if (upperShift) {\n result.append(String.fromCharCode(c40char.charCodeAt(0) + 128));\n upperShift = false;\n }\n else {\n result.append(c40char);\n }\n }\n else {\n switch (cValue) {\n case 27: // FNC1\n result.append(String.fromCharCode(29)); // translate as ASCII 29\n break;\n case 30: // Upper Shift\n upperShift = true;\n break;\n default:\n throw new FormatException();\n }\n }\n shift = 0;\n break;\n case 3:\n if (upperShift) {\n result.append(String.fromCharCode(cValue + 224));\n upperShift = false;\n }\n else {\n result.append(String.fromCharCode(cValue + 96));\n }\n shift = 0;\n break;\n default:\n throw new FormatException();\n }\n }\n } while (bits.available() > 0);\n };\n /**\n * See ISO 16022:2006, 5.2.6 and Annex C, Table C.2\n */\n DecodedBitStreamParser.decodeTextSegment = function (bits, result) {\n // Three Text values are encoded in a 16-bit value as\n // (1600 * C1) + (40 * C2) + C3 + 1\n // TODO(bbrown): The Upper Shift with Text doesn't work in the 4 value scenario all the time\n var upperShift = false;\n var cValues = [];\n var shift = 0;\n do {\n // If there is only one byte left then it will be encoded as ASCII\n if (bits.available() === 8) {\n return;\n }\n var firstByte = bits.readBits(8);\n if (firstByte === 254) { // Unlatch codeword\n return;\n }\n this.parseTwoBytes(firstByte, bits.readBits(8), cValues);\n for (var i = 0; i < 3; i++) {\n var cValue = cValues[i];\n switch (shift) {\n case 0:\n if (cValue < 3) {\n shift = cValue + 1;\n }\n else if (cValue < this.TEXT_BASIC_SET_CHARS.length) {\n var textChar = this.TEXT_BASIC_SET_CHARS[cValue];\n if (upperShift) {\n result.append(String.fromCharCode(textChar.charCodeAt(0) + 128));\n upperShift = false;\n }\n else {\n result.append(textChar);\n }\n }\n else {\n throw new FormatException();\n }\n break;\n case 1:\n if (upperShift) {\n result.append(String.fromCharCode(cValue + 128));\n upperShift = false;\n }\n else {\n result.append(String.fromCharCode(cValue));\n }\n shift = 0;\n break;\n case 2:\n // Shift 2 for Text is the same encoding as C40\n if (cValue < this.TEXT_SHIFT2_SET_CHARS.length) {\n var textChar = this.TEXT_SHIFT2_SET_CHARS[cValue];\n if (upperShift) {\n result.append(String.fromCharCode(textChar.charCodeAt(0) + 128));\n upperShift = false;\n }\n else {\n result.append(textChar);\n }\n }\n else {\n switch (cValue) {\n case 27: // FNC1\n result.append(String.fromCharCode(29)); // translate as ASCII 29\n break;\n case 30: // Upper Shift\n upperShift = true;\n break;\n default:\n throw new FormatException();\n }\n }\n shift = 0;\n break;\n case 3:\n if (cValue < this.TEXT_SHIFT3_SET_CHARS.length) {\n var textChar = this.TEXT_SHIFT3_SET_CHARS[cValue];\n if (upperShift) {\n result.append(String.fromCharCode(textChar.charCodeAt(0) + 128));\n upperShift = false;\n }\n else {\n result.append(textChar);\n }\n shift = 0;\n }\n else {\n throw new FormatException();\n }\n break;\n default:\n throw new FormatException();\n }\n }\n } while (bits.available() > 0);\n };\n /**\n * See ISO 16022:2006, 5.2.7\n */\n DecodedBitStreamParser.decodeAnsiX12Segment = function (bits, result) {\n // Three ANSI X12 values are encoded in a 16-bit value as\n // (1600 * C1) + (40 * C2) + C3 + 1\n var cValues = [];\n do {\n // If there is only one byte left then it will be encoded as ASCII\n if (bits.available() === 8) {\n return;\n }\n var firstByte = bits.readBits(8);\n if (firstByte === 254) { // Unlatch codeword\n return;\n }\n this.parseTwoBytes(firstByte, bits.readBits(8), cValues);\n for (var i = 0; i < 3; i++) {\n var cValue = cValues[i];\n switch (cValue) {\n case 0: // X12 segment terminatorThe main class which implements Data Matrix Code decoding -- as opposed to locating and extracting\n * the Data Matrix Code from an image.
\n *\n * @author bbrown@google.com (Brian Brown)\n */\nvar Decoder = /** @class */ (function () {\n function Decoder() {\n this.rsDecoder = new ReedSolomonDecoder(GenericGF.DATA_MATRIX_FIELD_256);\n }\n /**\n *Decodes a Data Matrix Code represented as a {@link BitMatrix}. A 1 or \"true\" is taken\n * to mean a black module.
\n *\n * @param bits booleans representing white/black Data Matrix Code modules\n * @return text and bytes encoded within the Data Matrix Code\n * @throws FormatException if the Data Matrix Code cannot be decoded\n * @throws ChecksumException if error correction fails\n */\n Decoder.prototype.decode = function (bits) {\n var e_1, _a;\n // Construct a parser and read version, error-correction level\n var parser = new BitMatrixParser(bits);\n var version = parser.getVersion();\n // Read codewords\n var codewords = parser.readCodewords();\n // Separate into data blocks\n var dataBlocks = DataBlock.getDataBlocks(codewords, version);\n // Count total number of data bytes\n var totalBytes = 0;\n try {\n for (var dataBlocks_1 = __values(dataBlocks), dataBlocks_1_1 = dataBlocks_1.next(); !dataBlocks_1_1.done; dataBlocks_1_1 = dataBlocks_1.next()) {\n var db = dataBlocks_1_1.value;\n totalBytes += db.getNumDataCodewords();\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (dataBlocks_1_1 && !dataBlocks_1_1.done && (_a = dataBlocks_1.return)) _a.call(dataBlocks_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n var resultBytes = new Uint8Array(totalBytes);\n var dataBlocksCount = dataBlocks.length;\n // Error-correct and copy data blocks together into a stream of bytes\n for (var j = 0; j < dataBlocksCount; j++) {\n var dataBlock = dataBlocks[j];\n var codewordBytes = dataBlock.getCodewords();\n var numDataCodewords = dataBlock.getNumDataCodewords();\n this.correctErrors(codewordBytes, numDataCodewords);\n for (var i = 0; i < numDataCodewords; i++) {\n // De-interlace data blocks.\n resultBytes[i * dataBlocksCount + j] = codewordBytes[i];\n }\n }\n // Decode the contents of that stream of bytes\n return DecodedBitStreamParser.decode(resultBytes);\n };\n /**\n *Given data and error-correction codewords received, possibly corrupted by errors, attempts to\n * correct the errors in-place using Reed-Solomon error correction.
\n *\n * @param codewordBytes data and error correction codewords\n * @param numDataCodewords number of codewords that are data bytes\n * @throws ChecksumException if error correction fails\n */\n Decoder.prototype.correctErrors = function (codewordBytes, numDataCodewords) {\n // const numCodewords = codewordBytes.length;\n // First read into an array of ints\n var codewordsInts = new Int32Array(codewordBytes);\n // for (let i = 0; i < numCodewords; i++) {\n // codewordsInts[i] = codewordBytes[i] & 0xFF;\n // }\n try {\n this.rsDecoder.decode(codewordsInts, codewordBytes.length - numDataCodewords);\n }\n catch (ignored /* ReedSolomonException */) {\n throw new ChecksumException();\n }\n // Copy back into array of bytes -- only need to worry about the bytes that were data\n // We don't care about errors in the error-correction codewords\n for (var i = 0; i < numDataCodewords; i++) {\n codewordBytes[i] = codewordsInts[i];\n }\n };\n return Decoder;\n}());\nexport default Decoder;\n","var __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport FormatException from '../../FormatException';\n/*\n * Copyright 2007 ZXing authors\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 *Encapsulates a set of error-correction blocks in one symbol version. Most versions will\n * use blocks of differing sizes within one version, so, this encapsulates the parameters for\n * each set of blocks. It also holds the number of error-correction codewords per block since it\n * will be the same across all blocks within one version.
\n */\nvar ECBlocks = /** @class */ (function () {\n function ECBlocks(ecCodewords, ecBlocks1, ecBlocks2) {\n this.ecCodewords = ecCodewords;\n this.ecBlocks = [ecBlocks1];\n ecBlocks2 && this.ecBlocks.push(ecBlocks2);\n }\n ECBlocks.prototype.getECCodewords = function () {\n return this.ecCodewords;\n };\n ECBlocks.prototype.getECBlocks = function () {\n return this.ecBlocks;\n };\n return ECBlocks;\n}());\nexport { ECBlocks };\n/**\n *Encapsulates the parameters for one error-correction block in one symbol version.\n * This includes the number of data codewords, and the number of times a block with these\n * parameters is used consecutively in the Data Matrix code version's format.
\n */\nvar ECB = /** @class */ (function () {\n function ECB(count, dataCodewords) {\n this.count = count;\n this.dataCodewords = dataCodewords;\n }\n ECB.prototype.getCount = function () {\n return this.count;\n };\n ECB.prototype.getDataCodewords = function () {\n return this.dataCodewords;\n };\n return ECB;\n}());\nexport { ECB };\n/**\n * The Version object encapsulates attributes about a particular\n * size Data Matrix Code.\n *\n * @author bbrown@google.com (Brian Brown)\n */\nvar Version = /** @class */ (function () {\n function Version(versionNumber, symbolSizeRows, symbolSizeColumns, dataRegionSizeRows, dataRegionSizeColumns, ecBlocks) {\n var e_1, _a;\n this.versionNumber = versionNumber;\n this.symbolSizeRows = symbolSizeRows;\n this.symbolSizeColumns = symbolSizeColumns;\n this.dataRegionSizeRows = dataRegionSizeRows;\n this.dataRegionSizeColumns = dataRegionSizeColumns;\n this.ecBlocks = ecBlocks;\n // Calculate the total number of codewords\n var total = 0;\n var ecCodewords = ecBlocks.getECCodewords();\n var ecbArray = ecBlocks.getECBlocks();\n try {\n for (var ecbArray_1 = __values(ecbArray), ecbArray_1_1 = ecbArray_1.next(); !ecbArray_1_1.done; ecbArray_1_1 = ecbArray_1.next()) {\n var ecBlock = ecbArray_1_1.value;\n total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (ecbArray_1_1 && !ecbArray_1_1.done && (_a = ecbArray_1.return)) _a.call(ecbArray_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n this.totalCodewords = total;\n }\n Version.prototype.getVersionNumber = function () {\n return this.versionNumber;\n };\n Version.prototype.getSymbolSizeRows = function () {\n return this.symbolSizeRows;\n };\n Version.prototype.getSymbolSizeColumns = function () {\n return this.symbolSizeColumns;\n };\n Version.prototype.getDataRegionSizeRows = function () {\n return this.dataRegionSizeRows;\n };\n Version.prototype.getDataRegionSizeColumns = function () {\n return this.dataRegionSizeColumns;\n };\n Version.prototype.getTotalCodewords = function () {\n return this.totalCodewords;\n };\n Version.prototype.getECBlocks = function () {\n return this.ecBlocks;\n };\n /**\n *Deduces version information from Data Matrix dimensions.
\n *\n * @param numRows Number of rows in modules\n * @param numColumns Number of columns in modules\n * @return Version for a Data Matrix Code of those dimensions\n * @throws FormatException if dimensions do correspond to a valid Data Matrix size\n */\n Version.getVersionForDimensions = function (numRows, numColumns) {\n var e_2, _a;\n if ((numRows & 0x01) !== 0 || (numColumns & 0x01) !== 0) {\n throw new FormatException();\n }\n try {\n for (var _b = __values(Version.VERSIONS), _c = _b.next(); !_c.done; _c = _b.next()) {\n var version = _c.value;\n if (version.symbolSizeRows === numRows && version.symbolSizeColumns === numColumns) {\n return version;\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_2) throw e_2.error; }\n }\n throw new FormatException();\n };\n // @Override\n Version.prototype.toString = function () {\n return '' + this.versionNumber;\n };\n /**\n * See ISO 16022:2006 5.5.1 Table 7\n */\n Version.buildVersions = function () {\n return [\n new Version(1, 10, 10, 8, 8, new ECBlocks(5, new ECB(1, 3))),\n new Version(2, 12, 12, 10, 10, new ECBlocks(7, new ECB(1, 5))),\n new Version(3, 14, 14, 12, 12, new ECBlocks(10, new ECB(1, 8))),\n new Version(4, 16, 16, 14, 14, new ECBlocks(12, new ECB(1, 12))),\n new Version(5, 18, 18, 16, 16, new ECBlocks(14, new ECB(1, 18))),\n new Version(6, 20, 20, 18, 18, new ECBlocks(18, new ECB(1, 22))),\n new Version(7, 22, 22, 20, 20, new ECBlocks(20, new ECB(1, 30))),\n new Version(8, 24, 24, 22, 22, new ECBlocks(24, new ECB(1, 36))),\n new Version(9, 26, 26, 24, 24, new ECBlocks(28, new ECB(1, 44))),\n new Version(10, 32, 32, 14, 14, new ECBlocks(36, new ECB(1, 62))),\n new Version(11, 36, 36, 16, 16, new ECBlocks(42, new ECB(1, 86))),\n new Version(12, 40, 40, 18, 18, new ECBlocks(48, new ECB(1, 114))),\n new Version(13, 44, 44, 20, 20, new ECBlocks(56, new ECB(1, 144))),\n new Version(14, 48, 48, 22, 22, new ECBlocks(68, new ECB(1, 174))),\n new Version(15, 52, 52, 24, 24, new ECBlocks(42, new ECB(2, 102))),\n new Version(16, 64, 64, 14, 14, new ECBlocks(56, new ECB(2, 140))),\n new Version(17, 72, 72, 16, 16, new ECBlocks(36, new ECB(4, 92))),\n new Version(18, 80, 80, 18, 18, new ECBlocks(48, new ECB(4, 114))),\n new Version(19, 88, 88, 20, 20, new ECBlocks(56, new ECB(4, 144))),\n new Version(20, 96, 96, 22, 22, new ECBlocks(68, new ECB(4, 174))),\n new Version(21, 104, 104, 24, 24, new ECBlocks(56, new ECB(6, 136))),\n new Version(22, 120, 120, 18, 18, new ECBlocks(68, new ECB(6, 175))),\n new Version(23, 132, 132, 20, 20, new ECBlocks(62, new ECB(8, 163))),\n new Version(24, 144, 144, 22, 22, new ECBlocks(62, new ECB(8, 156), new ECB(2, 155))),\n new Version(25, 8, 18, 6, 16, new ECBlocks(7, new ECB(1, 5))),\n new Version(26, 8, 32, 6, 14, new ECBlocks(11, new ECB(1, 10))),\n new Version(27, 12, 26, 10, 24, new ECBlocks(14, new ECB(1, 16))),\n new Version(28, 12, 36, 10, 16, new ECBlocks(18, new ECB(1, 22))),\n new Version(29, 16, 36, 14, 16, new ECBlocks(24, new ECB(1, 32))),\n new Version(30, 16, 48, 14, 22, new ECBlocks(28, new ECB(1, 49)))\n ];\n };\n Version.VERSIONS = Version.buildVersions();\n return Version;\n}());\nexport default Version;\n","import WhiteRectangleDetector from '../../common/detector/WhiteRectangleDetector';\nimport DetectorResult from '../../common/DetectorResult';\nimport GridSamplerInstance from '../../common/GridSamplerInstance';\nimport NotFoundException from '../../NotFoundException';\nimport ResultPoint from '../../ResultPoint';\n/*\n * Copyright 2008 ZXing authors\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 *Encapsulates logic that can detect a Data Matrix Code in an image, even if the Data Matrix Code\n * is rotated or skewed, or partially obscured.
\n *\n * @author Sean Owen\n */\nvar Detector = /** @class */ (function () {\n function Detector(image) {\n this.image = image;\n this.rectangleDetector = new WhiteRectangleDetector(this.image);\n }\n /**\n *Detects a Data Matrix Code in an image.
\n *\n * @return {@link DetectorResult} encapsulating results of detecting a Data Matrix Code\n * @throws NotFoundException if no Data Matrix Code can be found\n */\n Detector.prototype.detect = function () {\n var cornerPoints = this.rectangleDetector.detect();\n var points = this.detectSolid1(cornerPoints);\n points = this.detectSolid2(points);\n points[3] = this.correctTopRight(points);\n if (!points[3]) {\n throw new NotFoundException();\n }\n points = this.shiftToModuleCenter(points);\n var topLeft = points[0];\n var bottomLeft = points[1];\n var bottomRight = points[2];\n var topRight = points[3];\n var dimensionTop = this.transitionsBetween(topLeft, topRight) + 1;\n var dimensionRight = this.transitionsBetween(bottomRight, topRight) + 1;\n if ((dimensionTop & 0x01) === 1) {\n dimensionTop += 1;\n }\n if ((dimensionRight & 0x01) === 1) {\n dimensionRight += 1;\n }\n if (4 * dimensionTop < 7 * dimensionRight && 4 * dimensionRight < 7 * dimensionTop) {\n // The matrix is square\n dimensionTop = dimensionRight = Math.max(dimensionTop, dimensionRight);\n }\n var bits = Detector.sampleGrid(this.image, topLeft, bottomLeft, bottomRight, topRight, dimensionTop, dimensionRight);\n return new DetectorResult(bits, [topLeft, bottomLeft, bottomRight, topRight]);\n };\n Detector.shiftPoint = function (point, to, div) {\n var x = (to.getX() - point.getX()) / (div + 1);\n var y = (to.getY() - point.getY()) / (div + 1);\n return new ResultPoint(point.getX() + x, point.getY() + y);\n };\n Detector.moveAway = function (point, fromX, fromY) {\n var x = point.getX();\n var y = point.getY();\n if (x < fromX) {\n x -= 1;\n }\n else {\n x += 1;\n }\n if (y < fromY) {\n y -= 1;\n }\n else {\n y += 1;\n }\n return new ResultPoint(x, y);\n };\n /**\n * Detect a solid side which has minimum transition.\n */\n Detector.prototype.detectSolid1 = function (cornerPoints) {\n // 0 2\n // 1 3\n var pointA = cornerPoints[0];\n var pointB = cornerPoints[1];\n var pointC = cornerPoints[3];\n var pointD = cornerPoints[2];\n var trAB = this.transitionsBetween(pointA, pointB);\n var trBC = this.transitionsBetween(pointB, pointC);\n var trCD = this.transitionsBetween(pointC, pointD);\n var trDA = this.transitionsBetween(pointD, pointA);\n // 0..3\n // : :\n // 1--2\n var min = trAB;\n var points = [pointD, pointA, pointB, pointC];\n if (min > trBC) {\n min = trBC;\n points[0] = pointA;\n points[1] = pointB;\n points[2] = pointC;\n points[3] = pointD;\n }\n if (min > trCD) {\n min = trCD;\n points[0] = pointB;\n points[1] = pointC;\n points[2] = pointD;\n points[3] = pointA;\n }\n if (min > trDA) {\n points[0] = pointC;\n points[1] = pointD;\n points[2] = pointA;\n points[3] = pointB;\n }\n return points;\n };\n /**\n * Detect a second solid side next to first solid side.\n */\n Detector.prototype.detectSolid2 = function (points) {\n // A..D\n // : :\n // B--C\n var pointA = points[0];\n var pointB = points[1];\n var pointC = points[2];\n var pointD = points[3];\n // Transition detection on the edge is not stable.\n // To safely detect, shift the points to the module center.\n var tr = this.transitionsBetween(pointA, pointD);\n var pointBs = Detector.shiftPoint(pointB, pointC, (tr + 1) * 4);\n var pointCs = Detector.shiftPoint(pointC, pointB, (tr + 1) * 4);\n var trBA = this.transitionsBetween(pointBs, pointA);\n var trCD = this.transitionsBetween(pointCs, pointD);\n // 0..3\n // | :\n // 1--2\n if (trBA < trCD) {\n // solid sides: A-B-C\n points[0] = pointA;\n points[1] = pointB;\n points[2] = pointC;\n points[3] = pointD;\n }\n else {\n // solid sides: B-C-D\n points[0] = pointB;\n points[1] = pointC;\n points[2] = pointD;\n points[3] = pointA;\n }\n return points;\n };\n /**\n * Calculates the corner position of the white top right module.\n */\n Detector.prototype.correctTopRight = function (points) {\n // A..D\n // | :\n // B--C\n var pointA = points[0];\n var pointB = points[1];\n var pointC = points[2];\n var pointD = points[3];\n // shift points for safe transition detection.\n var trTop = this.transitionsBetween(pointA, pointD);\n var trRight = this.transitionsBetween(pointB, pointD);\n var pointAs = Detector.shiftPoint(pointA, pointB, (trRight + 1) * 4);\n var pointCs = Detector.shiftPoint(pointC, pointB, (trTop + 1) * 4);\n trTop = this.transitionsBetween(pointAs, pointD);\n trRight = this.transitionsBetween(pointCs, pointD);\n var candidate1 = new ResultPoint(pointD.getX() + (pointC.getX() - pointB.getX()) / (trTop + 1), pointD.getY() + (pointC.getY() - pointB.getY()) / (trTop + 1));\n var candidate2 = new ResultPoint(pointD.getX() + (pointA.getX() - pointB.getX()) / (trRight + 1), pointD.getY() + (pointA.getY() - pointB.getY()) / (trRight + 1));\n if (!this.isValid(candidate1)) {\n if (this.isValid(candidate2)) {\n return candidate2;\n }\n return null;\n }\n if (!this.isValid(candidate2)) {\n return candidate1;\n }\n var sumc1 = this.transitionsBetween(pointAs, candidate1) + this.transitionsBetween(pointCs, candidate1);\n var sumc2 = this.transitionsBetween(pointAs, candidate2) + this.transitionsBetween(pointCs, candidate2);\n if (sumc1 > sumc2) {\n return candidate1;\n }\n else {\n return candidate2;\n }\n };\n /**\n * Shift the edge points to the module center.\n */\n Detector.prototype.shiftToModuleCenter = function (points) {\n // A..D\n // | :\n // B--C\n var pointA = points[0];\n var pointB = points[1];\n var pointC = points[2];\n var pointD = points[3];\n // calculate pseudo dimensions\n var dimH = this.transitionsBetween(pointA, pointD) + 1;\n var dimV = this.transitionsBetween(pointC, pointD) + 1;\n // shift points for safe dimension detection\n var pointAs = Detector.shiftPoint(pointA, pointB, dimV * 4);\n var pointCs = Detector.shiftPoint(pointC, pointB, dimH * 4);\n // calculate more precise dimensions\n dimH = this.transitionsBetween(pointAs, pointD) + 1;\n dimV = this.transitionsBetween(pointCs, pointD) + 1;\n if ((dimH & 0x01) === 1) {\n dimH += 1;\n }\n if ((dimV & 0x01) === 1) {\n dimV += 1;\n }\n // WhiteRectangleDetector returns points inside of the rectangle.\n // I want points on the edges.\n var centerX = (pointA.getX() + pointB.getX() + pointC.getX() + pointD.getX()) / 4;\n var centerY = (pointA.getY() + pointB.getY() + pointC.getY() + pointD.getY()) / 4;\n pointA = Detector.moveAway(pointA, centerX, centerY);\n pointB = Detector.moveAway(pointB, centerX, centerY);\n pointC = Detector.moveAway(pointC, centerX, centerY);\n pointD = Detector.moveAway(pointD, centerX, centerY);\n var pointBs;\n var pointDs;\n // shift points to the center of each modules\n pointAs = Detector.shiftPoint(pointA, pointB, dimV * 4);\n pointAs = Detector.shiftPoint(pointAs, pointD, dimH * 4);\n pointBs = Detector.shiftPoint(pointB, pointA, dimV * 4);\n pointBs = Detector.shiftPoint(pointBs, pointC, dimH * 4);\n pointCs = Detector.shiftPoint(pointC, pointD, dimV * 4);\n pointCs = Detector.shiftPoint(pointCs, pointB, dimH * 4);\n pointDs = Detector.shiftPoint(pointD, pointC, dimV * 4);\n pointDs = Detector.shiftPoint(pointDs, pointA, dimH * 4);\n return [pointAs, pointBs, pointCs, pointDs];\n };\n Detector.prototype.isValid = function (p) {\n return p.getX() >= 0 && p.getX() < this.image.getWidth() && p.getY() > 0 && p.getY() < this.image.getHeight();\n };\n Detector.sampleGrid = function (image, topLeft, bottomLeft, bottomRight, topRight, dimensionX, dimensionY) {\n var sampler = GridSamplerInstance.getInstance();\n return sampler.sampleGrid(image, dimensionX, dimensionY, 0.5, 0.5, dimensionX - 0.5, 0.5, dimensionX - 0.5, dimensionY - 0.5, 0.5, dimensionY - 0.5, topLeft.getX(), topLeft.getY(), topRight.getX(), topRight.getY(), bottomRight.getX(), bottomRight.getY(), bottomLeft.getX(), bottomLeft.getY());\n };\n /**\n * Counts the number of black/white transitions between two points, using something like Bresenham's algorithm.\n */\n Detector.prototype.transitionsBetween = function (from, to) {\n // See QR Code Detector, sizeOfBlackWhiteBlackRun()\n var fromX = Math.trunc(from.getX());\n var fromY = Math.trunc(from.getY());\n var toX = Math.trunc(to.getX());\n var toY = Math.trunc(to.getY());\n var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);\n if (steep) {\n var temp = fromX;\n fromX = fromY;\n fromY = temp;\n temp = toX;\n toX = toY;\n toY = temp;\n }\n var dx = Math.abs(toX - fromX);\n var dy = Math.abs(toY - fromY);\n var error = -dx / 2;\n var ystep = fromY < toY ? 1 : -1;\n var xstep = fromX < toX ? 1 : -1;\n var transitions = 0;\n var inBlack = this.image.get(steep ? fromY : fromX, steep ? fromX : fromY);\n for (var x = fromX, y = fromY; x !== toX; x += xstep) {\n var isBlack = this.image.get(steep ? y : x, steep ? x : y);\n if (isBlack !== inBlack) {\n transitions++;\n inBlack = isBlack;\n }\n error += dy;\n if (error > 0) {\n if (y === toY) {\n break;\n }\n y += ystep;\n error -= dx;\n }\n }\n return transitions;\n };\n return Detector;\n}());\nexport default Detector;\n","import { ASCII_ENCODATION, BASE256_ENCODATION, C40_ENCODATION, EDIFACT_ENCODATION, LATCH_TO_ANSIX12, LATCH_TO_BASE256, LATCH_TO_C40, LATCH_TO_EDIFACT, LATCH_TO_TEXT, TEXT_ENCODATION, UPPER_SHIFT, X12_ENCODATION, } from './constants';\n// tslint:disable-next-line:no-circular-imports\nimport HighLevelEncoder from './HighLevelEncoder';\nvar ASCIIEncoder = /** @class */ (function () {\n function ASCIIEncoder() {\n }\n ASCIIEncoder.prototype.getEncodingMode = function () {\n return ASCII_ENCODATION;\n };\n ASCIIEncoder.prototype.encode = function (context) {\n // step B\n var n = HighLevelEncoder.determineConsecutiveDigitCount(context.getMessage(), context.pos);\n if (n >= 2) {\n context.writeCodeword(this.encodeASCIIDigits(context.getMessage().charCodeAt(context.pos), context.getMessage().charCodeAt(context.pos + 1)));\n context.pos += 2;\n }\n else {\n var c = context.getCurrentChar();\n var newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());\n if (newMode !== this.getEncodingMode()) {\n switch (newMode) {\n case BASE256_ENCODATION:\n context.writeCodeword(LATCH_TO_BASE256);\n context.signalEncoderChange(BASE256_ENCODATION);\n return;\n case C40_ENCODATION:\n context.writeCodeword(LATCH_TO_C40);\n context.signalEncoderChange(C40_ENCODATION);\n return;\n case X12_ENCODATION:\n context.writeCodeword(LATCH_TO_ANSIX12);\n context.signalEncoderChange(X12_ENCODATION);\n break;\n case TEXT_ENCODATION:\n context.writeCodeword(LATCH_TO_TEXT);\n context.signalEncoderChange(TEXT_ENCODATION);\n break;\n case EDIFACT_ENCODATION:\n context.writeCodeword(LATCH_TO_EDIFACT);\n context.signalEncoderChange(EDIFACT_ENCODATION);\n break;\n default:\n throw new Error('Illegal mode: ' + newMode);\n }\n }\n else if (HighLevelEncoder.isExtendedASCII(c)) {\n context.writeCodeword(UPPER_SHIFT);\n context.writeCodeword(c - 128 + 1);\n context.pos++;\n }\n else {\n context.writeCodeword(c + 1);\n context.pos++;\n }\n }\n };\n ASCIIEncoder.prototype.encodeASCIIDigits = function (digit1, digit2) {\n if (HighLevelEncoder.isDigit(digit1) && HighLevelEncoder.isDigit(digit2)) {\n var num = (digit1 - 48) * 10 + (digit2 - 48);\n return num + 130;\n }\n throw new Error('not digits: ' + digit1 + digit2);\n };\n return ASCIIEncoder;\n}());\nexport { ASCIIEncoder };\n","import StringUtils from '../../common/StringUtils';\nimport StringBuilder from '../../util/StringBuilder';\nimport HighLevelEncoder from './HighLevelEncoder';\nimport { BASE256_ENCODATION, ASCII_ENCODATION } from './constants';\nvar Base256Encoder = /** @class */ (function () {\n function Base256Encoder() {\n }\n Base256Encoder.prototype.getEncodingMode = function () {\n return BASE256_ENCODATION;\n };\n Base256Encoder.prototype.encode = function (context) {\n var buffer = new StringBuilder();\n buffer.append(0); // Initialize length field\n while (context.hasMoreCharacters()) {\n var c = context.getCurrentChar();\n buffer.append(c);\n context.pos++;\n var newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());\n if (newMode !== this.getEncodingMode()) {\n // Return to ASCII encodation, which will actually handle latch to new mode\n context.signalEncoderChange(ASCII_ENCODATION);\n break;\n }\n }\n var dataCount = buffer.length() - 1;\n var lengthFieldSize = 1;\n var currentSize = context.getCodewordCount() + dataCount + lengthFieldSize;\n context.updateSymbolInfo(currentSize);\n var mustPad = context.getSymbolInfo().getDataCapacity() - currentSize > 0;\n if (context.hasMoreCharacters() || mustPad) {\n if (dataCount <= 249) {\n buffer.setCharAt(0, StringUtils.getCharAt(dataCount));\n }\n else if (dataCount <= 1555) {\n buffer.setCharAt(0, StringUtils.getCharAt(Math.floor(dataCount / 250) + 249));\n buffer.insert(1, StringUtils.getCharAt(dataCount % 250));\n }\n else {\n throw new Error('Message length not in valid ranges: ' + dataCount);\n }\n }\n for (var i = 0, c = buffer.length(); i < c; i++) {\n context.writeCodeword(this.randomize255State(buffer.charAt(i).charCodeAt(0), context.getCodewordCount() + 1));\n }\n };\n Base256Encoder.prototype.randomize255State = function (ch, codewordPosition) {\n var pseudoRandom = ((149 * codewordPosition) % 255) + 1;\n var tempVariable = ch + pseudoRandom;\n if (tempVariable <= 255) {\n return tempVariable;\n }\n else {\n return tempVariable - 256;\n }\n };\n return Base256Encoder;\n}());\nexport { Base256Encoder };\n","import StringBuilder from '../../util/StringBuilder';\nimport HighLevelEncoder from './HighLevelEncoder';\nimport { C40_ENCODATION, LATCH_TO_C40, ASCII_ENCODATION, C40_UNLATCH, } from './constants';\nvar C40Encoder = /** @class */ (function () {\n function C40Encoder() {\n }\n C40Encoder.prototype.getEncodingMode = function () {\n return C40_ENCODATION;\n };\n C40Encoder.prototype.encodeMaximal = function (context) {\n var buffer = new StringBuilder();\n var lastCharSize = 0;\n var backtrackStartPosition = context.pos;\n var backtrackBufferLength = 0;\n while (context.hasMoreCharacters()) {\n var c = context.getCurrentChar();\n context.pos++;\n lastCharSize = this.encodeChar(c, buffer);\n if (buffer.length() % 3 === 0) {\n backtrackStartPosition = context.pos;\n backtrackBufferLength = buffer.length();\n }\n }\n if (backtrackBufferLength !== buffer.length()) {\n var unwritten = Math.floor((buffer.length() / 3) * 2);\n var curCodewordCount = Math.floor(context.getCodewordCount() + unwritten + 1); // +1 for the latch to C40\n context.updateSymbolInfo(curCodewordCount);\n var available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;\n var rest = Math.floor(buffer.length() % 3);\n if ((rest === 2 && available !== 2) ||\n (rest === 1 && (lastCharSize > 3 || available !== 1))) {\n // buffer.setLength(backtrackBufferLength);\n context.pos = backtrackStartPosition;\n }\n }\n if (buffer.length() > 0) {\n context.writeCodeword(LATCH_TO_C40);\n }\n this.handleEOD(context, buffer);\n };\n C40Encoder.prototype.encode = function (context) {\n // step C\n var buffer = new StringBuilder();\n while (context.hasMoreCharacters()) {\n var c = context.getCurrentChar();\n context.pos++;\n var lastCharSize = this.encodeChar(c, buffer);\n var unwritten = Math.floor(buffer.length() / 3) * 2;\n var curCodewordCount = context.getCodewordCount() + unwritten;\n context.updateSymbolInfo(curCodewordCount);\n var available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;\n if (!context.hasMoreCharacters()) {\n // Avoid having a single C40 value in the last triplet\n var removed = new StringBuilder();\n if (buffer.length() % 3 === 2 && available !== 2) {\n lastCharSize = this.backtrackOneCharacter(context, buffer, removed, lastCharSize);\n }\n while (buffer.length() % 3 === 1 &&\n (lastCharSize > 3 || available !== 1)) {\n lastCharSize = this.backtrackOneCharacter(context, buffer, removed, lastCharSize);\n }\n break;\n }\n var count = buffer.length();\n if (count % 3 === 0) {\n var newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());\n if (newMode !== this.getEncodingMode()) {\n // Return to ASCII encodation, which will actually handle latch to new mode\n context.signalEncoderChange(ASCII_ENCODATION);\n break;\n }\n }\n }\n this.handleEOD(context, buffer);\n };\n C40Encoder.prototype.backtrackOneCharacter = function (context, buffer, removed, lastCharSize) {\n var count = buffer.length();\n var test = buffer.toString().substring(0, count - lastCharSize);\n buffer.setLengthToZero();\n buffer.append(test);\n // buffer.delete(count - lastCharSize, count);\n /*for (let i = count - lastCharSize; i < count; i++) {\n buffer.deleteCharAt(i);\n }*/\n context.pos--;\n var c = context.getCurrentChar();\n lastCharSize = this.encodeChar(c, removed);\n context.resetSymbolInfo(); // Deal with possible reduction in symbol size\n return lastCharSize;\n };\n C40Encoder.prototype.writeNextTriplet = function (context, buffer) {\n context.writeCodewords(this.encodeToCodewords(buffer.toString()));\n var test = buffer.toString().substring(3);\n buffer.setLengthToZero();\n buffer.append(test);\n // buffer.delete(0, 3);\n /*for (let i = 0; i < 3; i++) {\n buffer.deleteCharAt(i);\n }*/\n };\n /**\n * Handle \"end of data\" situations\n *\n * @param context the encoder context\n * @param buffer the buffer with the remaining encoded characters\n */\n C40Encoder.prototype.handleEOD = function (context, buffer) {\n var unwritten = Math.floor((buffer.length() / 3) * 2);\n var rest = buffer.length() % 3;\n var curCodewordCount = context.getCodewordCount() + unwritten;\n context.updateSymbolInfo(curCodewordCount);\n var available = context.getSymbolInfo().getDataCapacity() - curCodewordCount;\n if (rest === 2) {\n buffer.append('\\0'); // Shift 1\n while (buffer.length() >= 3) {\n this.writeNextTriplet(context, buffer);\n }\n if (context.hasMoreCharacters()) {\n context.writeCodeword(C40_UNLATCH);\n }\n }\n else if (available === 1 && rest === 1) {\n while (buffer.length() >= 3) {\n this.writeNextTriplet(context, buffer);\n }\n if (context.hasMoreCharacters()) {\n context.writeCodeword(C40_UNLATCH);\n }\n // else no unlatch\n context.pos--;\n }\n else if (rest === 0) {\n while (buffer.length() >= 3) {\n this.writeNextTriplet(context, buffer);\n }\n if (available > 0 || context.hasMoreCharacters()) {\n context.writeCodeword(C40_UNLATCH);\n }\n }\n else {\n throw new Error('Unexpected case. Please report!');\n }\n context.signalEncoderChange(ASCII_ENCODATION);\n };\n C40Encoder.prototype.encodeChar = function (c, sb) {\n if (c === ' '.charCodeAt(0)) {\n sb.append(3);\n return 1;\n }\n if (c >= '0'.charCodeAt(0) && c <= '9'.charCodeAt(0)) {\n sb.append(c - 48 + 4);\n return 1;\n }\n if (c >= 'A'.charCodeAt(0) && c <= 'Z'.charCodeAt(0)) {\n sb.append(c - 65 + 14);\n return 1;\n }\n if (c < ' '.charCodeAt(0)) {\n sb.append(0); // Shift 1 Set\n sb.append(c);\n return 2;\n }\n if (c <= '/'.charCodeAt(0)) {\n sb.append(1); // Shift 2 Set\n sb.append(c - 33);\n return 2;\n }\n if (c <= '@'.charCodeAt(0)) {\n sb.append(1); // Shift 2 Set\n sb.append(c - 58 + 15);\n return 2;\n }\n if (c <= '_'.charCodeAt(0)) {\n sb.append(1); // Shift 2 Set\n sb.append(c - 91 + 22);\n return 2;\n }\n if (c <= 127) {\n sb.append(2); // Shift 3 Set\n sb.append(c - 96);\n return 2;\n }\n sb.append(1 + \"\\u001E\"); // Shift 2, Upper Shift\n var len = 2;\n len += this.encodeChar(c - 128, sb);\n return len;\n };\n C40Encoder.prototype.encodeToCodewords = function (sb) {\n var v = 1600 * sb.charCodeAt(0) + 40 * sb.charCodeAt(1) + sb.charCodeAt(2) + 1;\n var cw1 = v / 256;\n var cw2 = v % 256;\n var result = new StringBuilder();\n result.append(cw1);\n result.append(cw2);\n return result.toString();\n };\n return C40Encoder;\n}());\nexport { C40Encoder };\n","import Arrays from '../../util/Arrays';\n/**\n * Symbol Character Placement Program. Adapted from Annex M.1 in ISO/IEC 16022:2000(E).\n */\nvar DefaultPlacement = /** @class */ (function () {\n /**\n * Main constructor\n *\n * @param codewords the codewords to place\n * @param numcols the number of columns\n * @param numrows the number of rows\n */\n function DefaultPlacement(codewords, numcols, numrows) {\n this.codewords = codewords;\n this.numcols = numcols;\n this.numrows = numrows;\n this.bits = new Uint8Array(numcols * numrows);\n Arrays.fill(this.bits, 2); // Initialize with \"not set\" value\n }\n DefaultPlacement.prototype.getNumrows = function () {\n return this.numrows;\n };\n DefaultPlacement.prototype.getNumcols = function () {\n return this.numcols;\n };\n DefaultPlacement.prototype.getBits = function () {\n return this.bits;\n };\n DefaultPlacement.prototype.getBit = function (col, row) {\n return this.bits[row * this.numcols + col] === 1;\n };\n DefaultPlacement.prototype.setBit = function (col, row, bit) {\n this.bits[row * this.numcols + col] = bit ? 1 : 0;\n };\n DefaultPlacement.prototype.noBit = function (col, row) {\n return this.bits[row * this.numcols + col] === 2;\n };\n DefaultPlacement.prototype.place = function () {\n var pos = 0;\n var row = 4;\n var col = 0;\n do {\n // repeatedly first check for one of the special corner cases, then...\n if (row === this.numrows && col === 0) {\n this.corner1(pos++);\n }\n if (row === this.numrows - 2 && col === 0 && this.numcols % 4 !== 0) {\n this.corner2(pos++);\n }\n if (row === this.numrows - 2 && col === 0 && this.numcols % 8 === 4) {\n this.corner3(pos++);\n }\n if (row === this.numrows + 4 && col === 2 && this.numcols % 8 === 0) {\n this.corner4(pos++);\n }\n // sweep upward diagonally, inserting successive characters...\n do {\n if (row < this.numrows && col >= 0 && this.noBit(col, row)) {\n this.utah(row, col, pos++);\n }\n row -= 2;\n col += 2;\n } while (row >= 0 && col < this.numcols);\n row++;\n col += 3;\n // and then sweep downward diagonally, inserting successive characters, ...\n do {\n if (row >= 0 && col < this.numcols && this.noBit(col, row)) {\n this.utah(row, col, pos++);\n }\n row += 2;\n col -= 2;\n } while (row < this.numrows && col >= 0);\n row += 3;\n col++;\n // ...until the entire array is scanned\n } while (row < this.numrows || col < this.numcols);\n // Lastly, if the lower right-hand corner is untouched, fill in fixed pattern\n if (this.noBit(this.numcols - 1, this.numrows - 1)) {\n this.setBit(this.numcols - 1, this.numrows - 1, true);\n this.setBit(this.numcols - 2, this.numrows - 2, true);\n }\n };\n DefaultPlacement.prototype.module = function (row, col, pos, bit) {\n if (row < 0) {\n row += this.numrows;\n col += 4 - ((this.numrows + 4) % 8);\n }\n if (col < 0) {\n col += this.numcols;\n row += 4 - ((this.numcols + 4) % 8);\n }\n // Note the conversion:\n var v = this.codewords.charCodeAt(pos);\n v &= 1 << (8 - bit);\n this.setBit(col, row, v !== 0);\n };\n /**\n * Places the 8 bits of a utah-shaped symbol character in ECC200.\n *\n * @param row the row\n * @param col the column\n * @param pos character position\n */\n DefaultPlacement.prototype.utah = function (row, col, pos) {\n this.module(row - 2, col - 2, pos, 1);\n this.module(row - 2, col - 1, pos, 2);\n this.module(row - 1, col - 2, pos, 3);\n this.module(row - 1, col - 1, pos, 4);\n this.module(row - 1, col, pos, 5);\n this.module(row, col - 2, pos, 6);\n this.module(row, col - 1, pos, 7);\n this.module(row, col, pos, 8);\n };\n DefaultPlacement.prototype.corner1 = function (pos) {\n this.module(this.numrows - 1, 0, pos, 1);\n this.module(this.numrows - 1, 1, pos, 2);\n this.module(this.numrows - 1, 2, pos, 3);\n this.module(0, this.numcols - 2, pos, 4);\n this.module(0, this.numcols - 1, pos, 5);\n this.module(1, this.numcols - 1, pos, 6);\n this.module(2, this.numcols - 1, pos, 7);\n this.module(3, this.numcols - 1, pos, 8);\n };\n DefaultPlacement.prototype.corner2 = function (pos) {\n this.module(this.numrows - 3, 0, pos, 1);\n this.module(this.numrows - 2, 0, pos, 2);\n this.module(this.numrows - 1, 0, pos, 3);\n this.module(0, this.numcols - 4, pos, 4);\n this.module(0, this.numcols - 3, pos, 5);\n this.module(0, this.numcols - 2, pos, 6);\n this.module(0, this.numcols - 1, pos, 7);\n this.module(1, this.numcols - 1, pos, 8);\n };\n DefaultPlacement.prototype.corner3 = function (pos) {\n this.module(this.numrows - 3, 0, pos, 1);\n this.module(this.numrows - 2, 0, pos, 2);\n this.module(this.numrows - 1, 0, pos, 3);\n this.module(0, this.numcols - 2, pos, 4);\n this.module(0, this.numcols - 1, pos, 5);\n this.module(1, this.numcols - 1, pos, 6);\n this.module(2, this.numcols - 1, pos, 7);\n this.module(3, this.numcols - 1, pos, 8);\n };\n DefaultPlacement.prototype.corner4 = function (pos) {\n this.module(this.numrows - 1, 0, pos, 1);\n this.module(this.numrows - 1, this.numcols - 1, pos, 2);\n this.module(0, this.numcols - 3, pos, 3);\n this.module(0, this.numcols - 2, pos, 4);\n this.module(0, this.numcols - 1, pos, 5);\n this.module(1, this.numcols - 3, pos, 6);\n this.module(1, this.numcols - 2, pos, 7);\n this.module(1, this.numcols - 1, pos, 8);\n };\n return DefaultPlacement;\n}());\nexport default DefaultPlacement;\n","import StringUtils from '../../common/StringUtils';\nimport StringBuilder from '../../util/StringBuilder';\nimport { EDIFACT_ENCODATION, ASCII_ENCODATION } from './constants';\nimport HighLevelEncoder from './HighLevelEncoder';\nvar EdifactEncoder = /** @class */ (function () {\n function EdifactEncoder() {\n }\n EdifactEncoder.prototype.getEncodingMode = function () {\n return EDIFACT_ENCODATION;\n };\n EdifactEncoder.prototype.encode = function (context) {\n // step F\n var buffer = new StringBuilder();\n while (context.hasMoreCharacters()) {\n var c = context.getCurrentChar();\n this.encodeChar(c, buffer);\n context.pos++;\n var count = buffer.length();\n if (count >= 4) {\n context.writeCodewords(this.encodeToCodewords(buffer.toString()));\n var test_1 = buffer.toString().substring(4);\n buffer.setLengthToZero();\n buffer.append(test_1);\n // buffer.delete(0, 4);\n // for (let i = 0; i < 4; i++) {\n // buffer.deleteCharAt(i);\n // }\n var newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());\n if (newMode !== this.getEncodingMode()) {\n // Return to ASCII encodation, which will actually handle latch to new mode\n context.signalEncoderChange(ASCII_ENCODATION);\n break;\n }\n }\n }\n buffer.append(StringUtils.getCharAt(31)); // Unlatch\n this.handleEOD(context, buffer);\n };\n /**\n * Handle \"end of data\" situations\n *\n * @param context the encoder context\n * @param buffer the buffer with the remaining encoded characters\n */\n EdifactEncoder.prototype.handleEOD = function (context, buffer) {\n try {\n var count = buffer.length();\n if (count === 0) {\n return; // Already finished\n }\n if (count === 1) {\n // Only an unlatch at the end\n context.updateSymbolInfo();\n var available = context.getSymbolInfo().getDataCapacity() -\n context.getCodewordCount();\n var remaining = context.getRemainingCharacters();\n // The following two lines are a hack inspired by the 'fix' from https://sourceforge.net/p/barcode4j/svn/221/\n if (remaining > available) {\n context.updateSymbolInfo(context.getCodewordCount() + 1);\n available =\n context.getSymbolInfo().getDataCapacity() -\n context.getCodewordCount();\n }\n if (remaining <= available && available <= 2) {\n return; // No unlatch\n }\n }\n if (count > 4) {\n throw new Error('Count must not exceed 4');\n }\n var restChars = count - 1;\n var encoded = this.encodeToCodewords(buffer.toString());\n var endOfSymbolReached = !context.hasMoreCharacters();\n var restInAscii = endOfSymbolReached && restChars <= 2;\n if (restChars <= 2) {\n context.updateSymbolInfo(context.getCodewordCount() + restChars);\n var available = context.getSymbolInfo().getDataCapacity() -\n context.getCodewordCount();\n if (available >= 3) {\n restInAscii = false;\n context.updateSymbolInfo(context.getCodewordCount() + encoded.length);\n // available = context.symbolInfo.dataCapacity - context.getCodewordCount();\n }\n }\n if (restInAscii) {\n context.resetSymbolInfo();\n context.pos -= restChars;\n }\n else {\n context.writeCodewords(encoded);\n }\n }\n finally {\n context.signalEncoderChange(ASCII_ENCODATION);\n }\n };\n EdifactEncoder.prototype.encodeChar = function (c, sb) {\n if (c >= ' '.charCodeAt(0) && c <= '?'.charCodeAt(0)) {\n sb.append(c);\n }\n else if (c >= '@'.charCodeAt(0) && c <= '^'.charCodeAt(0)) {\n sb.append(StringUtils.getCharAt(c - 64));\n }\n else {\n HighLevelEncoder.illegalCharacter(StringUtils.getCharAt(c));\n }\n };\n EdifactEncoder.prototype.encodeToCodewords = function (sb) {\n var len = sb.length;\n if (len === 0) {\n throw new Error('StringBuilder must not be empty');\n }\n var c1 = sb.charAt(0).charCodeAt(0);\n var c2 = len >= 2 ? sb.charAt(1).charCodeAt(0) : 0;\n var c3 = len >= 3 ? sb.charAt(2).charCodeAt(0) : 0;\n var c4 = len >= 4 ? sb.charAt(3).charCodeAt(0) : 0;\n var v = (c1 << 18) + (c2 << 12) + (c3 << 6) + c4;\n var cw1 = (v >> 16) & 255;\n var cw2 = (v >> 8) & 255;\n var cw3 = v & 255;\n var res = new StringBuilder();\n res.append(cw1);\n if (len >= 2) {\n res.append(cw2);\n }\n if (len >= 3) {\n res.append(cw3);\n }\n return res.toString();\n };\n return EdifactEncoder;\n}());\nexport { EdifactEncoder };\n","import StringBuilder from '../../util/StringBuilder';\nimport SymbolInfo from './SymbolInfo';\nvar EncoderContext = /** @class */ (function () {\n function EncoderContext(msg) {\n this.msg = msg;\n this.pos = 0;\n this.skipAtEnd = 0;\n // From this point on Strings are not Unicode anymore!\n var msgBinary = msg.split('').map(function (c) { return c.charCodeAt(0); });\n var sb = new StringBuilder();\n for (var i = 0, c = msgBinary.length; i < c; i++) {\n var ch = String.fromCharCode(msgBinary[i] & 0xff);\n if (ch === '?' && msg.charAt(i) !== '?') {\n throw new Error('Message contains characters outside ISO-8859-1 encoding.');\n }\n sb.append(ch);\n }\n this.msg = sb.toString(); // Not Unicode here!\n this.shape = 0 /* FORCE_NONE */;\n this.codewords = new StringBuilder();\n this.newEncoding = -1;\n }\n EncoderContext.prototype.setSymbolShape = function (shape) {\n this.shape = shape;\n };\n EncoderContext.prototype.setSizeConstraints = function (minSize, maxSize) {\n this.minSize = minSize;\n this.maxSize = maxSize;\n };\n EncoderContext.prototype.getMessage = function () {\n return this.msg;\n };\n EncoderContext.prototype.setSkipAtEnd = function (count) {\n this.skipAtEnd = count;\n };\n EncoderContext.prototype.getCurrentChar = function () {\n return this.msg.charCodeAt(this.pos);\n };\n EncoderContext.prototype.getCurrent = function () {\n return this.msg.charCodeAt(this.pos);\n };\n EncoderContext.prototype.getCodewords = function () {\n return this.codewords;\n };\n EncoderContext.prototype.writeCodewords = function (codewords) {\n this.codewords.append(codewords);\n };\n EncoderContext.prototype.writeCodeword = function (codeword) {\n this.codewords.append(codeword);\n };\n EncoderContext.prototype.getCodewordCount = function () {\n return this.codewords.length();\n };\n EncoderContext.prototype.getNewEncoding = function () {\n return this.newEncoding;\n };\n EncoderContext.prototype.signalEncoderChange = function (encoding) {\n this.newEncoding = encoding;\n };\n EncoderContext.prototype.resetEncoderSignal = function () {\n this.newEncoding = -1;\n };\n EncoderContext.prototype.hasMoreCharacters = function () {\n return this.pos < this.getTotalMessageCharCount();\n };\n EncoderContext.prototype.getTotalMessageCharCount = function () {\n return this.msg.length - this.skipAtEnd;\n };\n EncoderContext.prototype.getRemainingCharacters = function () {\n return this.getTotalMessageCharCount() - this.pos;\n };\n EncoderContext.prototype.getSymbolInfo = function () {\n return this.symbolInfo;\n };\n EncoderContext.prototype.updateSymbolInfo = function (len) {\n if (len === void 0) { len = this.getCodewordCount(); }\n if (this.symbolInfo == null || len > this.symbolInfo.getDataCapacity()) {\n this.symbolInfo = SymbolInfo.lookup(len, this.shape, this.minSize, this.maxSize, true);\n }\n };\n EncoderContext.prototype.resetSymbolInfo = function () {\n this.symbolInfo = null;\n };\n return EncoderContext;\n}());\nexport { EncoderContext };\n","import StringBuilder from '../../util/StringBuilder';\nimport { ALOG, FACTORS, FACTOR_SETS, LOG } from './constants';\n/**\n * Error Correction Code for ECC200.\n */\nvar ErrorCorrection = /** @class */ (function () {\n function ErrorCorrection() {\n }\n /**\n * Creates the ECC200 error correction for an encoded message.\n *\n * @param codewords the codewords\n * @param symbolInfo information about the symbol to be encoded\n * @return the codewords with interleaved error correction.\n */\n ErrorCorrection.encodeECC200 = function (codewords, symbolInfo) {\n if (codewords.length !== symbolInfo.getDataCapacity()) {\n throw new Error('The number of codewords does not match the selected symbol');\n }\n var sb = new StringBuilder();\n sb.append(codewords);\n var blockCount = symbolInfo.getInterleavedBlockCount();\n if (blockCount === 1) {\n var ecc = this.createECCBlock(codewords, symbolInfo.getErrorCodewords());\n sb.append(ecc);\n }\n else {\n // sb.setLength(sb.capacity());\n var dataSizes = [];\n var errorSizes = [];\n for (var i = 0; i < blockCount; i++) {\n dataSizes[i] = symbolInfo.getDataLengthForInterleavedBlock(i + 1);\n errorSizes[i] = symbolInfo.getErrorLengthForInterleavedBlock(i + 1);\n }\n for (var block = 0; block < blockCount; block++) {\n var temp = new StringBuilder();\n for (var d = block; d < symbolInfo.getDataCapacity(); d += blockCount) {\n temp.append(codewords.charAt(d));\n }\n var ecc = this.createECCBlock(temp.toString(), errorSizes[block]);\n var pos = 0;\n for (var e = block; e < errorSizes[block] * blockCount; e += blockCount) {\n sb.setCharAt(symbolInfo.getDataCapacity() + e, ecc.charAt(pos++));\n }\n }\n }\n return sb.toString();\n };\n ErrorCorrection.createECCBlock = function (codewords, numECWords) {\n var table = -1;\n for (var i = 0; i < FACTOR_SETS.length; i++) {\n if (FACTOR_SETS[i] === numECWords) {\n table = i;\n break;\n }\n }\n if (table < 0) {\n throw new Error('Illegal number of error correction codewords specified: ' + numECWords);\n }\n var poly = FACTORS[table];\n var ecc = [];\n for (var i = 0; i < numECWords; i++) {\n ecc[i] = 0;\n }\n for (var i = 0; i < codewords.length; i++) {\n var m = ecc[numECWords - 1] ^ codewords.charAt(i).charCodeAt(0);\n for (var k = numECWords - 1; k > 0; k--) {\n if (m !== 0 && poly[k] !== 0) {\n ecc[k] = ecc[k - 1] ^ ALOG[(LOG[m] + LOG[poly[k]]) % 255];\n }\n else {\n ecc[k] = ecc[k - 1];\n }\n }\n if (m !== 0 && poly[0] !== 0) {\n ecc[0] = ALOG[(LOG[m] + LOG[poly[0]]) % 255];\n }\n else {\n ecc[0] = 0;\n }\n }\n var eccReversed = [];\n for (var i = 0; i < numECWords; i++) {\n eccReversed[i] = ecc[numECWords - i - 1];\n }\n return eccReversed.map(function (c) { return String.fromCharCode(c); }).join('');\n };\n return ErrorCorrection;\n}());\nexport default ErrorCorrection;\n","// tslint:disable-next-line:no-circular-imports\nimport { ASCIIEncoder } from './ASCIIEncoder';\n// tslint:disable-next-line:no-circular-imports\nimport { Base256Encoder } from './Base256Encoder';\n// tslint:disable-next-line:no-circular-imports\nimport { C40Encoder } from './C40Encoder';\nimport { ASCII_ENCODATION, BASE256_ENCODATION, C40_ENCODATION, EDIFACT_ENCODATION, MACRO_05, MACRO_05_HEADER, MACRO_06, MACRO_06_HEADER, MACRO_TRAILER, PAD, TEXT_ENCODATION, X12_ENCODATION, } from './constants';\n// tslint:disable-next-line:no-circular-imports\nimport { EdifactEncoder } from './EdifactEncoder';\nimport { EncoderContext } from './EncoderContext';\n// tslint:disable-next-line:no-circular-imports\nimport { X12Encoder } from './X12Encoder';\n// tslint:disable-next-line:no-circular-imports\nimport { TextEncoder } from './TextEncoder';\nimport Arrays from '../../util/Arrays';\nimport Integer from '../../util/Integer';\n/**\n * DataMatrix ECC 200 data encoder following the algorithm described in ISO/IEC 16022:200(E) in\n * annex S.\n */\nvar HighLevelEncoder = /** @class */ (function () {\n function HighLevelEncoder() {\n }\n HighLevelEncoder.randomize253State = function (codewordPosition) {\n var pseudoRandom = ((149 * codewordPosition) % 253) + 1;\n var tempVariable = PAD + pseudoRandom;\n return tempVariable <= 254 ? tempVariable : tempVariable - 254;\n };\n /**\n * Performs message encoding of a DataMatrix message using the algorithm described in annex P\n * of ISO/IEC 16022:2000(E).\n *\n * @param msg the message\n * @param shape requested shape. May be {@code SymbolShapeHint.FORCE_NONE},\n * {@code SymbolShapeHint.FORCE_SQUARE} or {@code SymbolShapeHint.FORCE_RECTANGLE}.\n * @param minSize the minimum symbol size constraint or null for no constraint\n * @param maxSize the maximum symbol size constraint or null for no constraint\n * @param forceC40 enforce C40 encoding\n * @return the encoded message (the char values range from 0 to 255)\n */\n HighLevelEncoder.encodeHighLevel = function (msg, shape, minSize, maxSize, forceC40) {\n if (shape === void 0) { shape = 0 /* FORCE_NONE */; }\n if (minSize === void 0) { minSize = null; }\n if (maxSize === void 0) { maxSize = null; }\n if (forceC40 === void 0) { forceC40 = false; }\n // the codewords 0..255 are encoded as Unicode characters\n var c40Encoder = new C40Encoder();\n var encoders = [\n new ASCIIEncoder(),\n c40Encoder,\n new TextEncoder(),\n new X12Encoder(),\n new EdifactEncoder(),\n new Base256Encoder(),\n ];\n var context = new EncoderContext(msg);\n context.setSymbolShape(shape);\n context.setSizeConstraints(minSize, maxSize);\n if (msg.startsWith(MACRO_05_HEADER) && msg.endsWith(MACRO_TRAILER)) {\n context.writeCodeword(MACRO_05);\n context.setSkipAtEnd(2);\n context.pos += MACRO_05_HEADER.length;\n }\n else if (msg.startsWith(MACRO_06_HEADER) && msg.endsWith(MACRO_TRAILER)) {\n context.writeCodeword(MACRO_06);\n context.setSkipAtEnd(2);\n context.pos += MACRO_06_HEADER.length;\n }\n var encodingMode = ASCII_ENCODATION; // Default mode\n if (forceC40) {\n c40Encoder.encodeMaximal(context);\n encodingMode = context.getNewEncoding();\n context.resetEncoderSignal();\n }\n while (context.hasMoreCharacters()) {\n encoders[encodingMode].encode(context);\n if (context.getNewEncoding() >= 0) {\n encodingMode = context.getNewEncoding();\n context.resetEncoderSignal();\n }\n }\n var len = context.getCodewordCount();\n context.updateSymbolInfo();\n var capacity = context.getSymbolInfo().getDataCapacity();\n if (len < capacity &&\n encodingMode !== ASCII_ENCODATION &&\n encodingMode !== BASE256_ENCODATION &&\n encodingMode !== EDIFACT_ENCODATION) {\n context.writeCodeword('\\u00fe'); // Unlatch (254)\n }\n // Padding\n var codewords = context.getCodewords();\n if (codewords.length() < capacity) {\n codewords.append(PAD);\n }\n while (codewords.length() < capacity) {\n codewords.append(this.randomize253State(codewords.length() + 1));\n }\n return context.getCodewords().toString();\n };\n HighLevelEncoder.lookAheadTest = function (msg, startpos, currentMode) {\n var newMode = this.lookAheadTestIntern(msg, startpos, currentMode);\n if (currentMode === X12_ENCODATION && newMode === X12_ENCODATION) {\n var endpos = Math.min(startpos + 3, msg.length);\n for (var i = startpos; i < endpos; i++) {\n if (!this.isNativeX12(msg.charCodeAt(i))) {\n return ASCII_ENCODATION;\n }\n }\n }\n else if (currentMode === EDIFACT_ENCODATION &&\n newMode === EDIFACT_ENCODATION) {\n var endpos = Math.min(startpos + 4, msg.length);\n for (var i = startpos; i < endpos; i++) {\n if (!this.isNativeEDIFACT(msg.charCodeAt(i))) {\n return ASCII_ENCODATION;\n }\n }\n }\n return newMode;\n };\n HighLevelEncoder.lookAheadTestIntern = function (msg, startpos, currentMode) {\n if (startpos >= msg.length) {\n return currentMode;\n }\n var charCounts;\n // step J\n if (currentMode === ASCII_ENCODATION) {\n charCounts = [0, 1, 1, 1, 1, 1.25];\n }\n else {\n charCounts = [1, 2, 2, 2, 2, 2.25];\n charCounts[currentMode] = 0;\n }\n var charsProcessed = 0;\n var mins = new Uint8Array(6);\n var intCharCounts = [];\n while (true) {\n // step K\n if (startpos + charsProcessed === msg.length) {\n Arrays.fill(mins, 0);\n Arrays.fill(intCharCounts, 0);\n var min = this.findMinimums(charCounts, intCharCounts, Integer.MAX_VALUE, mins);\n var minCount = this.getMinimumCount(mins);\n if (intCharCounts[ASCII_ENCODATION] === min) {\n return ASCII_ENCODATION;\n }\n if (minCount === 1) {\n if (mins[BASE256_ENCODATION] > 0) {\n return BASE256_ENCODATION;\n }\n if (mins[EDIFACT_ENCODATION] > 0) {\n return EDIFACT_ENCODATION;\n }\n if (mins[TEXT_ENCODATION] > 0) {\n return TEXT_ENCODATION;\n }\n if (mins[X12_ENCODATION] > 0) {\n return X12_ENCODATION;\n }\n }\n return C40_ENCODATION;\n }\n var c = msg.charCodeAt(startpos + charsProcessed);\n charsProcessed++;\n // step L\n if (this.isDigit(c)) {\n charCounts[ASCII_ENCODATION] += 0.5;\n }\n else if (this.isExtendedASCII(c)) {\n charCounts[ASCII_ENCODATION] = Math.ceil(charCounts[ASCII_ENCODATION]);\n charCounts[ASCII_ENCODATION] += 2.0;\n }\n else {\n charCounts[ASCII_ENCODATION] = Math.ceil(charCounts[ASCII_ENCODATION]);\n charCounts[ASCII_ENCODATION]++;\n }\n // step M\n if (this.isNativeC40(c)) {\n charCounts[C40_ENCODATION] += 2.0 / 3.0;\n }\n else if (this.isExtendedASCII(c)) {\n charCounts[C40_ENCODATION] += 8.0 / 3.0;\n }\n else {\n charCounts[C40_ENCODATION] += 4.0 / 3.0;\n }\n // step N\n if (this.isNativeText(c)) {\n charCounts[TEXT_ENCODATION] += 2.0 / 3.0;\n }\n else if (this.isExtendedASCII(c)) {\n charCounts[TEXT_ENCODATION] += 8.0 / 3.0;\n }\n else {\n charCounts[TEXT_ENCODATION] += 4.0 / 3.0;\n }\n // step O\n if (this.isNativeX12(c)) {\n charCounts[X12_ENCODATION] += 2.0 / 3.0;\n }\n else if (this.isExtendedASCII(c)) {\n charCounts[X12_ENCODATION] += 13.0 / 3.0;\n }\n else {\n charCounts[X12_ENCODATION] += 10.0 / 3.0;\n }\n // step P\n if (this.isNativeEDIFACT(c)) {\n charCounts[EDIFACT_ENCODATION] += 3.0 / 4.0;\n }\n else if (this.isExtendedASCII(c)) {\n charCounts[EDIFACT_ENCODATION] += 17.0 / 4.0;\n }\n else {\n charCounts[EDIFACT_ENCODATION] += 13.0 / 4.0;\n }\n // step Q\n if (this.isSpecialB256(c)) {\n charCounts[BASE256_ENCODATION] += 4.0;\n }\n else {\n charCounts[BASE256_ENCODATION]++;\n }\n // step R\n if (charsProcessed >= 4) {\n Arrays.fill(mins, 0);\n Arrays.fill(intCharCounts, 0);\n this.findMinimums(charCounts, intCharCounts, Integer.MAX_VALUE, mins);\n if (intCharCounts[ASCII_ENCODATION] <\n this.min(intCharCounts[BASE256_ENCODATION], intCharCounts[C40_ENCODATION], intCharCounts[TEXT_ENCODATION], intCharCounts[X12_ENCODATION], intCharCounts[EDIFACT_ENCODATION])) {\n return ASCII_ENCODATION;\n }\n if (intCharCounts[BASE256_ENCODATION] < intCharCounts[ASCII_ENCODATION] ||\n intCharCounts[BASE256_ENCODATION] + 1 <\n this.min(intCharCounts[C40_ENCODATION], intCharCounts[TEXT_ENCODATION], intCharCounts[X12_ENCODATION], intCharCounts[EDIFACT_ENCODATION])) {\n return BASE256_ENCODATION;\n }\n if (intCharCounts[EDIFACT_ENCODATION] + 1 <\n this.min(intCharCounts[BASE256_ENCODATION], intCharCounts[C40_ENCODATION], intCharCounts[TEXT_ENCODATION], intCharCounts[X12_ENCODATION], intCharCounts[ASCII_ENCODATION])) {\n return EDIFACT_ENCODATION;\n }\n if (intCharCounts[TEXT_ENCODATION] + 1 <\n this.min(intCharCounts[BASE256_ENCODATION], intCharCounts[C40_ENCODATION], intCharCounts[EDIFACT_ENCODATION], intCharCounts[X12_ENCODATION], intCharCounts[ASCII_ENCODATION])) {\n return TEXT_ENCODATION;\n }\n if (intCharCounts[X12_ENCODATION] + 1 <\n this.min(intCharCounts[BASE256_ENCODATION], intCharCounts[C40_ENCODATION], intCharCounts[EDIFACT_ENCODATION], intCharCounts[TEXT_ENCODATION], intCharCounts[ASCII_ENCODATION])) {\n return X12_ENCODATION;\n }\n if (intCharCounts[C40_ENCODATION] + 1 <\n this.min(intCharCounts[ASCII_ENCODATION], intCharCounts[BASE256_ENCODATION], intCharCounts[EDIFACT_ENCODATION], intCharCounts[TEXT_ENCODATION])) {\n if (intCharCounts[C40_ENCODATION] < intCharCounts[X12_ENCODATION]) {\n return C40_ENCODATION;\n }\n if (intCharCounts[C40_ENCODATION] === intCharCounts[X12_ENCODATION]) {\n var p = startpos + charsProcessed + 1;\n while (p < msg.length) {\n var tc = msg.charCodeAt(p);\n if (this.isX12TermSep(tc)) {\n return X12_ENCODATION;\n }\n if (!this.isNativeX12(tc)) {\n break;\n }\n p++;\n }\n return C40_ENCODATION;\n }\n }\n }\n }\n };\n HighLevelEncoder.min = function (f1, f2, f3, f4, f5) {\n var val = Math.min(f1, Math.min(f2, Math.min(f3, f4)));\n if (f5 === undefined) {\n return val;\n }\n else {\n return Math.min(val, f5);\n }\n };\n HighLevelEncoder.findMinimums = function (charCounts, intCharCounts, min, mins) {\n for (var i = 0; i < 6; i++) {\n var current = (intCharCounts[i] = Math.ceil(charCounts[i]));\n if (min > current) {\n min = current;\n Arrays.fill(mins, 0);\n }\n if (min === current) {\n mins[i] = mins[i] + 1;\n }\n }\n return min;\n };\n HighLevelEncoder.getMinimumCount = function (mins) {\n var minCount = 0;\n for (var i = 0; i < 6; i++) {\n minCount += mins[i];\n }\n return minCount || 0;\n };\n HighLevelEncoder.isDigit = function (ch) {\n return ch >= '0'.charCodeAt(0) && ch <= '9'.charCodeAt(0);\n };\n HighLevelEncoder.isExtendedASCII = function (ch) {\n return ch >= 128 && ch <= 255;\n };\n HighLevelEncoder.isNativeC40 = function (ch) {\n return (ch === ' '.charCodeAt(0) ||\n (ch >= '0'.charCodeAt(0) && ch <= '9'.charCodeAt(0)) ||\n (ch >= 'A'.charCodeAt(0) && ch <= 'Z'.charCodeAt(0)));\n };\n HighLevelEncoder.isNativeText = function (ch) {\n return (ch === ' '.charCodeAt(0) ||\n (ch >= '0'.charCodeAt(0) && ch <= '9'.charCodeAt(0)) ||\n (ch >= 'a'.charCodeAt(0) && ch <= 'z'.charCodeAt(0)));\n };\n HighLevelEncoder.isNativeX12 = function (ch) {\n return (this.isX12TermSep(ch) ||\n ch === ' '.charCodeAt(0) ||\n (ch >= '0'.charCodeAt(0) && ch <= '9'.charCodeAt(0)) ||\n (ch >= 'A'.charCodeAt(0) && ch <= 'Z'.charCodeAt(0)));\n };\n HighLevelEncoder.isX12TermSep = function (ch) {\n return (ch === 13 || // CR\n ch === '*'.charCodeAt(0) ||\n ch === '>'.charCodeAt(0));\n };\n HighLevelEncoder.isNativeEDIFACT = function (ch) {\n return ch >= ' '.charCodeAt(0) && ch <= '^'.charCodeAt(0);\n };\n HighLevelEncoder.isSpecialB256 = function (ch) {\n return false; // TODO NOT IMPLEMENTED YET!!!\n };\n /**\n * Determines the number of consecutive characters that are encodable using numeric compaction.\n *\n * @param msg the message\n * @param startpos the start position within the message\n * @return the requested character count\n */\n HighLevelEncoder.determineConsecutiveDigitCount = function (msg, startpos) {\n if (startpos === void 0) { startpos = 0; }\n var len = msg.length;\n var idx = startpos;\n while (idx < len && this.isDigit(msg.charCodeAt(idx))) {\n idx++;\n }\n return idx - startpos;\n };\n HighLevelEncoder.illegalCharacter = function (singleCharacter) {\n var hex = Integer.toHexString(singleCharacter.charCodeAt(0));\n hex = '0000'.substring(0, 4 - hex.length) + hex;\n throw new Error('Illegal character: ' + singleCharacter + ' (0x' + hex + ')');\n };\n return HighLevelEncoder;\n}());\nexport default HighLevelEncoder;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nvar __read = (this && this.__read) || function (o, n) {\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\n if (!m) return o;\n var i = m.call(o), r, ar = [], e;\n try {\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\n }\n catch (error) { e = { error: error }; }\n finally {\n try {\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\n }\n finally { if (e) throw e.error; }\n }\n return ar;\n};\nvar __spread = (this && this.__spread) || function () {\n for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i]));\n return ar;\n};\nimport { MACRO_05_HEADER, MACRO_06_HEADER, MACRO_TRAILER, } from './constants';\nimport HighLevelEncoder from './HighLevelEncoder';\nimport { MinimalECIInput } from '../../common/MinimalECIInput';\nimport Integer from '../../util/Integer';\nvar Mode;\n(function (Mode) {\n Mode[Mode[\"ASCII\"] = 0] = \"ASCII\";\n Mode[Mode[\"C40\"] = 1] = \"C40\";\n Mode[Mode[\"TEXT\"] = 2] = \"TEXT\";\n Mode[Mode[\"X12\"] = 3] = \"X12\";\n Mode[Mode[\"EDF\"] = 4] = \"EDF\";\n Mode[Mode[\"B256\"] = 5] = \"B256\";\n})(Mode || (Mode = {}));\nvar C40_SHIFT2_CHARS = [\n '!',\n '\"',\n '#',\n '$',\n '%',\n '&',\n \"'\",\n '(',\n ')',\n '*',\n '+',\n ',',\n '-',\n '.',\n '/',\n ':',\n ';',\n '<',\n '=',\n '>',\n '?',\n '@',\n '[',\n '\\\\',\n ']',\n '^',\n '_',\n];\nvar MinimalEncoder = /** @class */ (function () {\n function MinimalEncoder() {\n }\n MinimalEncoder.isExtendedASCII = function (ch, fnc1) {\n return ch !== fnc1 && ch >= 128 && ch <= 255;\n };\n MinimalEncoder.isInC40Shift1Set = function (ch) {\n return ch <= 31;\n };\n MinimalEncoder.isInC40Shift2Set = function (ch, fnc1) {\n var e_1, _a;\n try {\n for (var C40_SHIFT2_CHARS_1 = __values(C40_SHIFT2_CHARS), C40_SHIFT2_CHARS_1_1 = C40_SHIFT2_CHARS_1.next(); !C40_SHIFT2_CHARS_1_1.done; C40_SHIFT2_CHARS_1_1 = C40_SHIFT2_CHARS_1.next()) {\n var c40Shift2Char = C40_SHIFT2_CHARS_1_1.value;\n if (c40Shift2Char.charCodeAt(0) === ch) {\n return true;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (C40_SHIFT2_CHARS_1_1 && !C40_SHIFT2_CHARS_1_1.done && (_a = C40_SHIFT2_CHARS_1.return)) _a.call(C40_SHIFT2_CHARS_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return ch === fnc1;\n };\n MinimalEncoder.isInTextShift1Set = function (ch) {\n return this.isInC40Shift1Set(ch);\n };\n MinimalEncoder.isInTextShift2Set = function (ch, fnc1) {\n return this.isInC40Shift2Set(ch, fnc1);\n };\n /**\n * Performs message encoding of a DataMatrix message\n *\n * @param msg the message\n * @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm\n * chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority\n * charset to encode any character in the input that can be encoded by it if the charset is among the\n * supported charsets.\n * @param fnc1 denotes the character in the input that represents the FNC1 character or -1 if this is not a GS1\n * bar code. If the value is not -1 then a FNC1 is also prepended.\n * @param shape requested shape.\n * @return the encoded message (the char values range from 0 to 255)\n */\n MinimalEncoder.encodeHighLevel = function (msg, priorityCharset, fnc1, shape) {\n if (priorityCharset === void 0) { priorityCharset = null; }\n if (fnc1 === void 0) { fnc1 = -1; }\n if (shape === void 0) { shape = 0 /* FORCE_NONE */; }\n var macroId = 0;\n if (msg.startsWith(MACRO_05_HEADER) && msg.endsWith(MACRO_TRAILER)) {\n macroId = 5;\n msg = msg.substring(MACRO_05_HEADER.length, msg.length - 2);\n }\n else if (msg.startsWith(MACRO_06_HEADER) && msg.endsWith(MACRO_TRAILER)) {\n macroId = 6;\n msg = msg.substring(MACRO_06_HEADER.length, msg.length - 2);\n }\n return decodeURIComponent(escape(String.fromCharCode.apply(String, __spread(this.encode(msg, priorityCharset, fnc1, shape, macroId)))));\n };\n /**\n * Encodes input minimally and returns an array of the codewords\n *\n * @param input The string to encode\n * @param priorityCharset The preferred {@link Charset}. When the value of the argument is null, the algorithm\n * chooses charsets that leads to a minimal representation. Otherwise the algorithm will use the priority\n * charset to encode any character in the input that can be encoded by it if the charset is among the\n * supported charsets.\n * @param fnc1 denotes the character in the input that represents the FNC1 character or -1 if this is not a GS1\n * bar code. If the value is not -1 then a FNC1 is also prepended.\n * @param shape requested shape.\n * @param macroId Prepends the specified macro function in case that a value of 5 or 6 is specified.\n * @return An array of bytes representing the codewords of a minimal encoding.\n */\n MinimalEncoder.encode = function (input, priorityCharset, fnc1, shape, macroId) {\n return this.encodeMinimally(new Input(input, priorityCharset, fnc1, shape, macroId)).getBytes();\n };\n MinimalEncoder.addEdge = function (edges, edge) {\n var vertexIndex = edge.fromPosition + edge.characterLength;\n if (edges[vertexIndex][edge.getEndMode()] === null ||\n edges[vertexIndex][edge.getEndMode()].cachedTotalSize >\n edge.cachedTotalSize) {\n edges[vertexIndex][edge.getEndMode()] = edge;\n }\n };\n /** @return the number of words in which the string starting at from can be encoded in c40 or text mode.\n * The number of characters encoded is returned in characterLength.\n * The number of characters encoded is also minimal in the sense that the algorithm stops as soon\n * as a character encoding fills a C40 word competely (three C40 values). An exception is at the\n * end of the string where two C40 values are allowed (according to the spec the third c40 value\n * is filled with 0 (Shift 1) in this case).\n */\n MinimalEncoder.getNumberOfC40Words = function (input, from, c40, characterLength) {\n var thirdsCount = 0;\n for (var i = from; i < input.length(); i++) {\n if (input.isECI(i)) {\n characterLength[0] = 0;\n return 0;\n }\n var ci = input.charAt(i);\n if ((c40 && HighLevelEncoder.isNativeC40(ci)) ||\n (!c40 && HighLevelEncoder.isNativeText(ci))) {\n thirdsCount++; // native\n }\n else if (!MinimalEncoder.isExtendedASCII(ci, input.getFNC1Character())) {\n thirdsCount += 2; // shift\n }\n else {\n var asciiValue = ci & 0xff;\n if (asciiValue >= 128 &&\n ((c40 && HighLevelEncoder.isNativeC40(asciiValue - 128)) ||\n (!c40 && HighLevelEncoder.isNativeText(asciiValue - 128)))) {\n thirdsCount += 3; // shift, Upper shift\n }\n else {\n thirdsCount += 4; // shift, Upper shift, shift\n }\n }\n if (thirdsCount % 3 === 0 ||\n ((thirdsCount - 2) % 3 === 0 && i + 1 === input.length())) {\n characterLength[0] = i - from + 1;\n return Math.ceil(thirdsCount / 3.0);\n }\n }\n characterLength[0] = 0;\n return 0;\n };\n MinimalEncoder.addEdges = function (input, edges, from, previous) {\n var e_2, _a;\n if (input.isECI(from)) {\n this.addEdge(edges, new Edge(input, Mode.ASCII, from, 1, previous));\n return;\n }\n var ch = input.charAt(from);\n if (previous === null || previous.getEndMode() !== Mode.EDF) {\n // not possible to unlatch a full EDF edge to something\n // else\n if (HighLevelEncoder.isDigit(ch) &&\n input.haveNCharacters(from, 2) &&\n HighLevelEncoder.isDigit(input.charAt(from + 1))) {\n // two digits ASCII encoded\n this.addEdge(edges, new Edge(input, Mode.ASCII, from, 2, previous));\n }\n else {\n // one ASCII encoded character or an extended character via Upper Shift\n this.addEdge(edges, new Edge(input, Mode.ASCII, from, 1, previous));\n }\n var modes = [Mode.C40, Mode.TEXT];\n try {\n for (var modes_1 = __values(modes), modes_1_1 = modes_1.next(); !modes_1_1.done; modes_1_1 = modes_1.next()) {\n var mode = modes_1_1.value;\n var characterLength = [];\n if (MinimalEncoder.getNumberOfC40Words(input, from, mode === Mode.C40, characterLength) > 0) {\n this.addEdge(edges, new Edge(input, mode, from, characterLength[0], previous));\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (modes_1_1 && !modes_1_1.done && (_a = modes_1.return)) _a.call(modes_1);\n }\n finally { if (e_2) throw e_2.error; }\n }\n if (input.haveNCharacters(from, 3) &&\n HighLevelEncoder.isNativeX12(input.charAt(from)) &&\n HighLevelEncoder.isNativeX12(input.charAt(from + 1)) &&\n HighLevelEncoder.isNativeX12(input.charAt(from + 2))) {\n this.addEdge(edges, new Edge(input, Mode.X12, from, 3, previous));\n }\n this.addEdge(edges, new Edge(input, Mode.B256, from, 1, previous));\n }\n // We create 4 EDF edges, with 1, 2 3 or 4 characters length. The fourth normally doesn't have a latch to ASCII\n // unless it is 2 characters away from the end of the input.\n var i;\n for (i = 0; i < 3; i++) {\n var pos = from + i;\n if (input.haveNCharacters(pos, 1) &&\n HighLevelEncoder.isNativeEDIFACT(input.charAt(pos))) {\n this.addEdge(edges, new Edge(input, Mode.EDF, from, i + 1, previous));\n }\n else {\n break;\n }\n }\n if (i === 3 &&\n input.haveNCharacters(from, 4) &&\n HighLevelEncoder.isNativeEDIFACT(input.charAt(from + 3))) {\n this.addEdge(edges, new Edge(input, Mode.EDF, from, 4, previous));\n }\n };\n MinimalEncoder.encodeMinimally = function (input) {\n /* The minimal encoding is computed by Dijkstra. The acyclic graph is modeled as follows:\n * A vertex represents a combination of a position in the input and an encoding mode where position 0\n * denotes the position left of the first character, 1 the position left of the second character and so on.\n * Likewise the end vertices are located after the last character at position input.length().\n * For any position there might be up to six vertices, one for each of the encoding types ASCII, C40, TEXT, X12,\n * EDF and B256.\n *\n * As an example consider the input string \"ABC123\" then at position 0 there is only one vertex with the default\n * ASCII encodation. At position 3 there might be vertices for the types ASCII, C40, X12, EDF and B256.\n *\n * An edge leading to such a vertex encodes one or more of the characters left of the position that the vertex\n * represents. It encodes the characters in the encoding mode of the vertex that it ends on. In other words,\n * all edges leading to a particular vertex encode the same characters (the length of the suffix can vary) using the same\n * encoding mode.\n * As an example consider the input string \"ABC123\" and the vertex (4,EDF). Possible edges leading to this vertex\n * are:\n * (0,ASCII) --EDF(ABC1)--> (4,EDF)\n * (1,ASCII) --EDF(BC1)--> (4,EDF)\n * (1,B256) --EDF(BC1)--> (4,EDF)\n * (1,EDF) --EDF(BC1)--> (4,EDF)\n * (2,ASCII) --EDF(C1)--> (4,EDF)\n * (2,B256) --EDF(C1)--> (4,EDF)\n * (2,EDF) --EDF(C1)--> (4,EDF)\n * (3,ASCII) --EDF(1)--> (4,EDF)\n * (3,B256) --EDF(1)--> (4,EDF)\n * (3,EDF) --EDF(1)--> (4,EDF)\n * (3,C40) --EDF(1)--> (4,EDF)\n * (3,X12) --EDF(1)--> (4,EDF)\n *\n * The edges leading to a vertex are stored in such a way that there is a fast way to enumerate the edges ending\n * on a particular vertex.\n *\n * The algorithm processes the vertices in order of their position thereby performing the following:\n *\n * For every vertex at position i the algorithm enumerates the edges ending on the vertex and removes all but the\n * shortest from that list.\n * Then it processes the vertices for the position i+1. If i+1 == input.length() then the algorithm ends\n * and chooses the the edge with the smallest size from any of the edges leading to vertices at this position.\n * Otherwise the algorithm computes all possible outgoing edges for the vertices at the position i+1\n *\n * Examples:\n * The process is illustrated by showing the graph (edges) after each iteration from left to right over the input:\n * An edge is drawn as follows \"(\" + fromVertex + \") -- \" + encodingMode + \"(\" + encodedInput + \") (\" +\n * accumulatedSize + \") --> (\" + toVertex + \")\"\n *\n * Example 1 encoding the string \"ABCDEFG\":\n *\n *\n * Situation after adding edges to the start vertex (0,ASCII)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII)\n * (0,ASCII) B256(A) (3) --> (1,B256)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF)\n * (0,ASCII) C40(ABC) (3) --> (3,C40)\n * (0,ASCII) TEXT(ABC) (5) --> (3,TEXT)\n * (0,ASCII) X12(ABC) (3) --> (3,X12)\n * (0,ASCII) EDF(ABC) (4) --> (3,EDF)\n * (0,ASCII) EDF(ABCD) (4) --> (4,EDF)\n *\n * Situation after adding edges to vertices at position 1\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII)\n * (0,ASCII) B256(A) (3) --> (1,B256)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF)\n * (0,ASCII) C40(ABC) (3) --> (3,C40)\n * (0,ASCII) TEXT(ABC) (5) --> (3,TEXT)\n * (0,ASCII) X12(ABC) (3) --> (3,X12)\n * (0,ASCII) EDF(ABC) (4) --> (3,EDF)\n * (0,ASCII) EDF(ABCD) (4) --> (4,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) B256(B) (4) --> (2,B256)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BC) (5) --> (3,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) C40(BCD) (4) --> (4,C40)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) TEXT(BCD) (6) --> (4,TEXT)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) X12(BCD) (4) --> (4,X12)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCD) (5) --> (4,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCDE) (5) --> (5,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) ASCII(B) (4) --> (2,ASCII)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256)\n * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BC) (6) --> (3,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) C40(BCD) (5) --> (4,C40)\n * (0,ASCII) B256(A) (3) --> (1,B256) TEXT(BCD) (7) --> (4,TEXT)\n * (0,ASCII) B256(A) (3) --> (1,B256) X12(BCD) (5) --> (4,X12)\n * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BCD) (6) --> (4,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BCDE) (6) --> (5,EDF)\n *\n * Edge \"(1,ASCII) ASCII(B) (2) --> (2,ASCII)\" is minimal for the vertex (2,ASCII) so that edge \"(1,B256) ASCII(B) (4) --> (2,ASCII)\" is removed.\n * Edge \"(1,B256) B256(B) (3) --> (2,B256)\" is minimal for the vertext (2,B256) so that the edge \"(1,ASCII) B256(B) (4) --> (2,B256)\" is removed.\n *\n * Situation after adding edges to vertices at position 2\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII)\n * (0,ASCII) B256(A) (3) --> (1,B256)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF)\n * (0,ASCII) C40(ABC) (3) --> (3,C40)\n * (0,ASCII) TEXT(ABC) (5) --> (3,TEXT)\n * (0,ASCII) X12(ABC) (3) --> (3,X12)\n * (0,ASCII) EDF(ABC) (4) --> (3,EDF)\n * (0,ASCII) EDF(ABCD) (4) --> (4,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BC) (5) --> (3,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) C40(BCD) (4) --> (4,C40)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) TEXT(BCD) (6) --> (4,TEXT)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) X12(BCD) (4) --> (4,X12)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCD) (5) --> (4,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCDE) (5) --> (5,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256)\n * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BC) (6) --> (3,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) C40(BCD) (5) --> (4,C40)\n * (0,ASCII) B256(A) (3) --> (1,B256) TEXT(BCD) (7) --> (4,TEXT)\n * (0,ASCII) B256(A) (3) --> (1,B256) X12(BCD) (5) --> (4,X12)\n * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BCD) (6) --> (4,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) EDF(BCDE) (6) --> (5,EDF)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF) ASCII(C) (5) --> (3,ASCII)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF) B256(C) (6) --> (3,B256)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF) EDF(CD) (7) --> (4,EDF)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF) C40(CDE) (6) --> (5,C40)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF) TEXT(CDE) (8) --> (5,TEXT)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF) X12(CDE) (6) --> (5,X12)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF) EDF(CDE) (7) --> (5,EDF)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF) EDF(CDEF) (7) --> (6,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) B256(C) (5) --> (3,B256)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) EDF(CD) (6) --> (4,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) C40(CDE) (5) --> (5,C40)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) TEXT(CDE) (7) --> (5,TEXT)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) X12(CDE) (5) --> (5,X12)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) EDF(CDE) (6) --> (5,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) EDF(CDEF) (6) --> (6,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) ASCII(C) (4) --> (3,ASCII)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) EDF(CD) (6) --> (4,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) C40(CDE) (5) --> (5,C40)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) TEXT(CDE) (7) --> (5,TEXT)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) X12(CDE) (5) --> (5,X12)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) EDF(CDE) (6) --> (5,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) EDF(CDEF) (6) --> (6,EDF)\n *\n * Edge \"(2,ASCII) ASCII(C) (3) --> (3,ASCII)\" is minimal for the vertex (3,ASCII) so that edges \"(2,EDF) ASCII(C) (5) --> (3,ASCII)\"\n * and \"(2,B256) ASCII(C) (4) --> (3,ASCII)\" can be removed.\n * Edge \"(0,ASCII) EDF(ABC) (4) --> (3,EDF)\" is minimal for the vertex (3,EDF) so that edges \"(1,ASCII) EDF(BC) (5) --> (3,EDF)\"\n * and \"(1,B256) EDF(BC) (6) --> (3,EDF)\" can be removed.\n * Edge \"(2,B256) B256(C) (4) --> (3,B256)\" is minimal for the vertex (3,B256) so that edges \"(2,ASCII) B256(C) (5) --> (3,B256)\"\n * and \"(2,EDF) B256(C) (6) --> (3,B256)\" can be removed.\n *\n * This continues for vertices 3 thru 7\n *\n * Situation after adding edges to vertices at position 7\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII)\n * (0,ASCII) B256(A) (3) --> (1,B256)\n * (0,ASCII) EDF(AB) (4) --> (2,EDF)\n * (0,ASCII) C40(ABC) (3) --> (3,C40)\n * (0,ASCII) TEXT(ABC) (5) --> (3,TEXT)\n * (0,ASCII) X12(ABC) (3) --> (3,X12)\n * (0,ASCII) EDF(ABC) (4) --> (3,EDF)\n * (0,ASCII) EDF(ABCD) (4) --> (4,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) C40(BCD) (4) --> (4,C40)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) TEXT(BCD) (6) --> (4,TEXT)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) X12(BCD) (4) --> (4,X12)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) EDF(BCDE) (5) --> (5,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256)\n * (0,ASCII) C40(ABC) (3) --> (3,C40) C40(DEF) (5) --> (6,C40)\n * (0,ASCII) X12(ABC) (3) --> (3,X12) X12(DEF) (5) --> (6,X12)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) C40(CDE) (5) --> (5,C40)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) TEXT(CDE) (7) --> (5,TEXT)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) X12(CDE) (5) --> (5,X12)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) EDF(CDEF) (6) --> (6,EDF)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) C40(BCD) (4) --> (4,C40) C40(EFG) (6) --> (7,C40) //Solution 1\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) X12(BCD) (4) --> (4,X12) X12(EFG) (6) --> (7,X12) //Solution 2\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) TEXT(DEF) (8) --> (6,TEXT)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) EDF(DEFG) (7) --> (7,EDF)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256) B256(D) (5) --> (4,B256)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII) ASCII(E) (5) --> (5,ASCII)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII) TEXT(EFG) (9) --> (7,TEXT)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256) B256(D) (5) --> (4,B256) B256(E) (6) --> (5,B256)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII) ASCII(E) (5) --> (5,ASCII) ASCII(F) (6) --> (6,ASCII)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256) B256(D) (5) --> (4,B256) B256(E) (6) --> (5,B256) B256(F) (7) --> (6,B256)\n * (0,ASCII) ASCII(A) (1) --> (1,ASCII) ASCII(B) (2) --> (2,ASCII) ASCII(C) (3) --> (3,ASCII) ASCII(D) (4) --> (4,ASCII) ASCII(E) (5) --> (5,ASCII) ASCII(F) (6) --> (6,ASCII) ASCII(G) (7) --> (7,ASCII)\n * (0,ASCII) B256(A) (3) --> (1,B256) B256(B) (3) --> (2,B256) B256(C) (4) --> (3,B256) B256(D) (5) --> (4,B256) B256(E) (6) --> (5,B256) B256(F) (7) --> (6,B256) B256(G) (8) --> (7,B256)\n *\n * Hence a minimal encoding of \"ABCDEFG\" is either ASCII(A),C40(BCDEFG) or ASCII(A), X12(BCDEFG) with a size of 5 bytes.\n */\n var inputLength = input.length();\n // Array that represents vertices. There is a vertex for every character and mode.\n // The last dimension in the array below encodes the 6 modes ASCII, C40, TEXT, X12, EDF and B256\n var edges = Array(inputLength + 1)\n .fill(null)\n .map(function () { return Array(6).fill(0); });\n this.addEdges(input, edges, 0, null);\n for (var i = 1; i <= inputLength; i++) {\n for (var j = 0; j < 6; j++) {\n if (edges[i][j] !== null && i < inputLength) {\n this.addEdges(input, edges, i, edges[i][j]);\n }\n }\n // optimize memory by removing edges that have been passed.\n for (var j = 0; j < 6; j++) {\n edges[i - 1][j] = null;\n }\n }\n var minimalJ = -1;\n var minimalSize = Integer.MAX_VALUE;\n for (var j = 0; j < 6; j++) {\n if (edges[inputLength][j] !== null) {\n var edge = edges[inputLength][j];\n var size = j >= 1 && j <= 3 ? edge.cachedTotalSize + 1 : edge.cachedTotalSize; // C40, TEXT and X12 need an\n // extra unlatch at the end\n if (size < minimalSize) {\n minimalSize = size;\n minimalJ = j;\n }\n }\n }\n if (minimalJ < 0) {\n throw new Error('Failed to encode \"' + input + '\"');\n }\n return new Result(edges[inputLength][minimalJ]);\n };\n return MinimalEncoder;\n}());\nexport { MinimalEncoder };\nvar Result = /** @class */ (function () {\n function Result(solution) {\n var input = solution.input;\n var size = 0;\n var bytesAL = [];\n var randomizePostfixLength = [];\n var randomizeLengths = [];\n if ((solution.mode === Mode.C40 ||\n solution.mode === Mode.TEXT ||\n solution.mode === Mode.X12) &&\n solution.getEndMode() !== Mode.ASCII) {\n size += this.prepend(Edge.getBytes(254), bytesAL);\n }\n var current = solution;\n while (current !== null) {\n size += this.prepend(current.getDataBytes(), bytesAL);\n if (current.previous === null ||\n current.getPreviousStartMode() !== current.getMode()) {\n if (current.getMode() === Mode.B256) {\n if (size <= 249) {\n bytesAL.unshift(size);\n size++;\n }\n else {\n bytesAL.unshift(size % 250);\n bytesAL.unshift(size / 250 + 249);\n size += 2;\n }\n randomizePostfixLength.push(bytesAL.length);\n randomizeLengths.push(size);\n }\n this.prepend(current.getLatchBytes(), bytesAL);\n size = 0;\n }\n current = current.previous;\n }\n if (input.getMacroId() === 5) {\n size += this.prepend(Edge.getBytes(236), bytesAL);\n }\n else if (input.getMacroId() === 6) {\n size += this.prepend(Edge.getBytes(237), bytesAL);\n }\n if (input.getFNC1Character() > 0) {\n size += this.prepend(Edge.getBytes(232), bytesAL);\n }\n for (var i = 0; i < randomizePostfixLength.length; i++) {\n this.applyRandomPattern(bytesAL, bytesAL.length - randomizePostfixLength[i], randomizeLengths[i]);\n }\n // add padding\n var capacity = solution.getMinSymbolSize(bytesAL.length);\n if (bytesAL.length < capacity) {\n bytesAL.push(129);\n }\n while (bytesAL.length < capacity) {\n bytesAL.push(this.randomize253State(bytesAL.length + 1));\n }\n this.bytes = new Uint8Array(bytesAL.length);\n for (var i = 0; i < this.bytes.length; i++) {\n this.bytes[i] = bytesAL[i];\n }\n }\n Result.prototype.prepend = function (bytes, into) {\n for (var i = bytes.length - 1; i >= 0; i--) {\n into.unshift(bytes[i]);\n }\n return bytes.length;\n };\n Result.prototype.randomize253State = function (codewordPosition) {\n var pseudoRandom = ((149 * codewordPosition) % 253) + 1;\n var tempVariable = 129 + pseudoRandom;\n return tempVariable <= 254 ? tempVariable : tempVariable - 254;\n };\n Result.prototype.applyRandomPattern = function (bytesAL, startPosition, length) {\n for (var i = 0; i < length; i++) {\n // See \"B.1 253-state algorithm\n var Pad_codeword_position = startPosition + i;\n var Pad_codeword_value = bytesAL[Pad_codeword_position] & 0xff;\n var pseudo_random_number = ((149 * (Pad_codeword_position + 1)) % 255) + 1;\n var temp_variable = Pad_codeword_value + pseudo_random_number;\n bytesAL[Pad_codeword_position] =\n temp_variable <= 255 ? temp_variable : temp_variable - 256;\n }\n };\n Result.prototype.getBytes = function () {\n return this.bytes;\n };\n return Result;\n}());\nvar Edge = /** @class */ (function () {\n function Edge(input, mode, fromPosition, characterLength, previous) {\n this.input = input;\n this.mode = mode;\n this.fromPosition = fromPosition;\n this.characterLength = characterLength;\n this.previous = previous;\n this.allCodewordCapacities = [\n 3, 5, 8, 10, 12, 16, 18, 22, 30, 32, 36, 44, 49, 62, 86, 114, 144, 174, 204,\n 280, 368, 456, 576, 696, 816, 1050, 1304, 1558,\n ];\n this.squareCodewordCapacities = [\n 3, 5, 8, 12, 18, 22, 30, 36, 44, 62, 86, 114, 144, 174, 204, 280, 368, 456,\n 576, 696, 816, 1050, 1304, 1558,\n ];\n this.rectangularCodewordCapacities = [5, 10, 16, 33, 32, 49];\n if (!(fromPosition + characterLength <= input.length())) {\n throw new Error('Invalid edge');\n }\n var size = previous !== null ? previous.cachedTotalSize : 0;\n var previousMode = this.getPreviousMode();\n /*\n * Switching modes\n * ASCII -> C40: latch 230\n * ASCII -> TEXT: latch 239\n * ASCII -> X12: latch 238\n * ASCII -> EDF: latch 240\n * ASCII -> B256: latch 231\n * C40 -> ASCII: word(c1,c2,c3), 254\n * TEXT -> ASCII: word(c1,c2,c3), 254\n * X12 -> ASCII: word(c1,c2,c3), 254\n * EDIFACT -> ASCII: Unlatch character,0,0,0 or c1,Unlatch character,0,0 or c1,c2,Unlatch character,0 or\n * c1,c2,c3,Unlatch character\n * B256 -> ASCII: without latch after n bytes\n */\n switch (mode) {\n case Mode.ASCII:\n size++;\n if (input.isECI(fromPosition) ||\n MinimalEncoder.isExtendedASCII(input.charAt(fromPosition), input.getFNC1Character())) {\n size++;\n }\n if (previousMode === Mode.C40 ||\n previousMode === Mode.TEXT ||\n previousMode === Mode.X12) {\n size++; // unlatch 254 to ASCII\n }\n break;\n case Mode.B256:\n size++;\n if (previousMode !== Mode.B256) {\n size++; // byte count\n }\n else if (this.getB256Size() === 250) {\n size++; // extra byte count\n }\n if (previousMode === Mode.ASCII) {\n size++; // latch to B256\n }\n else if (previousMode === Mode.C40 ||\n previousMode === Mode.TEXT ||\n previousMode === Mode.X12) {\n size += 2; // unlatch to ASCII, latch to B256\n }\n break;\n case Mode.C40:\n case Mode.TEXT:\n case Mode.X12:\n if (mode === Mode.X12) {\n size += 2;\n }\n else {\n var charLen = [];\n size +=\n MinimalEncoder.getNumberOfC40Words(input, fromPosition, mode === Mode.C40, charLen) * 2;\n }\n if (previousMode === Mode.ASCII || previousMode === Mode.B256) {\n size++; // additional byte for latch from ASCII to this mode\n }\n else if (previousMode !== mode &&\n (previousMode === Mode.C40 ||\n previousMode === Mode.TEXT ||\n previousMode === Mode.X12)) {\n size += 2; // unlatch 254 to ASCII followed by latch to this mode\n }\n break;\n case Mode.EDF:\n size += 3;\n if (previousMode === Mode.ASCII || previousMode === Mode.B256) {\n size++; // additional byte for latch from ASCII to this mode\n }\n else if (previousMode === Mode.C40 ||\n previousMode === Mode.TEXT ||\n previousMode === Mode.X12) {\n size += 2; // unlatch 254 to ASCII followed by latch to this mode\n }\n break;\n }\n this.cachedTotalSize = size;\n }\n // does not count beyond 250\n Edge.prototype.getB256Size = function () {\n var cnt = 0;\n var current = this;\n while (current !== null && current.mode === Mode.B256 && cnt <= 250) {\n cnt++;\n current = current.previous;\n }\n return cnt;\n };\n Edge.prototype.getPreviousStartMode = function () {\n return this.previous === null ? Mode.ASCII : this.previous.mode;\n };\n Edge.prototype.getPreviousMode = function () {\n return this.previous === null ? Mode.ASCII : this.previous.getEndMode();\n };\n /** Returns Mode.ASCII in case that:\n * - Mode is EDIFACT and characterLength is less than 4 or the remaining characters can be encoded in at most 2\n * ASCII bytes.\n * - Mode is C40, TEXT or X12 and the remaining characters can be encoded in at most 1 ASCII byte.\n * Returns mode in all other cases.\n * */\n Edge.prototype.getEndMode = function () {\n if (this.mode === Mode.EDF) {\n if (this.characterLength < 4) {\n return Mode.ASCII;\n }\n var lastASCII = this.getLastASCII(); // see 5.2.8.2 EDIFACT encodation Rules\n if (lastASCII > 0 &&\n this.getCodewordsRemaining(this.cachedTotalSize + lastASCII) <=\n 2 - lastASCII) {\n return Mode.ASCII;\n }\n }\n if (this.mode === Mode.C40 ||\n this.mode === Mode.TEXT ||\n this.mode === Mode.X12) {\n // see 5.2.5.2 C40 encodation rules and 5.2.7.2 ANSI X12 encodation rules\n if (this.fromPosition + this.characterLength >= this.input.length() &&\n this.getCodewordsRemaining(this.cachedTotalSize) === 0) {\n return Mode.ASCII;\n }\n var lastASCII = this.getLastASCII();\n if (lastASCII === 1 &&\n this.getCodewordsRemaining(this.cachedTotalSize + 1) === 0) {\n return Mode.ASCII;\n }\n }\n return this.mode;\n };\n Edge.prototype.getMode = function () {\n return this.mode;\n };\n /** Peeks ahead and returns 1 if the postfix consists of exactly two digits, 2 if the postfix consists of exactly\n * two consecutive digits and a non extended character or of 4 digits.\n * Returns 0 in any other case\n **/\n Edge.prototype.getLastASCII = function () {\n var length = this.input.length();\n var from = this.fromPosition + this.characterLength;\n if (length - from > 4 || from >= length) {\n return 0;\n }\n if (length - from === 1) {\n if (MinimalEncoder.isExtendedASCII(this.input.charAt(from), this.input.getFNC1Character())) {\n return 0;\n }\n return 1;\n }\n if (length - from === 2) {\n if (MinimalEncoder.isExtendedASCII(this.input.charAt(from), this.input.getFNC1Character()) ||\n MinimalEncoder.isExtendedASCII(this.input.charAt(from + 1), this.input.getFNC1Character())) {\n return 0;\n }\n if (HighLevelEncoder.isDigit(this.input.charAt(from)) &&\n HighLevelEncoder.isDigit(this.input.charAt(from + 1))) {\n return 1;\n }\n return 2;\n }\n if (length - from === 3) {\n if (HighLevelEncoder.isDigit(this.input.charAt(from)) &&\n HighLevelEncoder.isDigit(this.input.charAt(from + 1)) &&\n !MinimalEncoder.isExtendedASCII(this.input.charAt(from + 2), this.input.getFNC1Character())) {\n return 2;\n }\n if (HighLevelEncoder.isDigit(this.input.charAt(from + 1)) &&\n HighLevelEncoder.isDigit(this.input.charAt(from + 2)) &&\n !MinimalEncoder.isExtendedASCII(this.input.charAt(from), this.input.getFNC1Character())) {\n return 2;\n }\n return 0;\n }\n if (HighLevelEncoder.isDigit(this.input.charAt(from)) &&\n HighLevelEncoder.isDigit(this.input.charAt(from + 1)) &&\n HighLevelEncoder.isDigit(this.input.charAt(from + 2)) &&\n HighLevelEncoder.isDigit(this.input.charAt(from + 3))) {\n return 2;\n }\n return 0;\n };\n /** Returns the capacity in codewords of the smallest symbol that has enough capacity to fit the given minimal\n * number of codewords.\n **/\n Edge.prototype.getMinSymbolSize = function (minimum) {\n var e_3, _a, e_4, _b, e_5, _c;\n switch (this.input.getShapeHint()) {\n case 1 /* FORCE_SQUARE */:\n try {\n for (var _d = __values(this.squareCodewordCapacities), _e = _d.next(); !_e.done; _e = _d.next()) {\n var capacity = _e.value;\n if (capacity >= minimum) {\n return capacity;\n }\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (_e && !_e.done && (_a = _d.return)) _a.call(_d);\n }\n finally { if (e_3) throw e_3.error; }\n }\n break;\n case 2 /* FORCE_RECTANGLE */:\n try {\n for (var _f = __values(this.rectangularCodewordCapacities), _g = _f.next(); !_g.done; _g = _f.next()) {\n var capacity = _g.value;\n if (capacity >= minimum) {\n return capacity;\n }\n }\n }\n catch (e_4_1) { e_4 = { error: e_4_1 }; }\n finally {\n try {\n if (_g && !_g.done && (_b = _f.return)) _b.call(_f);\n }\n finally { if (e_4) throw e_4.error; }\n }\n break;\n }\n try {\n for (var _h = __values(this.allCodewordCapacities), _j = _h.next(); !_j.done; _j = _h.next()) {\n var capacity = _j.value;\n if (capacity >= minimum) {\n return capacity;\n }\n }\n }\n catch (e_5_1) { e_5 = { error: e_5_1 }; }\n finally {\n try {\n if (_j && !_j.done && (_c = _h.return)) _c.call(_h);\n }\n finally { if (e_5) throw e_5.error; }\n }\n return this.allCodewordCapacities[this.allCodewordCapacities.length - 1];\n };\n /** Returns the remaining capacity in codewords of the smallest symbol that has enough capacity to fit the given\n * minimal number of codewords.\n **/\n Edge.prototype.getCodewordsRemaining = function (minimum) {\n return this.getMinSymbolSize(minimum) - minimum;\n };\n Edge.getBytes = function (c1, c2) {\n var result = new Uint8Array(c2 ? 2 : 1);\n result[0] = c1;\n if (c2) {\n result[1] = c2;\n }\n return result;\n };\n Edge.prototype.setC40Word = function (bytes, offset, c1, c2, c3) {\n var val16 = 1600 * (c1 & 0xff) + 40 * (c2 & 0xff) + (c3 & 0xff) + 1;\n bytes[offset] = val16 / 256;\n bytes[offset + 1] = val16 % 256;\n };\n Edge.prototype.getX12Value = function (c) {\n return c === 13\n ? 0\n : c === 42\n ? 1\n : c === 62\n ? 2\n : c === 32\n ? 3\n : c >= 48 && c <= 57\n ? c - 44\n : c >= 65 && c <= 90\n ? c - 51\n : c;\n };\n Edge.prototype.getX12Words = function () {\n if (!(this.characterLength % 3 === 0)) {\n throw new Error('X12 words must be a multiple of 3');\n }\n var result = new Uint8Array((this.characterLength / 3) * 2);\n for (var i = 0; i < result.length; i += 2) {\n this.setC40Word(result, i, this.getX12Value(this.input.charAt(this.fromPosition + (i / 2) * 3)), this.getX12Value(this.input.charAt(this.fromPosition + (i / 2) * 3 + 1)), this.getX12Value(this.input.charAt(this.fromPosition + (i / 2) * 3 + 2)));\n }\n return result;\n };\n Edge.prototype.getShiftValue = function (c, c40, fnc1) {\n return (c40 && MinimalEncoder.isInC40Shift1Set(c)) ||\n (!c40 && MinimalEncoder.isInTextShift1Set(c))\n ? 0\n : (c40 && MinimalEncoder.isInC40Shift2Set(c, fnc1)) ||\n (!c40 && MinimalEncoder.isInTextShift2Set(c, fnc1))\n ? 1\n : 2;\n };\n Edge.prototype.getC40Value = function (c40, setIndex, c, fnc1) {\n if (c === fnc1) {\n if (!(setIndex === 2)) {\n throw new Error('FNC1 cannot be used in C40 shift 2');\n }\n return 27;\n }\n if (c40) {\n return c <= 31\n ? c\n : c === 32\n ? 3\n : c <= 47\n ? c - 33\n : c <= 57\n ? c - 44\n : c <= 64\n ? c - 43\n : c <= 90\n ? c - 51\n : c <= 95\n ? c - 69\n : c <= 127\n ? c - 96\n : c;\n }\n else {\n return c === 0\n ? 0\n : setIndex === 0 && c <= 3\n ? c - 1 // is this a bug in the spec?\n : setIndex === 1 && c <= 31\n ? c\n : c === 32\n ? 3\n : c >= 33 && c <= 47\n ? c - 33\n : c >= 48 && c <= 57\n ? c - 44\n : c >= 58 && c <= 64\n ? c - 43\n : c >= 65 && c <= 90\n ? c - 64\n : c >= 91 && c <= 95\n ? c - 69\n : c === 96\n ? 0\n : c >= 97 && c <= 122\n ? c - 83\n : c >= 123 && c <= 127\n ? c - 96\n : c;\n }\n };\n Edge.prototype.getC40Words = function (c40, fnc1) {\n var c40Values = [];\n for (var i = 0; i < this.characterLength; i++) {\n var ci = this.input.charAt(this.fromPosition + i);\n if ((c40 && HighLevelEncoder.isNativeC40(ci)) ||\n (!c40 && HighLevelEncoder.isNativeText(ci))) {\n c40Values.push(this.getC40Value(c40, 0, ci, fnc1));\n }\n else if (!MinimalEncoder.isExtendedASCII(ci, fnc1)) {\n var shiftValue = this.getShiftValue(ci, c40, fnc1);\n c40Values.push(shiftValue); // Shift[123]\n c40Values.push(this.getC40Value(c40, shiftValue, ci, fnc1));\n }\n else {\n var asciiValue = (ci & 0xff) - 128;\n if ((c40 && HighLevelEncoder.isNativeC40(asciiValue)) ||\n (!c40 && HighLevelEncoder.isNativeText(asciiValue))) {\n c40Values.push(1); // Shift 2\n c40Values.push(30); // Upper Shift\n c40Values.push(this.getC40Value(c40, 0, asciiValue, fnc1));\n }\n else {\n c40Values.push(1); // Shift 2\n c40Values.push(30); // Upper Shift\n var shiftValue = this.getShiftValue(asciiValue, c40, fnc1);\n c40Values.push(shiftValue); // Shift[123]\n c40Values.push(this.getC40Value(c40, shiftValue, asciiValue, fnc1));\n }\n }\n }\n if (c40Values.length % 3 !== 0) {\n if (!((c40Values.length - 2) % 3 === 0 &&\n this.fromPosition + this.characterLength === this.input.length())) {\n throw new Error('C40 words must be a multiple of 3');\n }\n c40Values.push(0); // pad with 0 (Shift 1)\n }\n var result = new Uint8Array((c40Values.length / 3) * 2);\n var byteIndex = 0;\n for (var i = 0; i < c40Values.length; i += 3) {\n this.setC40Word(result, byteIndex, c40Values[i] & 0xff, c40Values[i + 1] & 0xff, c40Values[i + 2] & 0xff);\n byteIndex += 2;\n }\n return result;\n };\n Edge.prototype.getEDFBytes = function () {\n var numberOfThirds = Math.ceil(this.characterLength / 4.0);\n var result = new Uint8Array(numberOfThirds * 3);\n var pos = this.fromPosition;\n var endPos = Math.min(this.fromPosition + this.characterLength - 1, this.input.length() - 1);\n for (var i = 0; i < numberOfThirds; i += 3) {\n var edfValues = [];\n for (var j = 0; j < 4; j++) {\n if (pos <= endPos) {\n edfValues[j] = this.input.charAt(pos++) & 0x3f;\n }\n else {\n edfValues[j] = pos === endPos + 1 ? 0x1f : 0;\n }\n }\n var val24 = edfValues[0] << 18;\n val24 |= edfValues[1] << 12;\n val24 |= edfValues[2] << 6;\n val24 |= edfValues[3];\n result[i] = (val24 >> 16) & 0xff;\n result[i + 1] = (val24 >> 8) & 0xff;\n result[i + 2] = val24 & 0xff;\n }\n return result;\n };\n Edge.prototype.getLatchBytes = function () {\n switch (this.getPreviousMode()) {\n case Mode.ASCII:\n case Mode.B256: // after B256 ends (via length) we are back to ASCII\n switch (this.mode) {\n case Mode.B256:\n return Edge.getBytes(231);\n case Mode.C40:\n return Edge.getBytes(230);\n case Mode.TEXT:\n return Edge.getBytes(239);\n case Mode.X12:\n return Edge.getBytes(238);\n case Mode.EDF:\n return Edge.getBytes(240);\n }\n break;\n case Mode.C40:\n case Mode.TEXT:\n case Mode.X12:\n if (this.mode !== this.getPreviousMode()) {\n switch (this.mode) {\n case Mode.ASCII:\n return Edge.getBytes(254);\n case Mode.B256:\n return Edge.getBytes(254, 231);\n case Mode.C40:\n return Edge.getBytes(254, 230);\n case Mode.TEXT:\n return Edge.getBytes(254, 239);\n case Mode.X12:\n return Edge.getBytes(254, 238);\n case Mode.EDF:\n return Edge.getBytes(254, 240);\n }\n }\n break;\n case Mode.EDF:\n // The rightmost EDIFACT edge always contains an unlatch character\n if (this.mode !== Mode.EDF) {\n throw new Error('Cannot switch from EDF to ' + this.mode);\n }\n break;\n }\n return new Uint8Array(0);\n };\n // Important: The function does not return the length bytes (one or two) in case of B256 encoding\n Edge.prototype.getDataBytes = function () {\n switch (this.mode) {\n case Mode.ASCII:\n if (this.input.isECI(this.fromPosition)) {\n return Edge.getBytes(241, this.input.getECIValue(this.fromPosition) + 1);\n }\n else if (MinimalEncoder.isExtendedASCII(this.input.charAt(this.fromPosition), this.input.getFNC1Character())) {\n return Edge.getBytes(235, this.input.charAt(this.fromPosition) - 127);\n }\n else if (this.characterLength === 2) {\n return Edge.getBytes(this.input.charAt(this.fromPosition) * 10 +\n this.input.charAt(this.fromPosition + 1) +\n 130);\n }\n else if (this.input.isFNC1(this.fromPosition)) {\n return Edge.getBytes(232);\n }\n else {\n return Edge.getBytes(this.input.charAt(this.fromPosition) + 1);\n }\n case Mode.B256:\n return Edge.getBytes(this.input.charAt(this.fromPosition));\n case Mode.C40:\n return this.getC40Words(true, this.input.getFNC1Character());\n case Mode.TEXT:\n return this.getC40Words(false, this.input.getFNC1Character());\n case Mode.X12:\n return this.getX12Words();\n case Mode.EDF:\n return this.getEDFBytes();\n }\n };\n return Edge;\n}());\nvar Input = /** @class */ (function (_super) {\n __extends(Input, _super);\n function Input(stringToEncode, priorityCharset, fnc1, shape, macroId) {\n var _this = _super.call(this, stringToEncode, priorityCharset, fnc1) || this;\n _this.shape = shape;\n _this.macroId = macroId;\n return _this;\n }\n Input.prototype.getMacroId = function () {\n return this.macroId;\n };\n Input.prototype.getShapeHint = function () {\n return this.shape;\n };\n return Input;\n}(MinimalECIInput));\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/**\n * Symbol info table for DataMatrix.\n */\nvar SymbolInfo = /** @class */ (function () {\n function SymbolInfo(rectangular, dataCapacity, errorCodewords, matrixWidth, matrixHeight, dataRegions, rsBlockData, rsBlockError) {\n if (rsBlockData === void 0) { rsBlockData = 0; }\n if (rsBlockError === void 0) { rsBlockError = 0; }\n this.rectangular = rectangular;\n this.dataCapacity = dataCapacity;\n this.errorCodewords = errorCodewords;\n this.matrixWidth = matrixWidth;\n this.matrixHeight = matrixHeight;\n this.dataRegions = dataRegions;\n this.rsBlockData = rsBlockData;\n this.rsBlockError = rsBlockError;\n }\n SymbolInfo.lookup = function (dataCodewords, shape, minSize, maxSize, fail) {\n var e_1, _a;\n if (shape === void 0) { shape = 0 /* FORCE_NONE */; }\n if (minSize === void 0) { minSize = null; }\n if (maxSize === void 0) { maxSize = null; }\n if (fail === void 0) { fail = true; }\n try {\n for (var PROD_SYMBOLS_1 = __values(PROD_SYMBOLS), PROD_SYMBOLS_1_1 = PROD_SYMBOLS_1.next(); !PROD_SYMBOLS_1_1.done; PROD_SYMBOLS_1_1 = PROD_SYMBOLS_1.next()) {\n var symbol = PROD_SYMBOLS_1_1.value;\n if (shape === 1 /* FORCE_SQUARE */ && symbol.rectangular) {\n continue;\n }\n if (shape === 2 /* FORCE_RECTANGLE */ && !symbol.rectangular) {\n continue;\n }\n if (minSize != null &&\n (symbol.getSymbolWidth() < minSize.getWidth() ||\n symbol.getSymbolHeight() < minSize.getHeight())) {\n continue;\n }\n if (maxSize != null &&\n (symbol.getSymbolWidth() > maxSize.getWidth() ||\n symbol.getSymbolHeight() > maxSize.getHeight())) {\n continue;\n }\n if (dataCodewords <= symbol.dataCapacity) {\n return symbol;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (PROD_SYMBOLS_1_1 && !PROD_SYMBOLS_1_1.done && (_a = PROD_SYMBOLS_1.return)) _a.call(PROD_SYMBOLS_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n if (fail) {\n throw new Error(\"Can't find a symbol arrangement that matches the message. Data codewords: \" +\n dataCodewords);\n }\n return null;\n };\n SymbolInfo.prototype.getHorizontalDataRegions = function () {\n switch (this.dataRegions) {\n case 1:\n return 1;\n case 2:\n case 4:\n return 2;\n case 16:\n return 4;\n case 36:\n return 6;\n default:\n throw new Error('Cannot handle this number of data regions');\n }\n };\n SymbolInfo.prototype.getVerticalDataRegions = function () {\n switch (this.dataRegions) {\n case 1:\n case 2:\n return 1;\n case 4:\n return 2;\n case 16:\n return 4;\n case 36:\n return 6;\n default:\n throw new Error('Cannot handle this number of data regions');\n }\n };\n SymbolInfo.prototype.getSymbolDataWidth = function () {\n return this.getHorizontalDataRegions() * this.matrixWidth;\n };\n SymbolInfo.prototype.getSymbolDataHeight = function () {\n return this.getVerticalDataRegions() * this.matrixHeight;\n };\n SymbolInfo.prototype.getSymbolWidth = function () {\n return this.getSymbolDataWidth() + this.getHorizontalDataRegions() * 2;\n };\n SymbolInfo.prototype.getSymbolHeight = function () {\n return this.getSymbolDataHeight() + this.getVerticalDataRegions() * 2;\n };\n SymbolInfo.prototype.getCodewordCount = function () {\n return this.dataCapacity + this.errorCodewords;\n };\n SymbolInfo.prototype.getInterleavedBlockCount = function () {\n if (!this.rsBlockData)\n return 1;\n return this.dataCapacity / this.rsBlockData;\n };\n SymbolInfo.prototype.getDataCapacity = function () {\n return this.dataCapacity;\n };\n SymbolInfo.prototype.getErrorCodewords = function () {\n return this.errorCodewords;\n };\n SymbolInfo.prototype.getDataLengthForInterleavedBlock = function (index) {\n return this.rsBlockData;\n };\n SymbolInfo.prototype.getErrorLengthForInterleavedBlock = function (index) {\n return this.rsBlockError;\n };\n return SymbolInfo;\n}());\nexport default SymbolInfo;\nvar DataMatrixSymbolInfo144 = /** @class */ (function (_super) {\n __extends(DataMatrixSymbolInfo144, _super);\n function DataMatrixSymbolInfo144() {\n return _super.call(this, false, 1558, 620, 22, 22, 36, -1, 62) || this;\n }\n DataMatrixSymbolInfo144.prototype.getInterleavedBlockCount = function () {\n return 10;\n };\n DataMatrixSymbolInfo144.prototype.getDataLengthForInterleavedBlock = function (index) {\n return index <= 8 ? 156 : 155;\n };\n return DataMatrixSymbolInfo144;\n}(SymbolInfo));\nexport var PROD_SYMBOLS = [\n new SymbolInfo(false, 3, 5, 8, 8, 1),\n new SymbolInfo(false, 5, 7, 10, 10, 1),\n /*rect*/ new SymbolInfo(true, 5, 7, 16, 6, 1),\n new SymbolInfo(false, 8, 10, 12, 12, 1),\n /*rect*/ new SymbolInfo(true, 10, 11, 14, 6, 2),\n new SymbolInfo(false, 12, 12, 14, 14, 1),\n /*rect*/ new SymbolInfo(true, 16, 14, 24, 10, 1),\n new SymbolInfo(false, 18, 14, 16, 16, 1),\n new SymbolInfo(false, 22, 18, 18, 18, 1),\n /*rect*/ new SymbolInfo(true, 22, 18, 16, 10, 2),\n new SymbolInfo(false, 30, 20, 20, 20, 1),\n /*rect*/ new SymbolInfo(true, 32, 24, 16, 14, 2),\n new SymbolInfo(false, 36, 24, 22, 22, 1),\n new SymbolInfo(false, 44, 28, 24, 24, 1),\n /*rect*/ new SymbolInfo(true, 49, 28, 22, 14, 2),\n new SymbolInfo(false, 62, 36, 14, 14, 4),\n new SymbolInfo(false, 86, 42, 16, 16, 4),\n new SymbolInfo(false, 114, 48, 18, 18, 4),\n new SymbolInfo(false, 144, 56, 20, 20, 4),\n new SymbolInfo(false, 174, 68, 22, 22, 4),\n new SymbolInfo(false, 204, 84, 24, 24, 4, 102, 42),\n new SymbolInfo(false, 280, 112, 14, 14, 16, 140, 56),\n new SymbolInfo(false, 368, 144, 16, 16, 16, 92, 36),\n new SymbolInfo(false, 456, 192, 18, 18, 16, 114, 48),\n new SymbolInfo(false, 576, 224, 20, 20, 16, 144, 56),\n new SymbolInfo(false, 696, 272, 22, 22, 16, 174, 68),\n new SymbolInfo(false, 816, 336, 24, 24, 16, 136, 56),\n new SymbolInfo(false, 1050, 408, 18, 18, 36, 175, 68),\n new SymbolInfo(false, 1304, 496, 20, 20, 36, 163, 62),\n new DataMatrixSymbolInfo144(),\n];\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport { C40Encoder } from './C40Encoder';\nimport { TEXT_ENCODATION } from './constants';\nvar TextEncoder = /** @class */ (function (_super) {\n __extends(TextEncoder, _super);\n function TextEncoder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n TextEncoder.prototype.getEncodingMode = function () {\n return TEXT_ENCODATION;\n };\n TextEncoder.prototype.encodeChar = function (c, sb) {\n if (c === ' '.charCodeAt(0)) {\n sb.append(3);\n return 1;\n }\n if (c >= '0'.charCodeAt(0) && c <= '9'.charCodeAt(0)) {\n sb.append(c - 48 + 4);\n return 1;\n }\n if (c >= 'a'.charCodeAt(0) && c <= 'z'.charCodeAt(0)) {\n sb.append(c - 97 + 14);\n return 1;\n }\n if (c < ' '.charCodeAt(0)) {\n sb.append(0); // Shift 1 Set\n sb.append(c);\n return 2;\n }\n if (c <= '/'.charCodeAt(0)) {\n sb.append(1); // Shift 2 Set\n sb.append(c - 33);\n return 2;\n }\n if (c <= '@'.charCodeAt(0)) {\n sb.append(1); // Shift 2 Set\n sb.append(c - 58 + 15);\n return 2;\n }\n if (c >= '['.charCodeAt(0) && c <= '_'.charCodeAt(0)) {\n sb.append(1); // Shift 2 Set\n sb.append(c - 91 + 22);\n return 2;\n }\n if (c === '`'.charCodeAt(0)) {\n sb.append(2); // Shift 3 Set\n sb.append(0); // '`' - 96 == 0\n return 2;\n }\n if (c <= 'Z'.charCodeAt(0)) {\n sb.append(2); // Shift 3 Set\n sb.append(c - 65 + 1);\n return 2;\n }\n if (c <= 127) {\n sb.append(2); // Shift 3 Set\n sb.append(c - 123 + 27);\n return 2;\n }\n sb.append(1 + \"\\u001E\"); // Shift 2, Upper Shift\n var len = 2;\n len += this.encodeChar(c - 128, sb);\n return len;\n };\n return TextEncoder;\n}(C40Encoder));\nexport { TextEncoder };\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport StringUtils from '../../common/StringUtils';\nimport StringBuilder from '../../util/StringBuilder';\nimport { C40Encoder } from './C40Encoder';\nimport HighLevelEncoder from './HighLevelEncoder';\nimport { X12_ENCODATION, ASCII_ENCODATION, X12_UNLATCH } from './constants';\nvar X12Encoder = /** @class */ (function (_super) {\n __extends(X12Encoder, _super);\n function X12Encoder() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n X12Encoder.prototype.getEncodingMode = function () {\n return X12_ENCODATION;\n };\n X12Encoder.prototype.encode = function (context) {\n // step C\n var buffer = new StringBuilder();\n while (context.hasMoreCharacters()) {\n var c = context.getCurrentChar();\n context.pos++;\n this.encodeChar(c, buffer);\n var count = buffer.length();\n if (count % 3 === 0) {\n this.writeNextTriplet(context, buffer);\n var newMode = HighLevelEncoder.lookAheadTest(context.getMessage(), context.pos, this.getEncodingMode());\n if (newMode !== this.getEncodingMode()) {\n // Return to ASCII encodation, which will actually handle latch to new mode\n context.signalEncoderChange(ASCII_ENCODATION);\n break;\n }\n }\n }\n this.handleEOD(context, buffer);\n };\n X12Encoder.prototype.encodeChar = function (c, sb) {\n switch (c) {\n case 13: // CR (Carriage return)\n sb.append(0);\n break;\n case '*'.charCodeAt(0):\n sb.append(1);\n break;\n case '>'.charCodeAt(0):\n sb.append(2);\n break;\n case ' '.charCodeAt(0):\n sb.append(3);\n break;\n default:\n if (c >= '0'.charCodeAt(0) && c <= '9'.charCodeAt(0)) {\n sb.append(c - 48 + 4);\n }\n else if (c >= 'A'.charCodeAt(0) && c <= 'Z'.charCodeAt(0)) {\n sb.append(c - 65 + 14);\n }\n else {\n HighLevelEncoder.illegalCharacter(StringUtils.getCharAt(c));\n }\n break;\n }\n return 1;\n };\n X12Encoder.prototype.handleEOD = function (context, buffer) {\n context.updateSymbolInfo();\n var available = context.getSymbolInfo().getDataCapacity() - context.getCodewordCount();\n var count = buffer.length();\n context.pos -= count;\n if (context.getRemainingCharacters() > 1 ||\n available > 1 ||\n context.getRemainingCharacters() !== available) {\n context.writeCodeword(X12_UNLATCH);\n }\n if (context.getNewEncoding() < 0) {\n context.signalEncoderChange(ASCII_ENCODATION);\n }\n };\n return X12Encoder;\n}(C40Encoder));\nexport { X12Encoder };\n","var _a;\n/**\n * Lookup table which factors to use for which number of error correction codewords.\n * See FACTORS.\n */\nexport var FACTOR_SETS = [\n 5, 7, 10, 11, 12, 14, 18, 20, 24, 28, 36, 42, 48, 56, 62, 68,\n];\n/**\n * Precomputed polynomial factors for ECC 200.\n */\nexport var FACTORS = [\n [228, 48, 15, 111, 62],\n [23, 68, 144, 134, 240, 92, 254],\n [28, 24, 185, 166, 223, 248, 116, 255, 110, 61],\n [175, 138, 205, 12, 194, 168, 39, 245, 60, 97, 120],\n [41, 153, 158, 91, 61, 42, 142, 213, 97, 178, 100, 242],\n [156, 97, 192, 252, 95, 9, 157, 119, 138, 45, 18, 186, 83, 185],\n [\n 83, 195, 100, 39, 188, 75, 66, 61, 241, 213, 109, 129, 94, 254, 225, 48, 90,\n 188,\n ],\n [\n 15, 195, 244, 9, 233, 71, 168, 2, 188, 160, 153, 145, 253, 79, 108, 82, 27,\n 174, 186, 172,\n ],\n [\n 52, 190, 88, 205, 109, 39, 176, 21, 155, 197, 251, 223, 155, 21, 5, 172,\n 254, 124, 12, 181, 184, 96, 50, 193,\n ],\n [\n 211, 231, 43, 97, 71, 96, 103, 174, 37, 151, 170, 53, 75, 34, 249, 121, 17,\n 138, 110, 213, 141, 136, 120, 151, 233, 168, 93, 255,\n ],\n [\n 245, 127, 242, 218, 130, 250, 162, 181, 102, 120, 84, 179, 220, 251, 80,\n 182, 229, 18, 2, 4, 68, 33, 101, 137, 95, 119, 115, 44, 175, 184, 59, 25,\n 225, 98, 81, 112,\n ],\n [\n 77, 193, 137, 31, 19, 38, 22, 153, 247, 105, 122, 2, 245, 133, 242, 8, 175,\n 95, 100, 9, 167, 105, 214, 111, 57, 121, 21, 1, 253, 57, 54, 101, 248, 202,\n 69, 50, 150, 177, 226, 5, 9, 5,\n ],\n [\n 245, 132, 172, 223, 96, 32, 117, 22, 238, 133, 238, 231, 205, 188, 237, 87,\n 191, 106, 16, 147, 118, 23, 37, 90, 170, 205, 131, 88, 120, 100, 66, 138,\n 186, 240, 82, 44, 176, 87, 187, 147, 160, 175, 69, 213, 92, 253, 225, 19,\n ],\n [\n 175, 9, 223, 238, 12, 17, 220, 208, 100, 29, 175, 170, 230, 192, 215, 235,\n 150, 159, 36, 223, 38, 200, 132, 54, 228, 146, 218, 234, 117, 203, 29, 232,\n 144, 238, 22, 150, 201, 117, 62, 207, 164, 13, 137, 245, 127, 67, 247, 28,\n 155, 43, 203, 107, 233, 53, 143, 46,\n ],\n [\n 242, 93, 169, 50, 144, 210, 39, 118, 202, 188, 201, 189, 143, 108, 196, 37,\n 185, 112, 134, 230, 245, 63, 197, 190, 250, 106, 185, 221, 175, 64, 114, 71,\n 161, 44, 147, 6, 27, 218, 51, 63, 87, 10, 40, 130, 188, 17, 163, 31, 176,\n 170, 4, 107, 232, 7, 94, 166, 224, 124, 86, 47, 11, 204,\n ],\n [\n 220, 228, 173, 89, 251, 149, 159, 56, 89, 33, 147, 244, 154, 36, 73, 127,\n 213, 136, 248, 180, 234, 197, 158, 177, 68, 122, 93, 213, 15, 160, 227, 236,\n 66, 139, 153, 185, 202, 167, 179, 25, 220, 232, 96, 210, 231, 136, 223, 239,\n 181, 241, 59, 52, 172, 25, 49, 232, 211, 189, 64, 54, 108, 153, 132, 63, 96,\n 103, 82, 186,\n ],\n];\nexport var /*final*/ MODULO_VALUE = 0x12d;\nvar static_LOG = function (LOG, ALOG) {\n var p = 1;\n for (var i = 0; i < 255; i++) {\n ALOG[i] = p;\n LOG[p] = i;\n p *= 2;\n if (p >= 256) {\n p ^= MODULO_VALUE;\n }\n }\n return {\n LOG: LOG,\n ALOG: ALOG,\n };\n};\nexport var LOG = (_a = static_LOG([], []), _a.LOG), ALOG = _a.ALOG;\nexport var SymbolShapeHint;\n(function (SymbolShapeHint) {\n SymbolShapeHint[SymbolShapeHint[\"FORCE_NONE\"] = 0] = \"FORCE_NONE\";\n SymbolShapeHint[SymbolShapeHint[\"FORCE_SQUARE\"] = 1] = \"FORCE_SQUARE\";\n SymbolShapeHint[SymbolShapeHint[\"FORCE_RECTANGLE\"] = 2] = \"FORCE_RECTANGLE\";\n})(SymbolShapeHint || (SymbolShapeHint = {}));\n/**\n * Padding character\n */\nexport var PAD = 129;\n/**\n * mode latch to C40 encodation mode\n */\nexport var LATCH_TO_C40 = 230;\n/**\n * mode latch to Base 256 encodation mode\n */\nexport var LATCH_TO_BASE256 = 231;\n/**\n * FNC1 Codeword\n */\n// private static FNC1 = 232;\n/**\n * Structured Append Codeword\n */\n// private static STRUCTURED_APPEND = 233;\n/**\n * Reader Programming\n */\n// private static READER_PROGRAMMING = 234;\n/**\n * Upper Shift\n */\nexport var UPPER_SHIFT = 235;\n/**\n * 05 Macro\n */\nexport var MACRO_05 = 236;\n/**\n * 06 Macro\n */\nexport var MACRO_06 = 237;\n/**\n * mode latch to ANSI X.12 encodation mode\n */\nexport var LATCH_TO_ANSIX12 = 238;\n/**\n * mode latch to Text encodation mode\n */\nexport var LATCH_TO_TEXT = 239;\n/**\n * mode latch to EDIFACT encodation mode\n */\nexport var LATCH_TO_EDIFACT = 240;\n/**\n * ECI character (Extended Channel Interpretation)\n */\n// private export const ECI = 241;\n/**\n * Unlatch from C40 encodation\n */\nexport var C40_UNLATCH = 254;\n/**\n * Unlatch from X12 encodation\n */\nexport var X12_UNLATCH = 254;\n/**\n * 05 Macro header\n */\nexport var MACRO_05_HEADER = '[)>\\u001E05\\u001D';\n/**\n * 06 Macro header\n */\nexport var MACRO_06_HEADER = '[)>\\u001E06\\u001D';\n/**\n * Macro trailer\n */\nexport var MACRO_TRAILER = '\\u001E\\u0004';\nexport var ASCII_ENCODATION = 0;\nexport var C40_ENCODATION = 1;\nexport var TEXT_ENCODATION = 2;\nexport var X12_ENCODATION = 3;\nexport var EDIFACT_ENCODATION = 4;\nexport var BASE256_ENCODATION = 5;\n","import { ASCIIEncoder } from './ASCIIEncoder';\nimport { Base256Encoder } from './Base256Encoder';\nimport { C40Encoder } from './C40Encoder';\nimport DefaultPlacement from './DefaultPlacement';\nimport { EdifactEncoder } from './EdifactEncoder';\nimport { EncoderContext } from './EncoderContext';\nimport ErrorCorrection from './ErrorCorrection';\nimport HighLevelEncoder from './HighLevelEncoder';\nimport { MinimalEncoder } from './MinimalEncoder';\nimport SymbolInfo from './SymbolInfo';\nimport { TextEncoder } from './TextEncoder';\nimport { X12Encoder } from './X12Encoder';\nexport { ASCIIEncoder, Base256Encoder, C40Encoder, EdifactEncoder, EncoderContext, ErrorCorrection, DefaultPlacement, HighLevelEncoder, MinimalEncoder, SymbolInfo, TextEncoder, X12Encoder, };\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport OneDReader from './OneDReader';\nimport NotFoundException from '../NotFoundException';\nimport FormatException from '../FormatException';\n/**\n *Encapsulates functionality and implementation that is common to UPC and EAN families\n * of one-dimensional barcodes.
\n *\n * @author dswitkin@google.com (Daniel Switkin)\n * @author Sean Owen\n * @author alasdair@google.com (Alasdair Mackintosh)\n */\nvar AbstractUPCEANReader = /** @class */ (function (_super) {\n __extends(AbstractUPCEANReader, _super);\n function AbstractUPCEANReader() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.decodeRowStringBuffer = '';\n return _this;\n }\n // private final UPCEANExtensionSupport extensionReader;\n // private final EANManufacturerOrgSupport eanManSupport;\n /*\n protected UPCEANReader() {\n decodeRowStringBuffer = new StringBuilder(20);\n extensionReader = new UPCEANExtensionSupport();\n eanManSupport = new EANManufacturerOrgSupport();\n }\n */\n AbstractUPCEANReader.findStartGuardPattern = function (row) {\n var foundStart = false;\n var startRange;\n var nextStart = 0;\n var counters = Int32Array.from([0, 0, 0]);\n while (!foundStart) {\n counters = Int32Array.from([0, 0, 0]);\n startRange = AbstractUPCEANReader.findGuardPattern(row, nextStart, false, this.START_END_PATTERN, counters);\n var start = startRange[0];\n nextStart = startRange[1];\n var quietStart = start - (nextStart - start);\n if (quietStart >= 0) {\n foundStart = row.isRange(quietStart, start, false);\n }\n }\n return startRange;\n };\n AbstractUPCEANReader.checkChecksum = function (s) {\n return AbstractUPCEANReader.checkStandardUPCEANChecksum(s);\n };\n AbstractUPCEANReader.checkStandardUPCEANChecksum = function (s) {\n var length = s.length;\n if (length === 0)\n return false;\n var check = parseInt(s.charAt(length - 1), 10);\n return AbstractUPCEANReader.getStandardUPCEANChecksum(s.substring(0, length - 1)) === check;\n };\n AbstractUPCEANReader.getStandardUPCEANChecksum = function (s) {\n var length = s.length;\n var sum = 0;\n for (var i = length - 1; i >= 0; i -= 2) {\n var digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);\n if (digit < 0 || digit > 9) {\n throw new FormatException();\n }\n sum += digit;\n }\n sum *= 3;\n for (var i = length - 2; i >= 0; i -= 2) {\n var digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);\n if (digit < 0 || digit > 9) {\n throw new FormatException();\n }\n sum += digit;\n }\n return (1000 - sum) % 10;\n };\n AbstractUPCEANReader.decodeEnd = function (row, endStart) {\n return AbstractUPCEANReader.findGuardPattern(row, endStart, false, AbstractUPCEANReader.START_END_PATTERN, new Int32Array(AbstractUPCEANReader.START_END_PATTERN.length).fill(0));\n };\n /**\n * @throws NotFoundException\n */\n AbstractUPCEANReader.findGuardPatternWithoutCounters = function (row, rowOffset, whiteFirst, pattern) {\n return this.findGuardPattern(row, rowOffset, whiteFirst, pattern, new Int32Array(pattern.length));\n };\n /**\n * @param row row of black/white values to search\n * @param rowOffset position to start search\n * @param whiteFirst if true, indicates that the pattern specifies white/black/white/...\n * pixel counts, otherwise, it is interpreted as black/white/black/...\n * @param pattern pattern of counts of number of black and white pixels that are being\n * searched for as a pattern\n * @param counters array of counters, as long as pattern, to re-use\n * @return start/end horizontal offset of guard pattern, as an array of two ints\n * @throws NotFoundException if pattern is not found\n */\n AbstractUPCEANReader.findGuardPattern = function (row, rowOffset, whiteFirst, pattern, counters) {\n var width = row.getSize();\n rowOffset = whiteFirst ? row.getNextUnset(rowOffset) : row.getNextSet(rowOffset);\n var counterPosition = 0;\n var patternStart = rowOffset;\n var patternLength = pattern.length;\n var isWhite = whiteFirst;\n for (var x = rowOffset; x < width; x++) {\n if (row.get(x) !== isWhite) {\n counters[counterPosition]++;\n }\n else {\n if (counterPosition === patternLength - 1) {\n if (OneDReader.patternMatchVariance(counters, pattern, AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE) < AbstractUPCEANReader.MAX_AVG_VARIANCE) {\n return Int32Array.from([patternStart, x]);\n }\n patternStart += counters[0] + counters[1];\n var slice = counters.slice(2, counters.length);\n for (var i = 0; i < counterPosition - 1; i++) {\n counters[i] = slice[i];\n }\n counters[counterPosition - 1] = 0;\n counters[counterPosition] = 0;\n counterPosition--;\n }\n else {\n counterPosition++;\n }\n counters[counterPosition] = 1;\n isWhite = !isWhite;\n }\n }\n throw new NotFoundException();\n };\n AbstractUPCEANReader.decodeDigit = function (row, counters, rowOffset, patterns) {\n this.recordPattern(row, rowOffset, counters);\n var bestVariance = this.MAX_AVG_VARIANCE;\n var bestMatch = -1;\n var max = patterns.length;\n for (var i = 0; i < max; i++) {\n var pattern = patterns[i];\n var variance = OneDReader.patternMatchVariance(counters, pattern, AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE);\n if (variance < bestVariance) {\n bestVariance = variance;\n bestMatch = i;\n }\n }\n if (bestMatch >= 0) {\n return bestMatch;\n }\n else {\n throw new NotFoundException();\n }\n };\n // These two values are critical for determining how permissive the decoding will be.\n // We've arrived at these values through a lot of trial and error. Setting them any higher\n // lets false positives creep in quickly.\n AbstractUPCEANReader.MAX_AVG_VARIANCE = 0.48;\n AbstractUPCEANReader.MAX_INDIVIDUAL_VARIANCE = 0.7;\n /**\n * Start/end guard pattern.\n */\n AbstractUPCEANReader.START_END_PATTERN = Int32Array.from([1, 1, 1]);\n /**\n * Pattern marking the middle of a UPC/EAN pattern, separating the two halves.\n */\n AbstractUPCEANReader.MIDDLE_PATTERN = Int32Array.from([1, 1, 1, 1, 1]);\n /**\n * end guard pattern.\n */\n AbstractUPCEANReader.END_PATTERN = Int32Array.from([1, 1, 1, 1, 1, 1]);\n /**\n * \"Odd\", or \"L\" patterns used to encode UPC/EAN digits.\n */\n AbstractUPCEANReader.L_PATTERNS = [\n Int32Array.from([3, 2, 1, 1]),\n Int32Array.from([2, 2, 2, 1]),\n Int32Array.from([2, 1, 2, 2]),\n Int32Array.from([1, 4, 1, 1]),\n Int32Array.from([1, 1, 3, 2]),\n Int32Array.from([1, 2, 3, 1]),\n Int32Array.from([1, 1, 1, 4]),\n Int32Array.from([1, 3, 1, 2]),\n Int32Array.from([1, 2, 1, 3]),\n Int32Array.from([3, 1, 1, 2]),\n ];\n return AbstractUPCEANReader;\n}(OneDReader));\nexport default AbstractUPCEANReader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/*namespace com.google.zxing.oned {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport NotFoundException from '../NotFoundException';\nimport OneDReader from './OneDReader';\nimport Result from '../Result';\nimport ResultPoint from '../ResultPoint';\n/**\n *Decodes CodaBar barcodes.
\n *\n * @author Evan @dodobelieve\n * @see CodaBarReader\n */\nvar CodaBarReader = /** @class */ (function (_super) {\n __extends(CodaBarReader, _super);\n function CodaBarReader() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.CODA_BAR_CHAR_SET = {\n nnnnnww: '0',\n nnnnwwn: '1',\n nnnwnnw: '2',\n wwnnnnn: '3',\n nnwnnwn: '4',\n wnnnnwn: '5',\n nwnnnnw: '6',\n nwnnwnn: '7',\n nwwnnnn: '8',\n wnnwnnn: '9',\n nnnwwnn: '-',\n nnwwnnn: '$',\n wnnnwnw: ':',\n wnwnnnw: '/',\n wnwnwnn: '.',\n nnwwwww: '+',\n nnwwnwn: 'A',\n nwnwnnw: 'B',\n nnnwnww: 'C',\n nnnwwwn: 'D'\n };\n return _this;\n }\n CodaBarReader.prototype.decodeRow = function (rowNumber, row, hints) {\n var validRowData = this.getValidRowData(row);\n if (!validRowData)\n throw new NotFoundException();\n var retStr = this.codaBarDecodeRow(validRowData.row);\n if (!retStr)\n throw new NotFoundException();\n return new Result(retStr, null, 0, [new ResultPoint(validRowData.left, rowNumber), new ResultPoint(validRowData.right, rowNumber)], BarcodeFormat.CODABAR, new Date().getTime());\n };\n /**\n * converts bit array to valid data array(lengths of black bits and white bits)\n * @param row bit array to convert\n */\n CodaBarReader.prototype.getValidRowData = function (row) {\n var booleanArr = row.toArray();\n var startIndex = booleanArr.indexOf(true);\n if (startIndex === -1)\n return null;\n var lastIndex = booleanArr.lastIndexOf(true);\n if (lastIndex <= startIndex)\n return null;\n booleanArr = booleanArr.slice(startIndex, lastIndex + 1);\n var result = [];\n var lastBit = booleanArr[0];\n var bitLength = 1;\n for (var i = 1; i < booleanArr.length; i++) {\n if (booleanArr[i] === lastBit) {\n bitLength++;\n }\n else {\n lastBit = booleanArr[i];\n result.push(bitLength);\n bitLength = 1;\n }\n }\n result.push(bitLength);\n // CodaBar code data valid\n if (result.length < 23 && (result.length + 1) % 8 !== 0)\n return null;\n return { row: result, left: startIndex, right: lastIndex };\n };\n /**\n * decode codabar code\n * @param row row to cecode\n */\n CodaBarReader.prototype.codaBarDecodeRow = function (row) {\n var code = [];\n var barThreshold = Math.ceil(row.reduce(function (pre, item) { return (pre + item) / 2; }, 0));\n // Read one encoded character at a time.\n while (row.length > 0) {\n var seg = row.splice(0, 8).splice(0, 7);\n var key = seg.map(function (len) { return (len < barThreshold ? 'n' : 'w'); }).join('');\n if (this.CODA_BAR_CHAR_SET[key] === undefined)\n return null;\n code.push(this.CODA_BAR_CHAR_SET[key]);\n }\n var strCode = code.join('');\n if (this.validCodaBarString(strCode))\n return strCode;\n return null;\n };\n /**\n * check if the string is a CodaBar string\n * @param src string to determine\n */\n CodaBarReader.prototype.validCodaBarString = function (src) {\n var reg = /^[A-D].{1,}[A-D]$/;\n return reg.test(src);\n };\n return CodaBarReader;\n}(OneDReader));\nexport default CodaBarReader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/*namespace com.google.zxing.oned {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport ChecksumException from '../ChecksumException';\nimport DecodeHintType from '../DecodeHintType';\nimport FormatException from '../FormatException';\nimport NotFoundException from '../NotFoundException';\n// import Reader from '../Reader';\nimport Result from '../Result';\n// import ResultMetadataType from '../ResultMetadataType';\nimport ResultPoint from '../ResultPoint';\nimport OneDReader from './OneDReader';\n/**\n *Decodes Code 128 barcodes.
\n *\n * @author Sean Owen\n */\nvar Code128Reader = /** @class */ (function (_super) {\n __extends(Code128Reader, _super);\n function Code128Reader() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Code128Reader.findStartPattern = function (row) {\n var width = row.getSize();\n var rowOffset = row.getNextSet(0);\n var counterPosition = 0;\n var counters = Int32Array.from([0, 0, 0, 0, 0, 0]);\n var patternStart = rowOffset;\n var isWhite = false;\n var patternLength = 6;\n for (var i = rowOffset; i < width; i++) {\n if (row.get(i) !== isWhite) {\n counters[counterPosition]++;\n }\n else {\n if (counterPosition === (patternLength - 1)) {\n var bestVariance = Code128Reader.MAX_AVG_VARIANCE;\n var bestMatch = -1;\n for (var startCode = Code128Reader.CODE_START_A; startCode <= Code128Reader.CODE_START_C; startCode++) {\n var variance = OneDReader.patternMatchVariance(counters, Code128Reader.CODE_PATTERNS[startCode], Code128Reader.MAX_INDIVIDUAL_VARIANCE);\n if (variance < bestVariance) {\n bestVariance = variance;\n bestMatch = startCode;\n }\n }\n // Look for whitespace before start pattern, >= 50% of width of start pattern\n if (bestMatch >= 0 &&\n row.isRange(Math.max(0, patternStart - (i - patternStart) / 2), patternStart, false)) {\n return Int32Array.from([patternStart, i, bestMatch]);\n }\n patternStart += counters[0] + counters[1];\n counters = counters.slice(2, counters.length);\n counters[counterPosition - 1] = 0;\n counters[counterPosition] = 0;\n counterPosition--;\n }\n else {\n counterPosition++;\n }\n counters[counterPosition] = 1;\n isWhite = !isWhite;\n }\n }\n throw new NotFoundException();\n };\n Code128Reader.decodeCode = function (row, counters, rowOffset) {\n OneDReader.recordPattern(row, rowOffset, counters);\n var bestVariance = Code128Reader.MAX_AVG_VARIANCE; // worst variance we'll accept\n var bestMatch = -1;\n for (var d = 0; d < Code128Reader.CODE_PATTERNS.length; d++) {\n var pattern = Code128Reader.CODE_PATTERNS[d];\n var variance = this.patternMatchVariance(counters, pattern, Code128Reader.MAX_INDIVIDUAL_VARIANCE);\n if (variance < bestVariance) {\n bestVariance = variance;\n bestMatch = d;\n }\n }\n // TODO We're overlooking the fact that the STOP pattern has 7 values, not 6.\n if (bestMatch >= 0) {\n return bestMatch;\n }\n else {\n throw new NotFoundException();\n }\n };\n Code128Reader.prototype.decodeRow = function (rowNumber, row, hints) {\n var convertFNC1 = hints && (hints.get(DecodeHintType.ASSUME_GS1) === true);\n var startPatternInfo = Code128Reader.findStartPattern(row);\n var startCode = startPatternInfo[2];\n var currentRawCodesIndex = 0;\n var rawCodes = new Uint8Array(20);\n rawCodes[currentRawCodesIndex++] = startCode;\n var codeSet;\n switch (startCode) {\n case Code128Reader.CODE_START_A:\n codeSet = Code128Reader.CODE_CODE_A;\n break;\n case Code128Reader.CODE_START_B:\n codeSet = Code128Reader.CODE_CODE_B;\n break;\n case Code128Reader.CODE_START_C:\n codeSet = Code128Reader.CODE_CODE_C;\n break;\n default:\n throw new FormatException();\n }\n var done = false;\n var isNextShifted = false;\n var result = '';\n var lastStart = startPatternInfo[0];\n var nextStart = startPatternInfo[1];\n var counters = Int32Array.from([0, 0, 0, 0, 0, 0]);\n var lastCode = 0;\n var code = 0;\n var checksumTotal = startCode;\n var multiplier = 0;\n var lastCharacterWasPrintable = true;\n var upperMode = false;\n var shiftUpperMode = false;\n while (!done) {\n var unshift = isNextShifted;\n isNextShifted = false;\n // Save off last code\n lastCode = code;\n // Decode another code from image\n code = Code128Reader.decodeCode(row, counters, nextStart);\n rawCodes[currentRawCodesIndex++] = code;\n // Remember whether the last code was printable or not (excluding CODE_STOP)\n if (code !== Code128Reader.CODE_STOP) {\n lastCharacterWasPrintable = true;\n }\n // Add to checksum computation (if not CODE_STOP of course)\n if (code !== Code128Reader.CODE_STOP) {\n multiplier++;\n checksumTotal += multiplier * code;\n }\n // Advance to where the next code will to start\n lastStart = nextStart;\n nextStart += counters.reduce(function (previous, current) { return previous + current; }, 0);\n // Take care of illegal start codes\n switch (code) {\n case Code128Reader.CODE_START_A:\n case Code128Reader.CODE_START_B:\n case Code128Reader.CODE_START_C:\n throw new FormatException();\n }\n switch (codeSet) {\n case Code128Reader.CODE_CODE_A:\n if (code < 64) {\n if (shiftUpperMode === upperMode) {\n result += String.fromCharCode((' '.charCodeAt(0) + code));\n }\n else {\n result += String.fromCharCode((' '.charCodeAt(0) + code + 128));\n }\n shiftUpperMode = false;\n }\n else if (code < 96) {\n if (shiftUpperMode === upperMode) {\n result += String.fromCharCode((code - 64));\n }\n else {\n result += String.fromCharCode((code + 64));\n }\n shiftUpperMode = false;\n }\n else {\n // Don't let CODE_STOP, which always appears, affect whether whether we think the last\n // code was printable or not.\n if (code !== Code128Reader.CODE_STOP) {\n lastCharacterWasPrintable = false;\n }\n switch (code) {\n case Code128Reader.CODE_FNC_1:\n if (convertFNC1) {\n if (result.length === 0) {\n // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code\n // is FNC1 then this is GS1-128. We add the symbology identifier.\n result += ']C1';\n }\n else {\n // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)\n result += String.fromCharCode(29);\n }\n }\n break;\n case Code128Reader.CODE_FNC_2:\n case Code128Reader.CODE_FNC_3:\n // do nothing?\n break;\n case Code128Reader.CODE_FNC_4_A:\n if (!upperMode && shiftUpperMode) {\n upperMode = true;\n shiftUpperMode = false;\n }\n else if (upperMode && shiftUpperMode) {\n upperMode = false;\n shiftUpperMode = false;\n }\n else {\n shiftUpperMode = true;\n }\n break;\n case Code128Reader.CODE_SHIFT:\n isNextShifted = true;\n codeSet = Code128Reader.CODE_CODE_B;\n break;\n case Code128Reader.CODE_CODE_B:\n codeSet = Code128Reader.CODE_CODE_B;\n break;\n case Code128Reader.CODE_CODE_C:\n codeSet = Code128Reader.CODE_CODE_C;\n break;\n case Code128Reader.CODE_STOP:\n done = true;\n break;\n }\n }\n break;\n case Code128Reader.CODE_CODE_B:\n if (code < 96) {\n if (shiftUpperMode === upperMode) {\n result += String.fromCharCode((' '.charCodeAt(0) + code));\n }\n else {\n result += String.fromCharCode((' '.charCodeAt(0) + code + 128));\n }\n shiftUpperMode = false;\n }\n else {\n if (code !== Code128Reader.CODE_STOP) {\n lastCharacterWasPrintable = false;\n }\n switch (code) {\n case Code128Reader.CODE_FNC_1:\n if (convertFNC1) {\n if (result.length === 0) {\n // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code\n // is FNC1 then this is GS1-128. We add the symbology identifier.\n result += ']C1';\n }\n else {\n // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)\n result += String.fromCharCode(29);\n }\n }\n break;\n case Code128Reader.CODE_FNC_2:\n case Code128Reader.CODE_FNC_3:\n // do nothing?\n break;\n case Code128Reader.CODE_FNC_4_B:\n if (!upperMode && shiftUpperMode) {\n upperMode = true;\n shiftUpperMode = false;\n }\n else if (upperMode && shiftUpperMode) {\n upperMode = false;\n shiftUpperMode = false;\n }\n else {\n shiftUpperMode = true;\n }\n break;\n case Code128Reader.CODE_SHIFT:\n isNextShifted = true;\n codeSet = Code128Reader.CODE_CODE_A;\n break;\n case Code128Reader.CODE_CODE_A:\n codeSet = Code128Reader.CODE_CODE_A;\n break;\n case Code128Reader.CODE_CODE_C:\n codeSet = Code128Reader.CODE_CODE_C;\n break;\n case Code128Reader.CODE_STOP:\n done = true;\n break;\n }\n }\n break;\n case Code128Reader.CODE_CODE_C:\n if (code < 100) {\n if (code < 10) {\n result += '0';\n }\n result += code;\n }\n else {\n if (code !== Code128Reader.CODE_STOP) {\n lastCharacterWasPrintable = false;\n }\n switch (code) {\n case Code128Reader.CODE_FNC_1:\n if (convertFNC1) {\n if (result.length === 0) {\n // GS1 specification 5.4.3.7. and 5.4.6.4. If the first char after the start code\n // is FNC1 then this is GS1-128. We add the symbology identifier.\n result += ']C1';\n }\n else {\n // GS1 specification 5.4.7.5. Every subsequent FNC1 is returned as ASCII 29 (GS)\n result += String.fromCharCode(29);\n }\n }\n break;\n case Code128Reader.CODE_CODE_A:\n codeSet = Code128Reader.CODE_CODE_A;\n break;\n case Code128Reader.CODE_CODE_B:\n codeSet = Code128Reader.CODE_CODE_B;\n break;\n case Code128Reader.CODE_STOP:\n done = true;\n break;\n }\n }\n break;\n }\n // Unshift back to another code set if we were shifted\n if (unshift) {\n codeSet = codeSet === Code128Reader.CODE_CODE_A ? Code128Reader.CODE_CODE_B : Code128Reader.CODE_CODE_A;\n }\n }\n var lastPatternSize = nextStart - lastStart;\n // Check for ample whitespace following pattern, but, to do this we first need to remember that\n // we fudged decoding CODE_STOP since it actually has 7 bars, not 6. There is a black bar left\n // to read off. Would be slightly better to properly read. Here we just skip it:\n nextStart = row.getNextUnset(nextStart);\n if (!row.isRange(nextStart, Math.min(row.getSize(), nextStart + (nextStart - lastStart) / 2), false)) {\n throw new NotFoundException();\n }\n // Pull out from sum the value of the penultimate check code\n checksumTotal -= multiplier * lastCode;\n // lastCode is the checksum then:\n if (checksumTotal % 103 !== lastCode) {\n throw new ChecksumException();\n }\n // Need to pull out the check digits from string\n var resultLength = result.length;\n if (resultLength === 0) {\n // false positive\n throw new NotFoundException();\n }\n // Only bother if the result had at least one character, and if the checksum digit happened to\n // be a printable character. If it was just interpreted as a control code, nothing to remove.\n if (resultLength > 0 && lastCharacterWasPrintable) {\n if (codeSet === Code128Reader.CODE_CODE_C) {\n result = result.substring(0, resultLength - 2);\n }\n else {\n result = result.substring(0, resultLength - 1);\n }\n }\n var left = (startPatternInfo[1] + startPatternInfo[0]) / 2.0;\n var right = lastStart + lastPatternSize / 2.0;\n var rawCodesSize = rawCodes.length;\n var rawBytes = new Uint8Array(rawCodesSize);\n for (var i = 0; i < rawCodesSize; i++) {\n rawBytes[i] = rawCodes[i];\n }\n var points = [new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)];\n return new Result(result, rawBytes, 0, points, BarcodeFormat.CODE_128, new Date().getTime());\n };\n Code128Reader.CODE_PATTERNS = [\n Int32Array.from([2, 1, 2, 2, 2, 2]),\n Int32Array.from([2, 2, 2, 1, 2, 2]),\n Int32Array.from([2, 2, 2, 2, 2, 1]),\n Int32Array.from([1, 2, 1, 2, 2, 3]),\n Int32Array.from([1, 2, 1, 3, 2, 2]),\n Int32Array.from([1, 3, 1, 2, 2, 2]),\n Int32Array.from([1, 2, 2, 2, 1, 3]),\n Int32Array.from([1, 2, 2, 3, 1, 2]),\n Int32Array.from([1, 3, 2, 2, 1, 2]),\n Int32Array.from([2, 2, 1, 2, 1, 3]),\n Int32Array.from([2, 2, 1, 3, 1, 2]),\n Int32Array.from([2, 3, 1, 2, 1, 2]),\n Int32Array.from([1, 1, 2, 2, 3, 2]),\n Int32Array.from([1, 2, 2, 1, 3, 2]),\n Int32Array.from([1, 2, 2, 2, 3, 1]),\n Int32Array.from([1, 1, 3, 2, 2, 2]),\n Int32Array.from([1, 2, 3, 1, 2, 2]),\n Int32Array.from([1, 2, 3, 2, 2, 1]),\n Int32Array.from([2, 2, 3, 2, 1, 1]),\n Int32Array.from([2, 2, 1, 1, 3, 2]),\n Int32Array.from([2, 2, 1, 2, 3, 1]),\n Int32Array.from([2, 1, 3, 2, 1, 2]),\n Int32Array.from([2, 2, 3, 1, 1, 2]),\n Int32Array.from([3, 1, 2, 1, 3, 1]),\n Int32Array.from([3, 1, 1, 2, 2, 2]),\n Int32Array.from([3, 2, 1, 1, 2, 2]),\n Int32Array.from([3, 2, 1, 2, 2, 1]),\n Int32Array.from([3, 1, 2, 2, 1, 2]),\n Int32Array.from([3, 2, 2, 1, 1, 2]),\n Int32Array.from([3, 2, 2, 2, 1, 1]),\n Int32Array.from([2, 1, 2, 1, 2, 3]),\n Int32Array.from([2, 1, 2, 3, 2, 1]),\n Int32Array.from([2, 3, 2, 1, 2, 1]),\n Int32Array.from([1, 1, 1, 3, 2, 3]),\n Int32Array.from([1, 3, 1, 1, 2, 3]),\n Int32Array.from([1, 3, 1, 3, 2, 1]),\n Int32Array.from([1, 1, 2, 3, 1, 3]),\n Int32Array.from([1, 3, 2, 1, 1, 3]),\n Int32Array.from([1, 3, 2, 3, 1, 1]),\n Int32Array.from([2, 1, 1, 3, 1, 3]),\n Int32Array.from([2, 3, 1, 1, 1, 3]),\n Int32Array.from([2, 3, 1, 3, 1, 1]),\n Int32Array.from([1, 1, 2, 1, 3, 3]),\n Int32Array.from([1, 1, 2, 3, 3, 1]),\n Int32Array.from([1, 3, 2, 1, 3, 1]),\n Int32Array.from([1, 1, 3, 1, 2, 3]),\n Int32Array.from([1, 1, 3, 3, 2, 1]),\n Int32Array.from([1, 3, 3, 1, 2, 1]),\n Int32Array.from([3, 1, 3, 1, 2, 1]),\n Int32Array.from([2, 1, 1, 3, 3, 1]),\n Int32Array.from([2, 3, 1, 1, 3, 1]),\n Int32Array.from([2, 1, 3, 1, 1, 3]),\n Int32Array.from([2, 1, 3, 3, 1, 1]),\n Int32Array.from([2, 1, 3, 1, 3, 1]),\n Int32Array.from([3, 1, 1, 1, 2, 3]),\n Int32Array.from([3, 1, 1, 3, 2, 1]),\n Int32Array.from([3, 3, 1, 1, 2, 1]),\n Int32Array.from([3, 1, 2, 1, 1, 3]),\n Int32Array.from([3, 1, 2, 3, 1, 1]),\n Int32Array.from([3, 3, 2, 1, 1, 1]),\n Int32Array.from([3, 1, 4, 1, 1, 1]),\n Int32Array.from([2, 2, 1, 4, 1, 1]),\n Int32Array.from([4, 3, 1, 1, 1, 1]),\n Int32Array.from([1, 1, 1, 2, 2, 4]),\n Int32Array.from([1, 1, 1, 4, 2, 2]),\n Int32Array.from([1, 2, 1, 1, 2, 4]),\n Int32Array.from([1, 2, 1, 4, 2, 1]),\n Int32Array.from([1, 4, 1, 1, 2, 2]),\n Int32Array.from([1, 4, 1, 2, 2, 1]),\n Int32Array.from([1, 1, 2, 2, 1, 4]),\n Int32Array.from([1, 1, 2, 4, 1, 2]),\n Int32Array.from([1, 2, 2, 1, 1, 4]),\n Int32Array.from([1, 2, 2, 4, 1, 1]),\n Int32Array.from([1, 4, 2, 1, 1, 2]),\n Int32Array.from([1, 4, 2, 2, 1, 1]),\n Int32Array.from([2, 4, 1, 2, 1, 1]),\n Int32Array.from([2, 2, 1, 1, 1, 4]),\n Int32Array.from([4, 1, 3, 1, 1, 1]),\n Int32Array.from([2, 4, 1, 1, 1, 2]),\n Int32Array.from([1, 3, 4, 1, 1, 1]),\n Int32Array.from([1, 1, 1, 2, 4, 2]),\n Int32Array.from([1, 2, 1, 1, 4, 2]),\n Int32Array.from([1, 2, 1, 2, 4, 1]),\n Int32Array.from([1, 1, 4, 2, 1, 2]),\n Int32Array.from([1, 2, 4, 1, 1, 2]),\n Int32Array.from([1, 2, 4, 2, 1, 1]),\n Int32Array.from([4, 1, 1, 2, 1, 2]),\n Int32Array.from([4, 2, 1, 1, 1, 2]),\n Int32Array.from([4, 2, 1, 2, 1, 1]),\n Int32Array.from([2, 1, 2, 1, 4, 1]),\n Int32Array.from([2, 1, 4, 1, 2, 1]),\n Int32Array.from([4, 1, 2, 1, 2, 1]),\n Int32Array.from([1, 1, 1, 1, 4, 3]),\n Int32Array.from([1, 1, 1, 3, 4, 1]),\n Int32Array.from([1, 3, 1, 1, 4, 1]),\n Int32Array.from([1, 1, 4, 1, 1, 3]),\n Int32Array.from([1, 1, 4, 3, 1, 1]),\n Int32Array.from([4, 1, 1, 1, 1, 3]),\n Int32Array.from([4, 1, 1, 3, 1, 1]),\n Int32Array.from([1, 1, 3, 1, 4, 1]),\n Int32Array.from([1, 1, 4, 1, 3, 1]),\n Int32Array.from([3, 1, 1, 1, 4, 1]),\n Int32Array.from([4, 1, 1, 1, 3, 1]),\n Int32Array.from([2, 1, 1, 4, 1, 2]),\n Int32Array.from([2, 1, 1, 2, 1, 4]),\n Int32Array.from([2, 1, 1, 2, 3, 2]),\n Int32Array.from([2, 3, 3, 1, 1, 1, 2]),\n ];\n Code128Reader.MAX_AVG_VARIANCE = 0.25;\n Code128Reader.MAX_INDIVIDUAL_VARIANCE = 0.7;\n Code128Reader.CODE_SHIFT = 98;\n Code128Reader.CODE_CODE_C = 99;\n Code128Reader.CODE_CODE_B = 100;\n Code128Reader.CODE_CODE_A = 101;\n Code128Reader.CODE_FNC_1 = 102;\n Code128Reader.CODE_FNC_2 = 97;\n Code128Reader.CODE_FNC_3 = 96;\n Code128Reader.CODE_FNC_4_A = 101;\n Code128Reader.CODE_FNC_4_B = 100;\n Code128Reader.CODE_START_A = 103;\n Code128Reader.CODE_START_B = 104;\n Code128Reader.CODE_START_C = 105;\n Code128Reader.CODE_STOP = 106;\n return Code128Reader;\n}(OneDReader));\nexport default Code128Reader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.oned {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport ChecksumException from '../ChecksumException';\nimport FormatException from '../FormatException';\nimport NotFoundException from '../NotFoundException';\nimport OneDReader from './OneDReader';\nimport Result from '../Result';\nimport ResultPoint from '../ResultPoint';\n/**\n *Decodes Code 39 barcodes. Supports \"Full ASCII Code 39\" if USE_CODE_39_EXTENDED_MODE is set.
\n *\n * @author Sean Owen\n * @see Code93Reader\n */\nvar Code39Reader = /** @class */ (function (_super) {\n __extends(Code39Reader, _super);\n /**\n * Creates a reader that assumes all encoded data is data, and does not treat the final\n * character as a check digit. It will not decoded \"extended Code 39\" sequences.\n */\n // public Code39Reader() {\n // this(false);\n // }\n /**\n * Creates a reader that can be configured to check the last character as a check digit.\n * It will not decoded \"extended Code 39\" sequences.\n *\n * @param usingCheckDigit if true, treat the last data character as a check digit, not\n * data, and verify that the checksum passes.\n */\n // public Code39Reader(boolean usingCheckDigit) {\n // this(usingCheckDigit, false);\n // }\n /**\n * Creates a reader that can be configured to check the last character as a check digit,\n * or optionally attempt to decode \"extended Code 39\" sequences that are used to encode\n * the full ASCII character set.\n *\n * @param usingCheckDigit if true, treat the last data character as a check digit, not\n * data, and verify that the checksum passes.\n * @param extendedMode if true, will attempt to decode extended Code 39 sequences in the\n * text.\n */\n function Code39Reader(usingCheckDigit, extendedMode) {\n if (usingCheckDigit === void 0) { usingCheckDigit = false; }\n if (extendedMode === void 0) { extendedMode = false; }\n var _this = _super.call(this) || this;\n _this.usingCheckDigit = usingCheckDigit;\n _this.extendedMode = extendedMode;\n _this.decodeRowResult = '';\n _this.counters = new Int32Array(9);\n return _this;\n }\n Code39Reader.prototype.decodeRow = function (rowNumber, row, hints) {\n var e_1, _a, e_2, _b;\n var theCounters = this.counters;\n theCounters.fill(0);\n this.decodeRowResult = '';\n var start = Code39Reader.findAsteriskPattern(row, theCounters);\n // Read off white space\n var nextStart = row.getNextSet(start[1]);\n var end = row.getSize();\n var decodedChar;\n var lastStart;\n do {\n Code39Reader.recordPattern(row, nextStart, theCounters);\n var pattern = Code39Reader.toNarrowWidePattern(theCounters);\n if (pattern < 0) {\n throw new NotFoundException();\n }\n decodedChar = Code39Reader.patternToChar(pattern);\n this.decodeRowResult += decodedChar;\n lastStart = nextStart;\n try {\n for (var theCounters_1 = (e_1 = void 0, __values(theCounters)), theCounters_1_1 = theCounters_1.next(); !theCounters_1_1.done; theCounters_1_1 = theCounters_1.next()) {\n var counter = theCounters_1_1.value;\n nextStart += counter;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (theCounters_1_1 && !theCounters_1_1.done && (_a = theCounters_1.return)) _a.call(theCounters_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Read off white space\n nextStart = row.getNextSet(nextStart);\n } while (decodedChar !== '*');\n this.decodeRowResult = this.decodeRowResult.substring(0, this.decodeRowResult.length - 1); // remove asterisk\n // Look for whitespace after pattern:\n var lastPatternSize = 0;\n try {\n for (var theCounters_2 = __values(theCounters), theCounters_2_1 = theCounters_2.next(); !theCounters_2_1.done; theCounters_2_1 = theCounters_2.next()) {\n var counter = theCounters_2_1.value;\n lastPatternSize += counter;\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (theCounters_2_1 && !theCounters_2_1.done && (_b = theCounters_2.return)) _b.call(theCounters_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n var whiteSpaceAfterEnd = nextStart - lastStart - lastPatternSize;\n // If 50% of last pattern size, following last pattern, is not whitespace, fail\n // (but if it's whitespace to the very end of the image, that's OK)\n if (nextStart !== end && (whiteSpaceAfterEnd * 2) < lastPatternSize) {\n throw new NotFoundException();\n }\n if (this.usingCheckDigit) {\n var max = this.decodeRowResult.length - 1;\n var total = 0;\n for (var i = 0; i < max; i++) {\n total += Code39Reader.ALPHABET_STRING.indexOf(this.decodeRowResult.charAt(i));\n }\n if (this.decodeRowResult.charAt(max) !== Code39Reader.ALPHABET_STRING.charAt(total % 43)) {\n throw new ChecksumException();\n }\n this.decodeRowResult = this.decodeRowResult.substring(0, max);\n }\n if (this.decodeRowResult.length === 0) {\n // false positive\n throw new NotFoundException();\n }\n var resultString;\n if (this.extendedMode) {\n resultString = Code39Reader.decodeExtended(this.decodeRowResult);\n }\n else {\n resultString = this.decodeRowResult;\n }\n var left = (start[1] + start[0]) / 2.0;\n var right = lastStart + lastPatternSize / 2.0;\n return new Result(resultString, null, 0, [new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)], BarcodeFormat.CODE_39, new Date().getTime());\n };\n Code39Reader.findAsteriskPattern = function (row, counters) {\n var width = row.getSize();\n var rowOffset = row.getNextSet(0);\n var counterPosition = 0;\n var patternStart = rowOffset;\n var isWhite = false;\n var patternLength = counters.length;\n for (var i = rowOffset; i < width; i++) {\n if (row.get(i) !== isWhite) {\n counters[counterPosition]++;\n }\n else {\n if (counterPosition === patternLength - 1) {\n // Look for whitespace before start pattern, >= 50% of width of start pattern\n if (this.toNarrowWidePattern(counters) === Code39Reader.ASTERISK_ENCODING &&\n row.isRange(Math.max(0, patternStart - Math.floor((i - patternStart) / 2)), patternStart, false)) {\n return [patternStart, i];\n }\n patternStart += counters[0] + counters[1];\n counters.copyWithin(0, 2, 2 + counterPosition - 1);\n counters[counterPosition - 1] = 0;\n counters[counterPosition] = 0;\n counterPosition--;\n }\n else {\n counterPosition++;\n }\n counters[counterPosition] = 1;\n isWhite = !isWhite;\n }\n }\n throw new NotFoundException();\n };\n // For efficiency, returns -1 on failure. Not throwing here saved as many as 700 exceptions\n // per image when using some of our blackbox images.\n Code39Reader.toNarrowWidePattern = function (counters) {\n var e_3, _a;\n var numCounters = counters.length;\n var maxNarrowCounter = 0;\n var wideCounters;\n do {\n var minCounter = 0x7fffffff;\n try {\n for (var counters_1 = (e_3 = void 0, __values(counters)), counters_1_1 = counters_1.next(); !counters_1_1.done; counters_1_1 = counters_1.next()) {\n var counter = counters_1_1.value;\n if (counter < minCounter && counter > maxNarrowCounter) {\n minCounter = counter;\n }\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (counters_1_1 && !counters_1_1.done && (_a = counters_1.return)) _a.call(counters_1);\n }\n finally { if (e_3) throw e_3.error; }\n }\n maxNarrowCounter = minCounter;\n wideCounters = 0;\n var totalWideCountersWidth = 0;\n var pattern = 0;\n for (var i = 0; i < numCounters; i++) {\n var counter = counters[i];\n if (counter > maxNarrowCounter) {\n pattern |= 1 << (numCounters - 1 - i);\n wideCounters++;\n totalWideCountersWidth += counter;\n }\n }\n if (wideCounters === 3) {\n // Found 3 wide counters, but are they close enough in width?\n // We can perform a cheap, conservative check to see if any individual\n // counter is more than 1.5 times the average:\n for (var i = 0; i < numCounters && wideCounters > 0; i++) {\n var counter = counters[i];\n if (counter > maxNarrowCounter) {\n wideCounters--;\n // totalWideCountersWidth = 3 * average, so this checks if counter >= 3/2 * average\n if ((counter * 2) >= totalWideCountersWidth) {\n return -1;\n }\n }\n }\n return pattern;\n }\n } while (wideCounters > 3);\n return -1;\n };\n Code39Reader.patternToChar = function (pattern) {\n for (var i = 0; i < Code39Reader.CHARACTER_ENCODINGS.length; i++) {\n if (Code39Reader.CHARACTER_ENCODINGS[i] === pattern) {\n return Code39Reader.ALPHABET_STRING.charAt(i);\n }\n }\n if (pattern === Code39Reader.ASTERISK_ENCODING) {\n return '*';\n }\n throw new NotFoundException();\n };\n Code39Reader.decodeExtended = function (encoded) {\n var length = encoded.length;\n var decoded = '';\n for (var i = 0; i < length; i++) {\n var c = encoded.charAt(i);\n if (c === '+' || c === '$' || c === '%' || c === '/') {\n var next = encoded.charAt(i + 1);\n var decodedChar = '\\0';\n switch (c) {\n case '+':\n // +A to +Z map to a to z\n if (next >= 'A' && next <= 'Z') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) + 32);\n }\n else {\n throw new FormatException();\n }\n break;\n case '$':\n // $A to $Z map to control codes SH to SB\n if (next >= 'A' && next <= 'Z') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) - 64);\n }\n else {\n throw new FormatException();\n }\n break;\n case '%':\n // %A to %E map to control codes ESC to US\n if (next >= 'A' && next <= 'E') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) - 38);\n }\n else if (next >= 'F' && next <= 'J') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) - 11);\n }\n else if (next >= 'K' && next <= 'O') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) + 16);\n }\n else if (next >= 'P' && next <= 'T') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) + 43);\n }\n else if (next === 'U') {\n decodedChar = '\\0';\n }\n else if (next === 'V') {\n decodedChar = '@';\n }\n else if (next === 'W') {\n decodedChar = '`';\n }\n else if (next === 'X' || next === 'Y' || next === 'Z') {\n decodedChar = '\\x7f';\n }\n else {\n throw new FormatException();\n }\n break;\n case '/':\n // /A to /O map to ! to , and /Z maps to :\n if (next >= 'A' && next <= 'O') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) - 32);\n }\n else if (next === 'Z') {\n decodedChar = ':';\n }\n else {\n throw new FormatException();\n }\n break;\n }\n decoded += decodedChar;\n // bump up i again since we read two characters\n i++;\n }\n else {\n decoded += c;\n }\n }\n return decoded;\n };\n Code39Reader.ALPHABET_STRING = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%';\n /**\n * These represent the encodings of characters, as patterns of wide and narrow bars.\n * The 9 least-significant bits of each int correspond to the pattern of wide and narrow,\n * with 1s representing \"wide\" and 0s representing narrow.\n */\n Code39Reader.CHARACTER_ENCODINGS = [\n 0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064,\n 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C,\n 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016,\n 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x0A8,\n 0x0A2, 0x08A, 0x02A // /-%\n ];\n Code39Reader.ASTERISK_ENCODING = 0x094;\n return Code39Reader;\n}(OneDReader));\nexport default Code39Reader;\n","/*\n * Copyright 2010 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.oned {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport ChecksumException from '../ChecksumException';\nimport FormatException from '../FormatException';\nimport NotFoundException from '../NotFoundException';\nimport OneDReader from './OneDReader';\nimport Result from '../Result';\n//import com.google.zxing.ResultMetadataType;\nimport ResultPoint from '../ResultPoint';\n/**\n *Decodes Code 93 barcodes.
\n *\n * @author Sean Owen\n * @see Code39Reader\n */\nvar Code93Reader = /** @class */ (function (_super) {\n __extends(Code93Reader, _super);\n //public Code93Reader() {\n // decodeRowResult = new StringBuilder(20);\n // counters = new int[6];\n //}\n function Code93Reader() {\n var _this = _super.call(this) || this;\n _this.decodeRowResult = '';\n _this.counters = new Int32Array(6);\n return _this;\n }\n Code93Reader.prototype.decodeRow = function (rowNumber, row, hints) {\n var e_1, _a, e_2, _b;\n var start = this.findAsteriskPattern(row);\n // Read off white space\n var nextStart = row.getNextSet(start[1]);\n var end = row.getSize();\n var theCounters = this.counters;\n theCounters.fill(0);\n this.decodeRowResult = '';\n var decodedChar;\n var lastStart;\n do {\n Code93Reader.recordPattern(row, nextStart, theCounters);\n var pattern = this.toPattern(theCounters);\n if (pattern < 0) {\n throw new NotFoundException();\n }\n decodedChar = this.patternToChar(pattern);\n this.decodeRowResult += decodedChar;\n lastStart = nextStart;\n try {\n for (var theCounters_1 = (e_1 = void 0, __values(theCounters)), theCounters_1_1 = theCounters_1.next(); !theCounters_1_1.done; theCounters_1_1 = theCounters_1.next()) {\n var counter = theCounters_1_1.value;\n nextStart += counter;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (theCounters_1_1 && !theCounters_1_1.done && (_a = theCounters_1.return)) _a.call(theCounters_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Read off white space\n nextStart = row.getNextSet(nextStart);\n } while (decodedChar !== '*');\n this.decodeRowResult = this.decodeRowResult.substring(0, this.decodeRowResult.length - 1); // remove asterisk\n var lastPatternSize = 0;\n try {\n for (var theCounters_2 = __values(theCounters), theCounters_2_1 = theCounters_2.next(); !theCounters_2_1.done; theCounters_2_1 = theCounters_2.next()) {\n var counter = theCounters_2_1.value;\n lastPatternSize += counter;\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (theCounters_2_1 && !theCounters_2_1.done && (_b = theCounters_2.return)) _b.call(theCounters_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n // Should be at least one more black module\n if (nextStart === end || !row.get(nextStart)) {\n throw new NotFoundException();\n }\n if (this.decodeRowResult.length < 2) {\n // false positive -- need at least 2 checksum digits\n throw new NotFoundException();\n }\n this.checkChecksums(this.decodeRowResult);\n // Remove checksum digits\n this.decodeRowResult = this.decodeRowResult.substring(0, this.decodeRowResult.length - 2);\n var resultString = this.decodeExtended(this.decodeRowResult);\n var left = (start[1] + start[0]) / 2.0;\n var right = lastStart + lastPatternSize / 2.0;\n return new Result(resultString, null, 0, [new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)], BarcodeFormat.CODE_93, new Date().getTime());\n };\n Code93Reader.prototype.findAsteriskPattern = function (row) {\n var width = row.getSize();\n var rowOffset = row.getNextSet(0);\n this.counters.fill(0);\n var theCounters = this.counters;\n var patternStart = rowOffset;\n var isWhite = false;\n var patternLength = theCounters.length;\n var counterPosition = 0;\n for (var i = rowOffset; i < width; i++) {\n if (row.get(i) !== isWhite) {\n theCounters[counterPosition]++;\n }\n else {\n if (counterPosition === patternLength - 1) {\n if (this.toPattern(theCounters) === Code93Reader.ASTERISK_ENCODING) {\n return new Int32Array([patternStart, i]);\n }\n patternStart += theCounters[0] + theCounters[1];\n theCounters.copyWithin(0, 2, 2 + counterPosition - 1);\n theCounters[counterPosition - 1] = 0;\n theCounters[counterPosition] = 0;\n counterPosition--;\n }\n else {\n counterPosition++;\n }\n theCounters[counterPosition] = 1;\n isWhite = !isWhite;\n }\n }\n throw new NotFoundException;\n };\n Code93Reader.prototype.toPattern = function (counters) {\n var e_3, _a;\n var sum = 0;\n try {\n for (var counters_1 = __values(counters), counters_1_1 = counters_1.next(); !counters_1_1.done; counters_1_1 = counters_1.next()) {\n var counter = counters_1_1.value;\n sum += counter;\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (counters_1_1 && !counters_1_1.done && (_a = counters_1.return)) _a.call(counters_1);\n }\n finally { if (e_3) throw e_3.error; }\n }\n var pattern = 0;\n var max = counters.length;\n for (var i = 0; i < max; i++) {\n var scaled = Math.round(counters[i] * 9.0 / sum);\n if (scaled < 1 || scaled > 4) {\n return -1;\n }\n if ((i & 0x01) === 0) {\n for (var j = 0; j < scaled; j++) {\n pattern = (pattern << 1) | 0x01;\n }\n }\n else {\n pattern <<= scaled;\n }\n }\n return pattern;\n };\n Code93Reader.prototype.patternToChar = function (pattern) {\n for (var i = 0; i < Code93Reader.CHARACTER_ENCODINGS.length; i++) {\n if (Code93Reader.CHARACTER_ENCODINGS[i] === pattern) {\n return Code93Reader.ALPHABET_STRING.charAt(i);\n }\n }\n throw new NotFoundException();\n };\n Code93Reader.prototype.decodeExtended = function (encoded) {\n var length = encoded.length;\n var decoded = '';\n for (var i = 0; i < length; i++) {\n var c = encoded.charAt(i);\n if (c >= 'a' && c <= 'd') {\n if (i >= length - 1) {\n throw new FormatException();\n }\n var next = encoded.charAt(i + 1);\n var decodedChar = '\\0';\n switch (c) {\n case 'd':\n // +A to +Z map to a to z\n if (next >= 'A' && next <= 'Z') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) + 32);\n }\n else {\n throw new FormatException();\n }\n break;\n case 'a':\n // $A to $Z map to control codes SH to SB\n if (next >= 'A' && next <= 'Z') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) - 64);\n }\n else {\n throw new FormatException();\n }\n break;\n case 'b':\n if (next >= 'A' && next <= 'E') {\n // %A to %E map to control codes ESC to USep\n decodedChar = String.fromCharCode(next.charCodeAt(0) - 38);\n }\n else if (next >= 'F' && next <= 'J') {\n // %F to %J map to ; < = > ?\n decodedChar = String.fromCharCode(next.charCodeAt(0) - 11);\n }\n else if (next >= 'K' && next <= 'O') {\n // %K to %O map to [ \\ ] ^ _\n decodedChar = String.fromCharCode(next.charCodeAt(0) + 16);\n }\n else if (next >= 'P' && next <= 'T') {\n // %P to %T map to { | } ~ DEL\n decodedChar = String.fromCharCode(next.charCodeAt(0) + 43);\n }\n else if (next === 'U') {\n // %U map to NUL\n decodedChar = '\\0';\n }\n else if (next === 'V') {\n // %V map to @\n decodedChar = '@';\n }\n else if (next === 'W') {\n // %W map to `\n decodedChar = '`';\n }\n else if (next >= 'X' && next <= 'Z') {\n // %X to %Z all map to DEL (127)\n decodedChar = String.fromCharCode(127);\n }\n else {\n throw new FormatException();\n }\n break;\n case 'c':\n // /A to /O map to ! to , and /Z maps to :\n if (next >= 'A' && next <= 'O') {\n decodedChar = String.fromCharCode(next.charCodeAt(0) - 32);\n }\n else if (next === 'Z') {\n decodedChar = ':';\n }\n else {\n throw new FormatException();\n }\n break;\n }\n decoded += decodedChar;\n // bump up i again since we read two characters\n i++;\n }\n else {\n decoded += c;\n }\n }\n return decoded;\n };\n Code93Reader.prototype.checkChecksums = function (result) {\n var length = result.length;\n this.checkOneChecksum(result, length - 2, 20);\n this.checkOneChecksum(result, length - 1, 15);\n };\n Code93Reader.prototype.checkOneChecksum = function (result, checkPosition, weightMax) {\n var weight = 1;\n var total = 0;\n for (var i = checkPosition - 1; i >= 0; i--) {\n total += weight * Code93Reader.ALPHABET_STRING.indexOf(result.charAt(i));\n if (++weight > weightMax) {\n weight = 1;\n }\n }\n if (result.charAt(checkPosition) !== Code93Reader.ALPHABET_STRING[total % 47]) {\n throw new ChecksumException;\n }\n };\n // Note that 'abcd' are dummy characters in place of control characters.\n Code93Reader.ALPHABET_STRING = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. $/+%abcd*\";\n /**\n * These represent the encodings of characters, as patterns of wide and narrow bars.\n * The 9 least-significant bits of each int correspond to the pattern of wide and narrow.\n */\n Code93Reader.CHARACTER_ENCODINGS = [\n 0x114, 0x148, 0x144, 0x142, 0x128, 0x124, 0x122, 0x150, 0x112, 0x10A,\n 0x1A8, 0x1A4, 0x1A2, 0x194, 0x192, 0x18A, 0x168, 0x164, 0x162, 0x134,\n 0x11A, 0x158, 0x14C, 0x146, 0x12C, 0x116, 0x1B4, 0x1B2, 0x1AC, 0x1A6,\n 0x196, 0x19A, 0x16C, 0x166, 0x136, 0x13A,\n 0x12E, 0x1D4, 0x1D2, 0x1CA, 0x16E, 0x176, 0x1AE,\n 0x126, 0x1DA, 0x1D6, 0x132, 0x15E,\n ];\n Code93Reader.ASTERISK_ENCODING = Code93Reader.CHARACTER_ENCODINGS[47];\n return Code93Reader;\n}(OneDReader));\nexport default Code93Reader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport BarcodeFormat from '../BarcodeFormat';\nimport UPCEANReader from './UPCEANReader';\nimport NotFoundException from '../NotFoundException';\n/**\n *Implements decoding of the EAN-13 format.
\n *\n * @author dswitkin@google.com (Daniel Switkin)\n * @author Sean Owen\n * @author alasdair@google.com (Alasdair Mackintosh)\n */\nvar EAN13Reader = /** @class */ (function (_super) {\n __extends(EAN13Reader, _super);\n function EAN13Reader() {\n var _this = _super.call(this) || this;\n _this.decodeMiddleCounters = Int32Array.from([0, 0, 0, 0]);\n return _this;\n }\n EAN13Reader.prototype.decodeMiddle = function (row, startRange, resultString) {\n var e_1, _a, e_2, _b;\n var counters = this.decodeMiddleCounters;\n counters[0] = 0;\n counters[1] = 0;\n counters[2] = 0;\n counters[3] = 0;\n var end = row.getSize();\n var rowOffset = startRange[1];\n var lgPatternFound = 0;\n for (var x = 0; x < 6 && rowOffset < end; x++) {\n var bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_AND_G_PATTERNS);\n resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch % 10));\n try {\n for (var counters_1 = (e_1 = void 0, __values(counters)), counters_1_1 = counters_1.next(); !counters_1_1.done; counters_1_1 = counters_1.next()) {\n var counter = counters_1_1.value;\n rowOffset += counter;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (counters_1_1 && !counters_1_1.done && (_a = counters_1.return)) _a.call(counters_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n if (bestMatch >= 10) {\n lgPatternFound |= 1 << (5 - x);\n }\n }\n resultString = EAN13Reader.determineFirstDigit(resultString, lgPatternFound);\n var middleRange = UPCEANReader.findGuardPattern(row, rowOffset, true, UPCEANReader.MIDDLE_PATTERN, new Int32Array(UPCEANReader.MIDDLE_PATTERN.length).fill(0));\n rowOffset = middleRange[1];\n for (var x = 0; x < 6 && rowOffset < end; x++) {\n var bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_PATTERNS);\n resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch));\n try {\n for (var counters_2 = (e_2 = void 0, __values(counters)), counters_2_1 = counters_2.next(); !counters_2_1.done; counters_2_1 = counters_2.next()) {\n var counter = counters_2_1.value;\n rowOffset += counter;\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (counters_2_1 && !counters_2_1.done && (_b = counters_2.return)) _b.call(counters_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n return { rowOffset: rowOffset, resultString: resultString };\n };\n EAN13Reader.prototype.getBarcodeFormat = function () {\n return BarcodeFormat.EAN_13;\n };\n EAN13Reader.determineFirstDigit = function (resultString, lgPatternFound) {\n for (var d = 0; d < 10; d++) {\n if (lgPatternFound === this.FIRST_DIGIT_ENCODINGS[d]) {\n resultString = String.fromCharCode(('0'.charCodeAt(0) + d)) + resultString;\n return resultString;\n }\n }\n throw new NotFoundException();\n };\n EAN13Reader.FIRST_DIGIT_ENCODINGS = [0x00, 0x0B, 0x0D, 0xE, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1A];\n return EAN13Reader;\n}(UPCEANReader));\nexport default EAN13Reader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport BarcodeFormat from '../BarcodeFormat';\nimport UPCEANReader from './UPCEANReader';\n/**\n *Implements decoding of the EAN-8 format.
\n *\n * @author Sean Owen\n */\nvar EAN8Reader = /** @class */ (function (_super) {\n __extends(EAN8Reader, _super);\n function EAN8Reader() {\n var _this = _super.call(this) || this;\n _this.decodeMiddleCounters = Int32Array.from([0, 0, 0, 0]);\n return _this;\n }\n EAN8Reader.prototype.decodeMiddle = function (row, startRange, resultString) {\n var e_1, _a, e_2, _b;\n var counters = this.decodeMiddleCounters;\n counters[0] = 0;\n counters[1] = 0;\n counters[2] = 0;\n counters[3] = 0;\n var end = row.getSize();\n var rowOffset = startRange[1];\n for (var x = 0; x < 4 && rowOffset < end; x++) {\n var bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_PATTERNS);\n resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch));\n try {\n for (var counters_1 = (e_1 = void 0, __values(counters)), counters_1_1 = counters_1.next(); !counters_1_1.done; counters_1_1 = counters_1.next()) {\n var counter = counters_1_1.value;\n rowOffset += counter;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (counters_1_1 && !counters_1_1.done && (_a = counters_1.return)) _a.call(counters_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n var middleRange = UPCEANReader.findGuardPattern(row, rowOffset, true, UPCEANReader.MIDDLE_PATTERN, new Int32Array(UPCEANReader.MIDDLE_PATTERN.length).fill(0));\n rowOffset = middleRange[1];\n for (var x = 0; x < 4 && rowOffset < end; x++) {\n var bestMatch = UPCEANReader.decodeDigit(row, counters, rowOffset, UPCEANReader.L_PATTERNS);\n resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch));\n try {\n for (var counters_2 = (e_2 = void 0, __values(counters)), counters_2_1 = counters_2.next(); !counters_2_1.done; counters_2_1 = counters_2.next()) {\n var counter = counters_2_1.value;\n rowOffset += counter;\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (counters_2_1 && !counters_2_1.done && (_b = counters_2.return)) _b.call(counters_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n return { rowOffset: rowOffset, resultString: resultString };\n };\n EAN8Reader.prototype.getBarcodeFormat = function () {\n return BarcodeFormat.EAN_8;\n };\n return EAN8Reader;\n}(UPCEANReader));\nexport default EAN8Reader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.oned {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport DecodeHintType from '../DecodeHintType';\nimport FormatException from '../FormatException';\nimport NotFoundException from '../NotFoundException';\nimport Result from '../Result';\nimport ResultPoint from '../ResultPoint';\nimport StringBuilder from '../util/StringBuilder';\nimport System from '../util/System';\nimport OneDReader from './OneDReader';\n/**\n *Decodes ITF barcodes.
\n *\n * @author Tjieco\n */\nvar ITFReader = /** @class */ (function (_super) {\n __extends(ITFReader, _super);\n function ITFReader() {\n // private static W = 3; // Pixel width of a 3x wide line\n // private static w = 2; // Pixel width of a 2x wide line\n // private static N = 1; // Pixed width of a narrow line\n var _this = _super !== null && _super.apply(this, arguments) || this;\n // Stores the actual narrow line width of the image being decoded.\n _this.narrowLineWidth = -1;\n return _this;\n }\n // See ITFWriter.PATTERNS\n /*\n \n /!**\n * Patterns of Wide / Narrow lines to indicate each digit\n *!/\n */\n ITFReader.prototype.decodeRow = function (rowNumber, row, hints) {\n var e_1, _a;\n // Find out where the Middle section (payload) starts & ends\n var startRange = this.decodeStart(row);\n var endRange = this.decodeEnd(row);\n var result = new StringBuilder();\n ITFReader.decodeMiddle(row, startRange[1], endRange[0], result);\n var resultString = result.toString();\n var allowedLengths = null;\n if (hints != null) {\n allowedLengths = hints.get(DecodeHintType.ALLOWED_LENGTHS);\n }\n if (allowedLengths == null) {\n allowedLengths = ITFReader.DEFAULT_ALLOWED_LENGTHS;\n }\n // To avoid false positives with 2D barcodes (and other patterns), make\n // an assumption that the decoded string must be a 'standard' length if it's short\n var length = resultString.length;\n var lengthOK = false;\n var maxAllowedLength = 0;\n try {\n for (var allowedLengths_1 = __values(allowedLengths), allowedLengths_1_1 = allowedLengths_1.next(); !allowedLengths_1_1.done; allowedLengths_1_1 = allowedLengths_1.next()) {\n var value = allowedLengths_1_1.value;\n if (length === value) {\n lengthOK = true;\n break;\n }\n if (value > maxAllowedLength) {\n maxAllowedLength = value;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (allowedLengths_1_1 && !allowedLengths_1_1.done && (_a = allowedLengths_1.return)) _a.call(allowedLengths_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n if (!lengthOK && length > maxAllowedLength) {\n lengthOK = true;\n }\n if (!lengthOK) {\n throw new FormatException();\n }\n var points = [new ResultPoint(startRange[1], rowNumber), new ResultPoint(endRange[0], rowNumber)];\n var resultReturn = new Result(resultString, null, // no natural byte representation for these barcodes\n 0, points, BarcodeFormat.ITF, new Date().getTime());\n return resultReturn;\n };\n /*\n /!**\n * @param row row of black/white values to search\n * @param payloadStart offset of start pattern\n * @param resultString {@link StringBuilder} to append decoded chars to\n * @throws NotFoundException if decoding could not complete successfully\n *!/*/\n ITFReader.decodeMiddle = function (row, payloadStart, payloadEnd, resultString) {\n // Digits are interleaved in pairs - 5 black lines for one digit, and the\n // 5\n // interleaved white lines for the second digit.\n // Therefore, need to scan 10 lines and then\n // split these into two arrays\n var counterDigitPair = new Int32Array(10); // 10\n var counterBlack = new Int32Array(5); // 5\n var counterWhite = new Int32Array(5); // 5\n counterDigitPair.fill(0);\n counterBlack.fill(0);\n counterWhite.fill(0);\n while (payloadStart < payloadEnd) {\n // Get 10 runs of black/white.\n OneDReader.recordPattern(row, payloadStart, counterDigitPair);\n // Split them into each array\n for (var k = 0; k < 5; k++) {\n var twoK = 2 * k;\n counterBlack[k] = counterDigitPair[twoK];\n counterWhite[k] = counterDigitPair[twoK + 1];\n }\n var bestMatch = ITFReader.decodeDigit(counterBlack);\n resultString.append(bestMatch.toString());\n bestMatch = this.decodeDigit(counterWhite);\n resultString.append(bestMatch.toString());\n counterDigitPair.forEach(function (counterDigit) {\n payloadStart += counterDigit;\n });\n }\n };\n /*/!**\n * Identify where the start of the middle / payload section starts.\n *\n * @param row row of black/white values to search\n * @return Array, containing index of start of 'start block' and end of\n * 'start block'\n *!/*/\n ITFReader.prototype.decodeStart = function (row) {\n var endStart = ITFReader.skipWhiteSpace(row);\n var startPattern = ITFReader.findGuardPattern(row, endStart, ITFReader.START_PATTERN);\n // Determine the width of a narrow line in pixels. We can do this by\n // getting the width of the start pattern and dividing by 4 because its\n // made up of 4 narrow lines.\n this.narrowLineWidth = (startPattern[1] - startPattern[0]) / 4;\n this.validateQuietZone(row, startPattern[0]);\n return startPattern;\n };\n /*/!**\n * The start & end patterns must be pre/post fixed by a quiet zone. This\n * zone must be at least 10 times the width of a narrow line. Scan back until\n * we either get to the start of the barcode or match the necessary number of\n * quiet zone pixels.\n *\n * Note: Its assumed the row is reversed when using this method to find\n * quiet zone after the end pattern.\n *\n * ref: http://www.barcode-1.net/i25code.html\n *\n * @param row bit array representing the scanned barcode.\n * @param startPattern index into row of the start or end pattern.\n * @throws NotFoundException if the quiet zone cannot be found\n *!/*/\n ITFReader.prototype.validateQuietZone = function (row, startPattern) {\n var quietCount = this.narrowLineWidth * 10; // expect to find this many pixels of quiet zone\n // if there are not so many pixel at all let's try as many as possible\n quietCount = quietCount < startPattern ? quietCount : startPattern;\n for (var i = startPattern - 1; quietCount > 0 && i >= 0; i--) {\n if (row.get(i)) {\n break;\n }\n quietCount--;\n }\n if (quietCount !== 0) {\n // Unable to find the necessary number of quiet zone pixels.\n throw new NotFoundException();\n }\n };\n /*\n /!**\n * Skip all whitespace until we get to the first black line.\n *\n * @param row row of black/white values to search\n * @return index of the first black line.\n * @throws NotFoundException Throws exception if no black lines are found in the row\n *!/*/\n ITFReader.skipWhiteSpace = function (row) {\n var width = row.getSize();\n var endStart = row.getNextSet(0);\n if (endStart === width) {\n throw new NotFoundException();\n }\n return endStart;\n };\n /*/!**\n * Identify where the end of the middle / payload section ends.\n *\n * @param row row of black/white values to search\n * @return Array, containing index of start of 'end block' and end of 'end\n * block'\n *!/*/\n ITFReader.prototype.decodeEnd = function (row) {\n // For convenience, reverse the row and then\n // search from 'the start' for the end block\n row.reverse();\n try {\n var endStart = ITFReader.skipWhiteSpace(row);\n var endPattern = void 0;\n try {\n endPattern = ITFReader.findGuardPattern(row, endStart, ITFReader.END_PATTERN_REVERSED[0]);\n }\n catch (error) {\n if (error instanceof NotFoundException) {\n endPattern = ITFReader.findGuardPattern(row, endStart, ITFReader.END_PATTERN_REVERSED[1]);\n }\n }\n // The start & end patterns must be pre/post fixed by a quiet zone. This\n // zone must be at least 10 times the width of a narrow line.\n // ref: http://www.barcode-1.net/i25code.html\n this.validateQuietZone(row, endPattern[0]);\n // Now recalculate the indices of where the 'endblock' starts & stops to\n // accommodate\n // the reversed nature of the search\n var temp = endPattern[0];\n endPattern[0] = row.getSize() - endPattern[1];\n endPattern[1] = row.getSize() - temp;\n return endPattern;\n }\n finally {\n // Put the row back the right way.\n row.reverse();\n }\n };\n /*\n /!**\n * @param row row of black/white values to search\n * @param rowOffset position to start search\n * @param pattern pattern of counts of number of black and white pixels that are\n * being searched for as a pattern\n * @return start/end horizontal offset of guard pattern, as an array of two\n * ints\n * @throws NotFoundException if pattern is not found\n *!/*/\n ITFReader.findGuardPattern = function (row, rowOffset, pattern) {\n var patternLength = pattern.length;\n var counters = new Int32Array(patternLength);\n var width = row.getSize();\n var isWhite = false;\n var counterPosition = 0;\n var patternStart = rowOffset;\n counters.fill(0);\n for (var x = rowOffset; x < width; x++) {\n if (row.get(x) !== isWhite) {\n counters[counterPosition]++;\n }\n else {\n if (counterPosition === patternLength - 1) {\n if (OneDReader.patternMatchVariance(counters, pattern, ITFReader.MAX_INDIVIDUAL_VARIANCE) < ITFReader.MAX_AVG_VARIANCE) {\n return [patternStart, x];\n }\n patternStart += counters[0] + counters[1];\n System.arraycopy(counters, 2, counters, 0, counterPosition - 1);\n counters[counterPosition - 1] = 0;\n counters[counterPosition] = 0;\n counterPosition--;\n }\n else {\n counterPosition++;\n }\n counters[counterPosition] = 1;\n isWhite = !isWhite;\n }\n }\n throw new NotFoundException();\n };\n /*/!**\n * Attempts to decode a sequence of ITF black/white lines into single\n * digit.\n *\n * @param counters the counts of runs of observed black/white/black/... values\n * @return The decoded digit\n * @throws NotFoundException if digit cannot be decoded\n *!/*/\n ITFReader.decodeDigit = function (counters) {\n var bestVariance = ITFReader.MAX_AVG_VARIANCE; // worst variance we'll accept\n var bestMatch = -1;\n var max = ITFReader.PATTERNS.length;\n for (var i = 0; i < max; i++) {\n var pattern = ITFReader.PATTERNS[i];\n var variance = OneDReader.patternMatchVariance(counters, pattern, ITFReader.MAX_INDIVIDUAL_VARIANCE);\n if (variance < bestVariance) {\n bestVariance = variance;\n bestMatch = i;\n }\n else if (variance === bestVariance) {\n // if we find a second 'best match' with the same variance, we can not reliably report to have a suitable match\n bestMatch = -1;\n }\n }\n if (bestMatch >= 0) {\n return bestMatch % 10;\n }\n else {\n throw new NotFoundException();\n }\n };\n ITFReader.PATTERNS = [\n Int32Array.from([1, 1, 2, 2, 1]),\n Int32Array.from([2, 1, 1, 1, 2]),\n Int32Array.from([1, 2, 1, 1, 2]),\n Int32Array.from([2, 2, 1, 1, 1]),\n Int32Array.from([1, 1, 2, 1, 2]),\n Int32Array.from([2, 1, 2, 1, 1]),\n Int32Array.from([1, 2, 2, 1, 1]),\n Int32Array.from([1, 1, 1, 2, 2]),\n Int32Array.from([2, 1, 1, 2, 1]),\n Int32Array.from([1, 2, 1, 2, 1]),\n Int32Array.from([1, 1, 3, 3, 1]),\n Int32Array.from([3, 1, 1, 1, 3]),\n Int32Array.from([1, 3, 1, 1, 3]),\n Int32Array.from([3, 3, 1, 1, 1]),\n Int32Array.from([1, 1, 3, 1, 3]),\n Int32Array.from([3, 1, 3, 1, 1]),\n Int32Array.from([1, 3, 3, 1, 1]),\n Int32Array.from([1, 1, 1, 3, 3]),\n Int32Array.from([3, 1, 1, 3, 1]),\n Int32Array.from([1, 3, 1, 3, 1]) // 9\n ];\n ITFReader.MAX_AVG_VARIANCE = 0.38;\n ITFReader.MAX_INDIVIDUAL_VARIANCE = 0.5;\n /* /!** Valid ITF lengths. Anything longer than the largest value is also allowed. *!/*/\n ITFReader.DEFAULT_ALLOWED_LENGTHS = [6, 8, 10, 12, 14];\n /*/!**\n * Start/end guard pattern.\n *\n * Note: The end pattern is reversed because the row is reversed before\n * searching for the END_PATTERN\n *!/*/\n ITFReader.START_PATTERN = Int32Array.from([1, 1, 1, 1]);\n ITFReader.END_PATTERN_REVERSED = [\n Int32Array.from([1, 1, 2]),\n Int32Array.from([1, 1, 3]) // 3x\n ];\n return ITFReader;\n}(OneDReader));\nexport default ITFReader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/*namespace com.google.zxing.oned {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport DecodeHintType from '../DecodeHintType';\nimport NotFoundException from '../NotFoundException';\nimport Code128Reader from './Code128Reader';\nimport Code39Reader from './Code39Reader';\nimport Code93Reader from './Code93Reader';\nimport ITFReader from './ITFReader';\nimport MultiFormatUPCEANReader from './MultiFormatUPCEANReader';\nimport OneDReader from './OneDReader';\nimport CodaBarReader from './CodaBarReader';\nimport RSSExpandedReader from './rss/expanded/RSSExpandedReader';\nimport RSS14Reader from './rss/RSS14Reader';\n/**\n * @author Daniel SwitkinA reader that can read all available UPC/EAN formats. If a caller wants to try to\n * read all such formats, it is most efficient to use this implementation rather than invoke\n * individual readers.
\n *\n * @author Sean Owen\n */\nvar MultiFormatUPCEANReader = /** @class */ (function (_super) {\n __extends(MultiFormatUPCEANReader, _super);\n function MultiFormatUPCEANReader(hints) {\n var _this = _super.call(this) || this;\n var possibleFormats = hints == null ? null : hints.get(DecodeHintType.POSSIBLE_FORMATS);\n var readers = [];\n if (possibleFormats != null) {\n if (possibleFormats.indexOf(BarcodeFormat.EAN_13) > -1) {\n readers.push(new EAN13Reader());\n }\n if (possibleFormats.indexOf(BarcodeFormat.UPC_A) > -1) {\n readers.push(new UPCAReader());\n }\n if (possibleFormats.indexOf(BarcodeFormat.EAN_8) > -1) {\n readers.push(new EAN8Reader());\n }\n if (possibleFormats.indexOf(BarcodeFormat.UPC_E) > -1) {\n readers.push(new UPCEReader());\n }\n }\n if (readers.length === 0) {\n readers.push(new EAN13Reader());\n readers.push(new UPCAReader());\n readers.push(new EAN8Reader());\n readers.push(new UPCEReader());\n }\n _this.readers = readers;\n return _this;\n }\n MultiFormatUPCEANReader.prototype.decodeRow = function (rowNumber, row, hints) {\n var e_1, _a;\n try {\n for (var _b = __values(this.readers), _c = _b.next(); !_c.done; _c = _b.next()) {\n var reader = _c.value;\n try {\n // const result: Result = reader.decodeRow(rowNumber, row, startGuardPattern, hints);\n var result = reader.decodeRow(rowNumber, row, hints);\n // Special case: a 12-digit code encoded in UPC-A is identical to a \"0\"\n // followed by those 12 digits encoded as EAN-13. Each will recognize such a code,\n // UPC-A as a 12-digit string and EAN-13 as a 13-digit string starting with \"0\".\n // Individually these are correct and their readers will both read such a code\n // and correctly call it EAN-13, or UPC-A, respectively.\n //\n // In this case, if we've been looking for both types, we'd like to call it\n // a UPC-A code. But for efficiency we only run the EAN-13 decoder to also read\n // UPC-A. So we special case it here, and convert an EAN-13 result to a UPC-A\n // result if appropriate.\n //\n // But, don't return UPC-A if UPC-A was not a requested format!\n var ean13MayBeUPCA = result.getBarcodeFormat() === BarcodeFormat.EAN_13 &&\n result.getText().charAt(0) === '0';\n // @SuppressWarnings(\"unchecked\")\n var possibleFormats = hints == null ? null : hints.get(DecodeHintType.POSSIBLE_FORMATS);\n var canReturnUPCA = possibleFormats == null || possibleFormats.includes(BarcodeFormat.UPC_A);\n if (ean13MayBeUPCA && canReturnUPCA) {\n var rawBytes = result.getRawBytes();\n // Transfer the metadata across\n var resultUPCA = new Result(result.getText().substring(1), rawBytes, (rawBytes ? rawBytes.length : null), result.getResultPoints(), BarcodeFormat.UPC_A);\n resultUPCA.putAllMetadata(result.getResultMetadata());\n return resultUPCA;\n }\n return result;\n }\n catch (err) {\n // continue;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n throw new NotFoundException();\n };\n MultiFormatUPCEANReader.prototype.reset = function () {\n var e_2, _a;\n try {\n for (var _b = __values(this.readers), _c = _b.next(); !_c.done; _c = _b.next()) {\n var reader = _c.value;\n reader.reset();\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_2) throw e_2.error; }\n }\n };\n return MultiFormatUPCEANReader;\n}(OneDReader));\nexport default MultiFormatUPCEANReader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nimport BitArray from '../common/BitArray';\nimport DecodeHintType from '../DecodeHintType';\nimport ResultMetadataType from '../ResultMetadataType';\nimport ResultPoint from '../ResultPoint';\nimport NotFoundException from '../NotFoundException';\n/**\n * Encapsulates functionality and implementation that is common to all families\n * of one-dimensional barcodes.\n *\n * @author dswitkin@google.com (Daniel Switkin)\n * @author Sean Owen\n */\nvar OneDReader = /** @class */ (function () {\n function OneDReader() {\n }\n /*\n @Override\n public Result decode(BinaryBitmap image) throws NotFoundException, FormatException {\n return decode(image, null);\n }\n */\n // Note that we don't try rotation without the try harder flag, even if rotation was supported.\n // @Override\n OneDReader.prototype.decode = function (image, hints) {\n try {\n return this.doDecode(image, hints);\n }\n catch (nfe) {\n var tryHarder = hints && (hints.get(DecodeHintType.TRY_HARDER) === true);\n if (tryHarder && image.isRotateSupported()) {\n var rotatedImage = image.rotateCounterClockwise();\n var result = this.doDecode(rotatedImage, hints);\n // Record that we found it rotated 90 degrees CCW / 270 degrees CW\n var metadata = result.getResultMetadata();\n var orientation_1 = 270;\n if (metadata !== null && (metadata.get(ResultMetadataType.ORIENTATION) === true)) {\n // But if we found it reversed in doDecode(), add in that result here:\n orientation_1 = (orientation_1 + metadata.get(ResultMetadataType.ORIENTATION) % 360);\n }\n result.putMetadata(ResultMetadataType.ORIENTATION, orientation_1);\n // Update result points\n var points = result.getResultPoints();\n if (points !== null) {\n var height = rotatedImage.getHeight();\n for (var i = 0; i < points.length; i++) {\n points[i] = new ResultPoint(height - points[i].getY() - 1, points[i].getX());\n }\n }\n return result;\n }\n else {\n throw new NotFoundException();\n }\n }\n };\n // @Override\n OneDReader.prototype.reset = function () {\n // do nothing\n };\n /**\n * We're going to examine rows from the middle outward, searching alternately above and below the\n * middle, and farther out each time. rowStep is the number of rows between each successive\n * attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then\n * middle + rowStep, then middle - (2 * rowStep), etc.\n * rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily\n * decided that moving up and down by about 1/16 of the image is pretty good; we try more of the\n * image if \"trying harder\".\n *\n * @param image The image to decode\n * @param hints Any hints that were requested\n * @return The contents of the decoded barcode\n * @throws NotFoundException Any spontaneous errors which occur\n */\n OneDReader.prototype.doDecode = function (image, hints) {\n var width = image.getWidth();\n var height = image.getHeight();\n var row = new BitArray(width);\n var tryHarder = hints && (hints.get(DecodeHintType.TRY_HARDER) === true);\n var rowStep = Math.max(1, height >> (tryHarder ? 8 : 5));\n var maxLines;\n if (tryHarder) {\n maxLines = height; // Look at the whole image, not just the center\n }\n else {\n maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image\n }\n var middle = Math.trunc(height / 2);\n for (var x = 0; x < maxLines; x++) {\n // Scanning from the middle out. Determine which row we're looking at next:\n var rowStepsAboveOrBelow = Math.trunc((x + 1) / 2);\n var isAbove = (x & 0x01) === 0; // i.e. is x even?\n var rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);\n if (rowNumber < 0 || rowNumber >= height) {\n // Oops, if we run off the top or bottom, stop\n break;\n }\n // Estimate black point for this row and load it:\n try {\n row = image.getBlackRow(rowNumber, row);\n }\n catch (ignored) {\n continue;\n }\n var _loop_1 = function (attempt) {\n if (attempt === 1) { // trying again?\n row.reverse(); // reverse the row and continue\n // This means we will only ever draw result points *once* in the life of this method\n // since we want to avoid drawing the wrong points after flipping the row, and,\n // don't want to clutter with noise from every single row scan -- just the scans\n // that start on the center line.\n if (hints && (hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK) === true)) {\n var newHints_1 = new Map();\n hints.forEach(function (hint, key) { return newHints_1.set(key, hint); });\n newHints_1.delete(DecodeHintType.NEED_RESULT_POINT_CALLBACK);\n hints = newHints_1;\n }\n }\n try {\n // Look for a barcode\n var result = this_1.decodeRow(rowNumber, row, hints);\n // We found our barcode\n if (attempt === 1) {\n // But it was upside down, so note that\n result.putMetadata(ResultMetadataType.ORIENTATION, 180);\n // And remember to flip the result points horizontally.\n var points = result.getResultPoints();\n if (points !== null) {\n points[0] = new ResultPoint(width - points[0].getX() - 1, points[0].getY());\n points[1] = new ResultPoint(width - points[1].getX() - 1, points[1].getY());\n }\n }\n return { value: result };\n }\n catch (re) {\n // continue -- just couldn't decode this row\n }\n };\n var this_1 = this;\n // While we have the image data in a BitArray, it's fairly cheap to reverse it in place to\n // handle decoding upside down barcodes.\n for (var attempt = 0; attempt < 2; attempt++) {\n var state_1 = _loop_1(attempt);\n if (typeof state_1 === \"object\")\n return state_1.value;\n }\n }\n throw new NotFoundException();\n };\n /**\n * Records the size of successive runs of white and black pixels in a row, starting at a given point.\n * The values are recorded in the given array, and the number of runs recorded is equal to the size\n * of the array. If the row starts on a white pixel at the given start point, then the first count\n * recorded is the run of white pixels starting from that point; likewise it is the count of a run\n * of black pixels if the row begin on a black pixels at that point.\n *\n * @param row row to count from\n * @param start offset into row to start at\n * @param counters array into which to record counts\n * @throws NotFoundException if counters cannot be filled entirely from row before running out\n * of pixels\n */\n OneDReader.recordPattern = function (row, start, counters) {\n var numCounters = counters.length;\n for (var index = 0; index < numCounters; index++)\n counters[index] = 0;\n var end = row.getSize();\n if (start >= end) {\n throw new NotFoundException();\n }\n var isWhite = !row.get(start);\n var counterPosition = 0;\n var i = start;\n while (i < end) {\n if (row.get(i) !== isWhite) {\n counters[counterPosition]++;\n }\n else {\n if (++counterPosition === numCounters) {\n break;\n }\n else {\n counters[counterPosition] = 1;\n isWhite = !isWhite;\n }\n }\n i++;\n }\n // If we read fully the last section of pixels and filled up our counters -- or filled\n // the last counter but ran off the side of the image, OK. Otherwise, a problem.\n if (!(counterPosition === numCounters || (counterPosition === numCounters - 1 && i === end))) {\n throw new NotFoundException();\n }\n };\n OneDReader.recordPatternInReverse = function (row, start, counters) {\n // This could be more efficient I guess\n var numTransitionsLeft = counters.length;\n var last = row.get(start);\n while (start > 0 && numTransitionsLeft >= 0) {\n if (row.get(--start) !== last) {\n numTransitionsLeft--;\n last = !last;\n }\n }\n if (numTransitionsLeft >= 0) {\n throw new NotFoundException();\n }\n OneDReader.recordPattern(row, start + 1, counters);\n };\n /**\n * Determines how closely a set of observed counts of runs of black/white values matches a given\n * target pattern. This is reported as the ratio of the total variance from the expected pattern\n * proportions across all pattern elements, to the length of the pattern.\n *\n * @param counters observed counters\n * @param pattern expected pattern\n * @param maxIndividualVariance The most any counter can differ before we give up\n * @return ratio of total variance between counters and pattern compared to total pattern size\n */\n OneDReader.patternMatchVariance = function (counters, pattern, maxIndividualVariance) {\n var numCounters = counters.length;\n var total = 0;\n var patternLength = 0;\n for (var i = 0; i < numCounters; i++) {\n total += counters[i];\n patternLength += pattern[i];\n }\n if (total < patternLength) {\n // If we don't even have one pixel per unit of bar width, assume this is too small\n // to reliably match, so fail:\n return Number.POSITIVE_INFINITY;\n }\n var unitBarWidth = total / patternLength;\n maxIndividualVariance *= unitBarWidth;\n var totalVariance = 0.0;\n for (var x = 0; x < numCounters; x++) {\n var counter = counters[x];\n var scaledPattern = pattern[x] * unitBarWidth;\n var variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;\n if (variance > maxIndividualVariance) {\n return Number.POSITIVE_INFINITY;\n }\n totalVariance += variance;\n }\n return totalVariance / total;\n };\n return OneDReader;\n}());\nexport default OneDReader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/*namespace com.google.zxing.oned {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport Result from '../Result';\nimport NotFoundException from '../NotFoundException';\nimport EAN13Reader from './EAN13Reader';\nimport UPCEANReader from './UPCEANReader';\n/**\n * Encapsulates functionality and implementation that is common to all families\n * of one-dimensional barcodes.\n *\n * @author dswitkin@google.com (Daniel Switkin)\n * @author Sean Owen\n * @author sam2332 (Sam Rudloff)\n *\n * @source https://github.com/zxing/zxing/blob/3c96923276dd5785d58eb970b6ba3f80d36a9505/core/src/main/java/com/google/zxing/oned/UPCAReader.java\n *\n * @experimental\n */\nvar UPCAReader = /** @class */ (function (_super) {\n __extends(UPCAReader, _super);\n function UPCAReader() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.ean13Reader = new EAN13Reader();\n return _this;\n }\n // @Override\n UPCAReader.prototype.getBarcodeFormat = function () {\n return BarcodeFormat.UPC_A;\n };\n // Note that we don't try rotation without the try harder flag, even if rotation was supported.\n // @Override\n UPCAReader.prototype.decode = function (image, hints) {\n return this.maybeReturnResult(this.ean13Reader.decode(image));\n };\n // @Override\n UPCAReader.prototype.decodeRow = function (rowNumber, row, hints) {\n return this.maybeReturnResult(this.ean13Reader.decodeRow(rowNumber, row, hints));\n };\n // @Override\n UPCAReader.prototype.decodeMiddle = function (row, startRange, resultString) {\n return this.ean13Reader.decodeMiddle(row, startRange, resultString);\n };\n UPCAReader.prototype.maybeReturnResult = function (result) {\n var text = result.getText();\n if (text.charAt(0) === '0') {\n var upcaResult = new Result(text.substring(1), null, null, result.getResultPoints(), BarcodeFormat.UPC_A);\n if (result.getResultMetadata() != null) {\n upcaResult.putAllMetadata(result.getResultMetadata());\n }\n return upcaResult;\n }\n else {\n throw new NotFoundException();\n }\n };\n UPCAReader.prototype.reset = function () {\n this.ean13Reader.reset();\n };\n return UPCAReader;\n}(UPCEANReader));\nexport default UPCAReader;\n","/*\n * Copyright (C) 2012 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport BarcodeFormat from '../BarcodeFormat';\nimport AbstractUPCEANReader from './AbstractUPCEANReader';\nimport Result from '../Result';\nimport ResultPoint from '../ResultPoint';\nimport ResultMetadataType from '../ResultMetadataType';\nimport NotFoundException from '../NotFoundException';\n/**\n * @see UPCEANExtension5Support\n */\nvar UPCEANExtension2Support = /** @class */ (function () {\n function UPCEANExtension2Support() {\n this.decodeMiddleCounters = Int32Array.from([0, 0, 0, 0]);\n this.decodeRowStringBuffer = '';\n }\n UPCEANExtension2Support.prototype.decodeRow = function (rowNumber, row, extensionStartRange) {\n var result = this.decodeRowStringBuffer;\n var end = this.decodeMiddle(row, extensionStartRange, result);\n var resultString = result.toString();\n var extensionData = UPCEANExtension2Support.parseExtensionString(resultString);\n var resultPoints = [\n new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0, rowNumber),\n new ResultPoint(end, rowNumber)\n ];\n var extensionResult = new Result(resultString, null, 0, resultPoints, BarcodeFormat.UPC_EAN_EXTENSION, new Date().getTime());\n if (extensionData != null) {\n extensionResult.putAllMetadata(extensionData);\n }\n return extensionResult;\n };\n UPCEANExtension2Support.prototype.decodeMiddle = function (row, startRange, resultString) {\n var e_1, _a;\n var counters = this.decodeMiddleCounters;\n counters[0] = 0;\n counters[1] = 0;\n counters[2] = 0;\n counters[3] = 0;\n var end = row.getSize();\n var rowOffset = startRange[1];\n var checkParity = 0;\n for (var x = 0; x < 2 && rowOffset < end; x++) {\n var bestMatch = AbstractUPCEANReader.decodeDigit(row, counters, rowOffset, AbstractUPCEANReader.L_AND_G_PATTERNS);\n resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch % 10));\n try {\n for (var counters_1 = (e_1 = void 0, __values(counters)), counters_1_1 = counters_1.next(); !counters_1_1.done; counters_1_1 = counters_1.next()) {\n var counter = counters_1_1.value;\n rowOffset += counter;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (counters_1_1 && !counters_1_1.done && (_a = counters_1.return)) _a.call(counters_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n if (bestMatch >= 10) {\n checkParity |= 1 << (1 - x);\n }\n if (x !== 1) {\n // Read off separator if not last\n rowOffset = row.getNextSet(rowOffset);\n rowOffset = row.getNextUnset(rowOffset);\n }\n }\n if (resultString.length !== 2) {\n throw new NotFoundException();\n }\n if (parseInt(resultString.toString()) % 4 !== checkParity) {\n throw new NotFoundException();\n }\n return rowOffset;\n };\n UPCEANExtension2Support.parseExtensionString = function (raw) {\n if (raw.length !== 2) {\n return null;\n }\n return new Map([[ResultMetadataType.ISSUE_NUMBER, parseInt(raw)]]);\n };\n return UPCEANExtension2Support;\n}());\nexport default UPCEANExtension2Support;\n","/*\n * Copyright (C) 2010 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport BarcodeFormat from '../BarcodeFormat';\n// import UPCEANReader from './UPCEANReader';\nimport AbstractUPCEANReader from './AbstractUPCEANReader';\nimport Result from '../Result';\nimport ResultPoint from '../ResultPoint';\nimport ResultMetadataType from '../ResultMetadataType';\nimport NotFoundException from '../NotFoundException';\n/**\n * @see UPCEANExtension2Support\n */\nvar UPCEANExtension5Support = /** @class */ (function () {\n function UPCEANExtension5Support() {\n this.CHECK_DIGIT_ENCODINGS = [0x18, 0x14, 0x12, 0x11, 0x0C, 0x06, 0x03, 0x0A, 0x09, 0x05];\n this.decodeMiddleCounters = Int32Array.from([0, 0, 0, 0]);\n this.decodeRowStringBuffer = '';\n }\n UPCEANExtension5Support.prototype.decodeRow = function (rowNumber, row, extensionStartRange) {\n var result = this.decodeRowStringBuffer;\n var end = this.decodeMiddle(row, extensionStartRange, result);\n var resultString = result.toString();\n var extensionData = UPCEANExtension5Support.parseExtensionString(resultString);\n var resultPoints = [\n new ResultPoint((extensionStartRange[0] + extensionStartRange[1]) / 2.0, rowNumber),\n new ResultPoint(end, rowNumber)\n ];\n var extensionResult = new Result(resultString, null, 0, resultPoints, BarcodeFormat.UPC_EAN_EXTENSION, new Date().getTime());\n if (extensionData != null) {\n extensionResult.putAllMetadata(extensionData);\n }\n return extensionResult;\n };\n UPCEANExtension5Support.prototype.decodeMiddle = function (row, startRange, resultString) {\n var e_1, _a;\n var counters = this.decodeMiddleCounters;\n counters[0] = 0;\n counters[1] = 0;\n counters[2] = 0;\n counters[3] = 0;\n var end = row.getSize();\n var rowOffset = startRange[1];\n var lgPatternFound = 0;\n for (var x = 0; x < 5 && rowOffset < end; x++) {\n var bestMatch = AbstractUPCEANReader.decodeDigit(row, counters, rowOffset, AbstractUPCEANReader.L_AND_G_PATTERNS);\n resultString += String.fromCharCode(('0'.charCodeAt(0) + bestMatch % 10));\n try {\n for (var counters_1 = (e_1 = void 0, __values(counters)), counters_1_1 = counters_1.next(); !counters_1_1.done; counters_1_1 = counters_1.next()) {\n var counter = counters_1_1.value;\n rowOffset += counter;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (counters_1_1 && !counters_1_1.done && (_a = counters_1.return)) _a.call(counters_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n if (bestMatch >= 10) {\n lgPatternFound |= 1 << (4 - x);\n }\n if (x !== 4) {\n // Read off separator if not last\n rowOffset = row.getNextSet(rowOffset);\n rowOffset = row.getNextUnset(rowOffset);\n }\n }\n if (resultString.length !== 5) {\n throw new NotFoundException();\n }\n var checkDigit = this.determineCheckDigit(lgPatternFound);\n if (UPCEANExtension5Support.extensionChecksum(resultString.toString()) !== checkDigit) {\n throw new NotFoundException();\n }\n return rowOffset;\n };\n UPCEANExtension5Support.extensionChecksum = function (s) {\n var length = s.length;\n var sum = 0;\n for (var i = length - 2; i >= 0; i -= 2) {\n sum += s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);\n }\n sum *= 3;\n for (var i = length - 1; i >= 0; i -= 2) {\n sum += s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);\n }\n sum *= 3;\n return sum % 10;\n };\n UPCEANExtension5Support.prototype.determineCheckDigit = function (lgPatternFound) {\n for (var d = 0; d < 10; d++) {\n if (lgPatternFound === this.CHECK_DIGIT_ENCODINGS[d]) {\n return d;\n }\n }\n throw new NotFoundException();\n };\n UPCEANExtension5Support.parseExtensionString = function (raw) {\n if (raw.length !== 5) {\n return null;\n }\n var value = UPCEANExtension5Support.parseExtension5String(raw);\n if (value == null) {\n return null;\n }\n return new Map([[ResultMetadataType.SUGGESTED_PRICE, value]]);\n };\n UPCEANExtension5Support.parseExtension5String = function (raw) {\n var currency;\n switch (raw.charAt(0)) {\n case '0':\n currency = '£';\n break;\n case '5':\n currency = '$';\n break;\n case '9':\n // Reference: http://www.jollytech.com\n switch (raw) {\n case '90000':\n // No suggested retail price\n return null;\n case '99991':\n // Complementary\n return '0.00';\n case '99990':\n return 'Used';\n }\n // Otherwise... unknown currency?\n currency = '';\n break;\n default:\n currency = '';\n break;\n }\n var rawAmount = parseInt(raw.substring(1));\n var unitsString = (rawAmount / 100).toString();\n var hundredths = rawAmount % 100;\n var hundredthsString = hundredths < 10 ? '0' + hundredths : hundredths.toString(); // fixme\n return currency + unitsString + '.' + hundredthsString;\n };\n return UPCEANExtension5Support;\n}());\nexport default UPCEANExtension5Support;\n","/*\n * Copyright (C) 2010 ZXing authors\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 */\nimport AbstractUPCEANReader from './AbstractUPCEANReader';\nimport UPCEANExtension5Support from './UPCEANExtension5Support';\nimport UPCEANExtension2Support from './UPCEANExtension2Support';\nvar UPCEANExtensionSupport = /** @class */ (function () {\n function UPCEANExtensionSupport() {\n }\n UPCEANExtensionSupport.decodeRow = function (rowNumber, row, rowOffset) {\n var extensionStartRange = AbstractUPCEANReader.findGuardPattern(row, rowOffset, false, this.EXTENSION_START_PATTERN, new Int32Array(this.EXTENSION_START_PATTERN.length).fill(0));\n try {\n // return null;\n var fiveSupport = new UPCEANExtension5Support();\n return fiveSupport.decodeRow(rowNumber, row, extensionStartRange);\n }\n catch (err) {\n // return null;\n var twoSupport = new UPCEANExtension2Support();\n return twoSupport.decodeRow(rowNumber, row, extensionStartRange);\n }\n };\n UPCEANExtensionSupport.EXTENSION_START_PATTERN = Int32Array.from([1, 1, 2]);\n return UPCEANExtensionSupport;\n}());\nexport default UPCEANExtensionSupport;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport BarcodeFormat from '../BarcodeFormat';\nimport DecodeHintType from '../DecodeHintType';\nimport Result from '../Result';\nimport ResultMetadataType from '../ResultMetadataType';\nimport ResultPoint from '../ResultPoint';\nimport UPCEANExtensionSupport from './UPCEANExtensionSupport';\nimport AbstractUPCEANReader from './AbstractUPCEANReader';\nimport NotFoundException from '../NotFoundException';\nimport FormatException from '../FormatException';\nimport ChecksumException from '../ChecksumException';\n/**\n *Encapsulates functionality and implementation that is common to UPC and EAN families\n * of one-dimensional barcodes.
\n *\n * @author dswitkin@google.com (Daniel Switkin)\n * @author Sean Owen\n * @author alasdair@google.com (Alasdair Mackintosh)\n */\nvar UPCEANReader = /** @class */ (function (_super) {\n __extends(UPCEANReader, _super);\n function UPCEANReader() {\n var _this = _super.call(this) || this;\n _this.decodeRowStringBuffer = '';\n UPCEANReader.L_AND_G_PATTERNS = UPCEANReader.L_PATTERNS.map(function (arr) { return Int32Array.from(arr); });\n for (var i = 10; i < 20; i++) {\n var widths = UPCEANReader.L_PATTERNS[i - 10];\n var reversedWidths = new Int32Array(widths.length);\n for (var j = 0; j < widths.length; j++) {\n reversedWidths[j] = widths[widths.length - j - 1];\n }\n UPCEANReader.L_AND_G_PATTERNS[i] = reversedWidths;\n }\n return _this;\n }\n UPCEANReader.prototype.decodeRow = function (rowNumber, row, hints) {\n var startGuardRange = UPCEANReader.findStartGuardPattern(row);\n var resultPointCallback = hints == null ? null : hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);\n if (resultPointCallback != null) {\n var resultPoint_1 = new ResultPoint((startGuardRange[0] + startGuardRange[1]) / 2.0, rowNumber);\n resultPointCallback.foundPossibleResultPoint(resultPoint_1);\n }\n var budello = this.decodeMiddle(row, startGuardRange, this.decodeRowStringBuffer);\n var endStart = budello.rowOffset;\n var result = budello.resultString;\n if (resultPointCallback != null) {\n var resultPoint_2 = new ResultPoint(endStart, rowNumber);\n resultPointCallback.foundPossibleResultPoint(resultPoint_2);\n }\n var endRange = UPCEANReader.decodeEnd(row, endStart);\n if (resultPointCallback != null) {\n var resultPoint_3 = new ResultPoint((endRange[0] + endRange[1]) / 2.0, rowNumber);\n resultPointCallback.foundPossibleResultPoint(resultPoint_3);\n }\n // Make sure there is a quiet zone at least as big as the end pattern after the barcode. The\n // spec might want more whitespace, but in practice this is the maximum we can count on.\n var end = endRange[1];\n var quietEnd = end + (end - endRange[0]);\n if (quietEnd >= row.getSize() || !row.isRange(end, quietEnd, false)) {\n throw new NotFoundException();\n }\n var resultString = result.toString();\n // UPC/EAN should never be less than 8 chars anyway\n if (resultString.length < 8) {\n throw new FormatException();\n }\n if (!UPCEANReader.checkChecksum(resultString)) {\n throw new ChecksumException();\n }\n var left = (startGuardRange[1] + startGuardRange[0]) / 2.0;\n var right = (endRange[1] + endRange[0]) / 2.0;\n var format = this.getBarcodeFormat();\n var resultPoint = [new ResultPoint(left, rowNumber), new ResultPoint(right, rowNumber)];\n var decodeResult = new Result(resultString, null, 0, resultPoint, format, new Date().getTime());\n var extensionLength = 0;\n try {\n var extensionResult = UPCEANExtensionSupport.decodeRow(rowNumber, row, endRange[1]);\n decodeResult.putMetadata(ResultMetadataType.UPC_EAN_EXTENSION, extensionResult.getText());\n decodeResult.putAllMetadata(extensionResult.getResultMetadata());\n decodeResult.addResultPoints(extensionResult.getResultPoints());\n extensionLength = extensionResult.getText().length;\n }\n catch (err) {\n }\n var allowedExtensions = hints == null ? null : hints.get(DecodeHintType.ALLOWED_EAN_EXTENSIONS);\n if (allowedExtensions != null) {\n var valid = false;\n for (var length_1 in allowedExtensions) {\n if (extensionLength.toString() === length_1) { // check me\n valid = true;\n break;\n }\n }\n if (!valid) {\n throw new NotFoundException();\n }\n }\n if (format === BarcodeFormat.EAN_13 || format === BarcodeFormat.UPC_A) {\n // let countryID = eanManSupport.lookupContryIdentifier(resultString); todo\n // if (countryID != null) {\n // decodeResult.putMetadata(ResultMetadataType.POSSIBLE_COUNTRY, countryID);\n // }\n }\n return decodeResult;\n };\n UPCEANReader.checkChecksum = function (s) {\n return UPCEANReader.checkStandardUPCEANChecksum(s);\n };\n UPCEANReader.checkStandardUPCEANChecksum = function (s) {\n var length = s.length;\n if (length === 0)\n return false;\n var check = parseInt(s.charAt(length - 1), 10);\n return UPCEANReader.getStandardUPCEANChecksum(s.substring(0, length - 1)) === check;\n };\n UPCEANReader.getStandardUPCEANChecksum = function (s) {\n var length = s.length;\n var sum = 0;\n for (var i = length - 1; i >= 0; i -= 2) {\n var digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);\n if (digit < 0 || digit > 9) {\n throw new FormatException();\n }\n sum += digit;\n }\n sum *= 3;\n for (var i = length - 2; i >= 0; i -= 2) {\n var digit = s.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);\n if (digit < 0 || digit > 9) {\n throw new FormatException();\n }\n sum += digit;\n }\n return (1000 - sum) % 10;\n };\n UPCEANReader.decodeEnd = function (row, endStart) {\n return UPCEANReader.findGuardPattern(row, endStart, false, UPCEANReader.START_END_PATTERN, new Int32Array(UPCEANReader.START_END_PATTERN.length).fill(0));\n };\n return UPCEANReader;\n}(AbstractUPCEANReader));\nexport default UPCEANReader;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport UPCEANReader from './UPCEANReader';\nimport StringBuilder from '../util/StringBuilder';\nimport NotFoundException from '../NotFoundException';\nimport BarcodeFormat from '../BarcodeFormat';\n// package com.google.zxing.oned;\n// import com.google.zxing.BarcodeFormat;\n// import com.google.zxing.FormatException;\n// import com.google.zxing.NotFoundException;\n// import com.google.zxing.common.BitArray;\n/**\n *Implements decoding of the UPC-E format.
\n *This is a great reference for\n * UPC-E information.
\n *\n * @author Sean Owen\n *\n * @source https://github.com/zxing/zxing/blob/3c96923276dd5785d58eb970b6ba3f80d36a9505/core/src/main/java/com/google/zxing/oned/UPCEReader.java\n *\n * @experimental\n */\nvar UPCEReader = /** @class */ (function (_super) {\n __extends(UPCEReader, _super);\n function UPCEReader() {\n var _this = _super.call(this) || this;\n _this.decodeMiddleCounters = new Int32Array(4);\n return _this;\n }\n /**\n * @throws NotFoundException\n */\n // @Override\n UPCEReader.prototype.decodeMiddle = function (row, startRange, result) {\n var e_1, _a;\n var counters = this.decodeMiddleCounters.map(function (x) { return x; });\n counters[0] = 0;\n counters[1] = 0;\n counters[2] = 0;\n counters[3] = 0;\n var end = row.getSize();\n var rowOffset = startRange[1];\n var lgPatternFound = 0;\n for (var x = 0; x < 6 && rowOffset < end; x++) {\n var bestMatch = UPCEReader.decodeDigit(row, counters, rowOffset, UPCEReader.L_AND_G_PATTERNS);\n result += String.fromCharCode(('0'.charCodeAt(0) + bestMatch % 10));\n try {\n for (var counters_1 = (e_1 = void 0, __values(counters)), counters_1_1 = counters_1.next(); !counters_1_1.done; counters_1_1 = counters_1.next()) {\n var counter = counters_1_1.value;\n rowOffset += counter;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (counters_1_1 && !counters_1_1.done && (_a = counters_1.return)) _a.call(counters_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n if (bestMatch >= 10) {\n lgPatternFound |= 1 << (5 - x);\n }\n }\n UPCEReader.determineNumSysAndCheckDigit(new StringBuilder(result), lgPatternFound);\n return rowOffset;\n };\n /**\n * @throws NotFoundException\n */\n // @Override\n UPCEReader.prototype.decodeEnd = function (row, endStart) {\n return UPCEReader.findGuardPatternWithoutCounters(row, endStart, true, UPCEReader.MIDDLE_END_PATTERN);\n };\n /**\n * @throws FormatException\n */\n // @Override\n UPCEReader.prototype.checkChecksum = function (s) {\n return UPCEANReader.checkChecksum(UPCEReader.convertUPCEtoUPCA(s));\n };\n /**\n * @throws NotFoundException\n */\n UPCEReader.determineNumSysAndCheckDigit = function (resultString, lgPatternFound) {\n for (var numSys = 0; numSys <= 1; numSys++) {\n for (var d = 0; d < 10; d++) {\n if (lgPatternFound === this.NUMSYS_AND_CHECK_DIGIT_PATTERNS[numSys][d]) {\n resultString.insert(0, /*(char)*/ ('0' + numSys));\n resultString.append(/*(char)*/ ('0' + d));\n return;\n }\n }\n }\n throw NotFoundException.getNotFoundInstance();\n };\n // @Override\n UPCEReader.prototype.getBarcodeFormat = function () {\n return BarcodeFormat.UPC_E;\n };\n /**\n * Expands a UPC-E value back into its full, equivalent UPC-A code value.\n *\n * @param upce UPC-E code as string of digits\n * @return equivalent UPC-A code as string of digits\n */\n UPCEReader.convertUPCEtoUPCA = function (upce) {\n // the following line is equivalent to upce.getChars(1, 7, upceChars, 0);\n var upceChars = upce.slice(1, 7).split('').map(function (x) { return x.charCodeAt(0); });\n var result = new StringBuilder( /*12*/);\n result.append(upce.charAt(0));\n var lastChar = upceChars[5];\n switch (lastChar) {\n case 0:\n case 1:\n case 2:\n result.appendChars(upceChars, 0, 2);\n result.append(lastChar);\n result.append('0000');\n result.appendChars(upceChars, 2, 3);\n break;\n case 3:\n result.appendChars(upceChars, 0, 3);\n result.append('00000');\n result.appendChars(upceChars, 3, 2);\n break;\n case 4:\n result.appendChars(upceChars, 0, 4);\n result.append('00000');\n result.append(upceChars[4]);\n break;\n default:\n result.appendChars(upceChars, 0, 5);\n result.append('0000');\n result.append(lastChar);\n break;\n }\n // Only append check digit in conversion if supplied\n if (upce.length >= 8) {\n result.append(upce.charAt(7));\n }\n return result.toString();\n };\n /**\n * The pattern that marks the middle, and end, of a UPC-E pattern.\n * There is no \"second half\" to a UPC-E barcode.\n */\n UPCEReader.MIDDLE_END_PATTERN = Int32Array.from([1, 1, 1, 1, 1, 1]);\n // For an UPC-E barcode, the final digit is represented by the parities used\n // to encode the middle six digits, according to the table below.\n //\n // Parity of next 6 digits\n // Digit 0 1 2 3 4 5\n // 0 Even Even Even Odd Odd Odd\n // 1 Even Even Odd Even Odd Odd\n // 2 Even Even Odd Odd Even Odd\n // 3 Even Even Odd Odd Odd Even\n // 4 Even Odd Even Even Odd Odd\n // 5 Even Odd Odd Even Even Odd\n // 6 Even Odd Odd Odd Even Even\n // 7 Even Odd Even Odd Even Odd\n // 8 Even Odd Even Odd Odd Even\n // 9 Even Odd Odd Even Odd Even\n //\n // The encoding is represented by the following array, which is a bit pattern\n // using Odd = 0 and Even = 1. For example, 5 is represented by:\n //\n // Odd Even Even Odd Odd Even\n // in binary:\n // 0 1 1 0 0 1 == 0x19\n //\n /**\n * See {@link #L_AND_G_PATTERNS}; these values similarly represent patterns of\n * even-odd parity encodings of digits that imply both the number system (0 or 1)\n * used, and the check digit.\n */\n UPCEReader.NUMSYS_AND_CHECK_DIGIT_PATTERNS = [\n Int32Array.from([0x38, 0x34, 0x32, 0x31, 0x2C, 0x26, 0x23, 0x2A, 0x29, 0x25]),\n Int32Array.from([0x07, 0x0B, 0x0D, 0x0E, 0x13, 0x19, 0x1C, 0x15, 0x16, 0x1]),\n ];\n return UPCEReader;\n}(UPCEANReader));\nexport default UPCEReader;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport MathUtils from '../../common/detector/MathUtils';\nimport NotFoundException from '../../NotFoundException';\nimport OneDReader from '../OneDReader';\n// import Integer from '../../util/Integer';\n// import Float from '../../util/Float';\nvar AbstractRSSReader = /** @class */ (function (_super) {\n __extends(AbstractRSSReader, _super);\n function AbstractRSSReader() {\n var _this = _super.call(this) || this;\n _this.decodeFinderCounters = new Int32Array(4);\n _this.dataCharacterCounters = new Int32Array(8);\n _this.oddRoundingErrors = new Array(4);\n _this.evenRoundingErrors = new Array(4);\n _this.oddCounts = new Array(_this.dataCharacterCounters.length / 2);\n _this.evenCounts = new Array(_this.dataCharacterCounters.length / 2);\n return _this;\n }\n AbstractRSSReader.prototype.getDecodeFinderCounters = function () {\n return this.decodeFinderCounters;\n };\n AbstractRSSReader.prototype.getDataCharacterCounters = function () {\n return this.dataCharacterCounters;\n };\n AbstractRSSReader.prototype.getOddRoundingErrors = function () {\n return this.oddRoundingErrors;\n };\n AbstractRSSReader.prototype.getEvenRoundingErrors = function () {\n return this.evenRoundingErrors;\n };\n AbstractRSSReader.prototype.getOddCounts = function () {\n return this.oddCounts;\n };\n AbstractRSSReader.prototype.getEvenCounts = function () {\n return this.evenCounts;\n };\n AbstractRSSReader.prototype.parseFinderValue = function (counters, finderPatterns) {\n for (var value = 0; value < finderPatterns.length; value++) {\n if (OneDReader.patternMatchVariance(counters, finderPatterns[value], AbstractRSSReader.MAX_INDIVIDUAL_VARIANCE) < AbstractRSSReader.MAX_AVG_VARIANCE) {\n return value;\n }\n }\n throw new NotFoundException();\n };\n /**\n * @param array values to sum\n * @return sum of values\n * @deprecated call {@link MathUtils#sum(int[])}\n */\n AbstractRSSReader.count = function (array) {\n return MathUtils.sum(new Int32Array(array));\n };\n AbstractRSSReader.increment = function (array, errors) {\n var index = 0;\n var biggestError = errors[0];\n for (var i = 1; i < array.length; i++) {\n if (errors[i] > biggestError) {\n biggestError = errors[i];\n index = i;\n }\n }\n array[index]++;\n };\n AbstractRSSReader.decrement = function (array, errors) {\n var index = 0;\n var biggestError = errors[0];\n for (var i = 1; i < array.length; i++) {\n if (errors[i] < biggestError) {\n biggestError = errors[i];\n index = i;\n }\n }\n array[index]--;\n };\n AbstractRSSReader.isFinderPattern = function (counters) {\n var e_1, _a;\n var firstTwoSum = counters[0] + counters[1];\n var sum = firstTwoSum + counters[2] + counters[3];\n var ratio = firstTwoSum / sum;\n if (ratio >= AbstractRSSReader.MIN_FINDER_PATTERN_RATIO && ratio <= AbstractRSSReader.MAX_FINDER_PATTERN_RATIO) {\n // passes ratio test in spec, but see if the counts are unreasonable\n var minCounter = Number.MAX_SAFE_INTEGER;\n var maxCounter = Number.MIN_SAFE_INTEGER;\n try {\n for (var counters_1 = __values(counters), counters_1_1 = counters_1.next(); !counters_1_1.done; counters_1_1 = counters_1.next()) {\n var counter = counters_1_1.value;\n if (counter > maxCounter) {\n maxCounter = counter;\n }\n if (counter < minCounter) {\n minCounter = counter;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (counters_1_1 && !counters_1_1.done && (_a = counters_1.return)) _a.call(counters_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return maxCounter < 10 * minCounter;\n }\n return false;\n };\n AbstractRSSReader.MAX_AVG_VARIANCE = 0.2;\n AbstractRSSReader.MAX_INDIVIDUAL_VARIANCE = 0.45;\n AbstractRSSReader.MIN_FINDER_PATTERN_RATIO = 9.5 / 12.0;\n AbstractRSSReader.MAX_FINDER_PATTERN_RATIO = 12.5 / 14.0;\n return AbstractRSSReader;\n}(OneDReader));\nexport default AbstractRSSReader;\n","var DataCharacter = /** @class */ (function () {\n function DataCharacter(value, checksumPortion) {\n this.value = value;\n this.checksumPortion = checksumPortion;\n }\n DataCharacter.prototype.getValue = function () {\n return this.value;\n };\n DataCharacter.prototype.getChecksumPortion = function () {\n return this.checksumPortion;\n };\n DataCharacter.prototype.toString = function () {\n return this.value + '(' + this.checksumPortion + ')';\n };\n DataCharacter.prototype.equals = function (o) {\n if (!(o instanceof DataCharacter)) {\n return false;\n }\n var that = o;\n return this.value === that.value && this.checksumPortion === that.checksumPortion;\n };\n DataCharacter.prototype.hashCode = function () {\n return this.value ^ this.checksumPortion;\n };\n return DataCharacter;\n}());\nexport default DataCharacter;\n","import ResultPoint from '../../ResultPoint';\nvar FinderPattern = /** @class */ (function () {\n function FinderPattern(value, startEnd, start, end, rowNumber) {\n this.value = value;\n this.startEnd = startEnd;\n this.value = value;\n this.startEnd = startEnd;\n this.resultPoints = new Array();\n this.resultPoints.push(new ResultPoint(start, rowNumber));\n this.resultPoints.push(new ResultPoint(end, rowNumber));\n }\n FinderPattern.prototype.getValue = function () {\n return this.value;\n };\n FinderPattern.prototype.getStartEnd = function () {\n return this.startEnd;\n };\n FinderPattern.prototype.getResultPoints = function () {\n return this.resultPoints;\n };\n FinderPattern.prototype.equals = function (o) {\n if (!(o instanceof FinderPattern)) {\n return false;\n }\n var that = o;\n return this.value === that.value;\n };\n FinderPattern.prototype.hashCode = function () {\n return this.value;\n };\n return FinderPattern;\n}());\nexport default FinderPattern;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport DataCharacter from './DataCharacter';\nvar Pair = /** @class */ (function (_super) {\n __extends(Pair, _super);\n function Pair(value, checksumPortion, finderPattern) {\n var _this = _super.call(this, value, checksumPortion) || this;\n _this.count = 0;\n _this.finderPattern = finderPattern;\n return _this;\n }\n Pair.prototype.getFinderPattern = function () {\n return this.finderPattern;\n };\n Pair.prototype.getCount = function () {\n return this.count;\n };\n Pair.prototype.incrementCount = function () {\n this.count++;\n };\n return Pair;\n}(DataCharacter));\nexport default Pair;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport AbstractRSSReader from './AbstractRSSReader';\nimport Pair from './Pair';\nimport Result from '../../Result';\nimport DecodeHintType from '../../DecodeHintType';\nimport NotFoundException from '../../NotFoundException';\nimport StringBuilder from '../../util/StringBuilder';\nimport BarcodeFormat from '../../BarcodeFormat';\nimport ResultPoint from '../../ResultPoint';\nimport FinderPattern from './FinderPattern';\nimport DataCharacter from './DataCharacter';\nimport MathUtils from '../../common/detector/MathUtils';\nimport RSSUtils from './RSSUtils';\nimport System from '../../util/System';\nimport OneDReader from '../OneDReader';\nvar RSS14Reader = /** @class */ (function (_super) {\n __extends(RSS14Reader, _super);\n function RSS14Reader() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.possibleLeftPairs = [];\n _this.possibleRightPairs = [];\n return _this;\n }\n RSS14Reader.prototype.decodeRow = function (rowNumber, row, hints) {\n var e_1, _a, e_2, _b;\n var leftPair = this.decodePair(row, false, rowNumber, hints);\n RSS14Reader.addOrTally(this.possibleLeftPairs, leftPair);\n row.reverse();\n var rightPair = this.decodePair(row, true, rowNumber, hints);\n RSS14Reader.addOrTally(this.possibleRightPairs, rightPair);\n row.reverse();\n try {\n for (var _c = __values(this.possibleLeftPairs), _d = _c.next(); !_d.done; _d = _c.next()) {\n var left = _d.value;\n if (left.getCount() > 1) {\n try {\n for (var _e = (e_2 = void 0, __values(this.possibleRightPairs)), _f = _e.next(); !_f.done; _f = _e.next()) {\n var right = _f.value;\n if (right.getCount() > 1 && RSS14Reader.checkChecksum(left, right)) {\n return RSS14Reader.constructResult(left, right);\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n }\n finally { if (e_2) throw e_2.error; }\n }\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n }\n finally { if (e_1) throw e_1.error; }\n }\n throw new NotFoundException();\n };\n RSS14Reader.addOrTally = function (possiblePairs, pair) {\n var e_3, _a;\n if (pair == null) {\n return;\n }\n var found = false;\n try {\n for (var possiblePairs_1 = __values(possiblePairs), possiblePairs_1_1 = possiblePairs_1.next(); !possiblePairs_1_1.done; possiblePairs_1_1 = possiblePairs_1.next()) {\n var other = possiblePairs_1_1.value;\n if (other.getValue() === pair.getValue()) {\n other.incrementCount();\n found = true;\n break;\n }\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (possiblePairs_1_1 && !possiblePairs_1_1.done && (_a = possiblePairs_1.return)) _a.call(possiblePairs_1);\n }\n finally { if (e_3) throw e_3.error; }\n }\n if (!found) {\n possiblePairs.push(pair);\n }\n };\n RSS14Reader.prototype.reset = function () {\n this.possibleLeftPairs.length = 0;\n this.possibleRightPairs.length = 0;\n };\n RSS14Reader.constructResult = function (leftPair, rightPair) {\n var symbolValue = 4537077 * leftPair.getValue() + rightPair.getValue();\n var text = new String(symbolValue).toString();\n var buffer = new StringBuilder();\n for (var i = 13 - text.length; i > 0; i--) {\n buffer.append('0');\n }\n buffer.append(text);\n var checkDigit = 0;\n for (var i = 0; i < 13; i++) {\n var digit = buffer.charAt(i).charCodeAt(0) - '0'.charCodeAt(0);\n checkDigit += ((i & 0x01) === 0) ? 3 * digit : digit;\n }\n checkDigit = 10 - (checkDigit % 10);\n if (checkDigit === 10) {\n checkDigit = 0;\n }\n buffer.append(checkDigit.toString());\n var leftPoints = leftPair.getFinderPattern().getResultPoints();\n var rightPoints = rightPair.getFinderPattern().getResultPoints();\n return new Result(buffer.toString(), null, 0, [leftPoints[0], leftPoints[1], rightPoints[0], rightPoints[1]], BarcodeFormat.RSS_14, new Date().getTime());\n };\n RSS14Reader.checkChecksum = function (leftPair, rightPair) {\n var checkValue = (leftPair.getChecksumPortion() + 16 * rightPair.getChecksumPortion()) % 79;\n var targetCheckValue = 9 * leftPair.getFinderPattern().getValue() + rightPair.getFinderPattern().getValue();\n if (targetCheckValue > 72) {\n targetCheckValue--;\n }\n if (targetCheckValue > 8) {\n targetCheckValue--;\n }\n return checkValue === targetCheckValue;\n };\n RSS14Reader.prototype.decodePair = function (row, right, rowNumber, hints) {\n try {\n var startEnd = this.findFinderPattern(row, right);\n var pattern = this.parseFoundFinderPattern(row, rowNumber, right, startEnd);\n var resultPointCallback = hints == null ? null : hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);\n if (resultPointCallback != null) {\n var center = (startEnd[0] + startEnd[1]) / 2.0;\n if (right) {\n // row is actually reversed\n center = row.getSize() - 1 - center;\n }\n resultPointCallback.foundPossibleResultPoint(new ResultPoint(center, rowNumber));\n }\n var outside = this.decodeDataCharacter(row, pattern, true);\n var inside = this.decodeDataCharacter(row, pattern, false);\n return new Pair(1597 * outside.getValue() + inside.getValue(), outside.getChecksumPortion() + 4 * inside.getChecksumPortion(), pattern);\n }\n catch (err) {\n return null;\n }\n };\n RSS14Reader.prototype.decodeDataCharacter = function (row, pattern, outsideChar) {\n var counters = this.getDataCharacterCounters();\n for (var x = 0; x < counters.length; x++) {\n counters[x] = 0;\n }\n if (outsideChar) {\n OneDReader.recordPatternInReverse(row, pattern.getStartEnd()[0], counters);\n }\n else {\n OneDReader.recordPattern(row, pattern.getStartEnd()[1] + 1, counters);\n // reverse it\n for (var i = 0, j = counters.length - 1; i < j; i++, j--) {\n var temp = counters[i];\n counters[i] = counters[j];\n counters[j] = temp;\n }\n }\n var numModules = outsideChar ? 16 : 15;\n var elementWidth = MathUtils.sum(new Int32Array(counters)) / numModules;\n var oddCounts = this.getOddCounts();\n var evenCounts = this.getEvenCounts();\n var oddRoundingErrors = this.getOddRoundingErrors();\n var evenRoundingErrors = this.getEvenRoundingErrors();\n for (var i = 0; i < counters.length; i++) {\n var value = counters[i] / elementWidth;\n var count = Math.floor(value + 0.5);\n if (count < 1) {\n count = 1;\n }\n else if (count > 8) {\n count = 8;\n }\n var offset = Math.floor(i / 2);\n if ((i & 0x01) === 0) {\n oddCounts[offset] = count;\n oddRoundingErrors[offset] = value - count;\n }\n else {\n evenCounts[offset] = count;\n evenRoundingErrors[offset] = value - count;\n }\n }\n this.adjustOddEvenCounts(outsideChar, numModules);\n var oddSum = 0;\n var oddChecksumPortion = 0;\n for (var i = oddCounts.length - 1; i >= 0; i--) {\n oddChecksumPortion *= 9;\n oddChecksumPortion += oddCounts[i];\n oddSum += oddCounts[i];\n }\n var evenChecksumPortion = 0;\n var evenSum = 0;\n for (var i = evenCounts.length - 1; i >= 0; i--) {\n evenChecksumPortion *= 9;\n evenChecksumPortion += evenCounts[i];\n evenSum += evenCounts[i];\n }\n var checksumPortion = oddChecksumPortion + 3 * evenChecksumPortion;\n if (outsideChar) {\n if ((oddSum & 0x01) !== 0 || oddSum > 12 || oddSum < 4) {\n throw new NotFoundException();\n }\n var group = (12 - oddSum) / 2;\n var oddWidest = RSS14Reader.OUTSIDE_ODD_WIDEST[group];\n var evenWidest = 9 - oddWidest;\n var vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, false);\n var vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, true);\n var tEven = RSS14Reader.OUTSIDE_EVEN_TOTAL_SUBSET[group];\n var gSum = RSS14Reader.OUTSIDE_GSUM[group];\n return new DataCharacter(vOdd * tEven + vEven + gSum, checksumPortion);\n }\n else {\n if ((evenSum & 0x01) !== 0 || evenSum > 10 || evenSum < 4) {\n throw new NotFoundException();\n }\n var group = (10 - evenSum) / 2;\n var oddWidest = RSS14Reader.INSIDE_ODD_WIDEST[group];\n var evenWidest = 9 - oddWidest;\n var vOdd = RSSUtils.getRSSvalue(oddCounts, oddWidest, true);\n var vEven = RSSUtils.getRSSvalue(evenCounts, evenWidest, false);\n var tOdd = RSS14Reader.INSIDE_ODD_TOTAL_SUBSET[group];\n var gSum = RSS14Reader.INSIDE_GSUM[group];\n return new DataCharacter(vEven * tOdd + vOdd + gSum, checksumPortion);\n }\n };\n RSS14Reader.prototype.findFinderPattern = function (row, rightFinderPattern) {\n var counters = this.getDecodeFinderCounters();\n counters[0] = 0;\n counters[1] = 0;\n counters[2] = 0;\n counters[3] = 0;\n var width = row.getSize();\n var isWhite = false;\n var rowOffset = 0;\n while (rowOffset < width) {\n isWhite = !row.get(rowOffset);\n if (rightFinderPattern === isWhite) {\n // Will encounter white first when searching for right finder pattern\n break;\n }\n rowOffset++;\n }\n var counterPosition = 0;\n var patternStart = rowOffset;\n for (var x = rowOffset; x < width; x++) {\n if (row.get(x) !== isWhite) {\n counters[counterPosition]++;\n }\n else {\n if (counterPosition === 3) {\n if (AbstractRSSReader.isFinderPattern(counters)) {\n return [patternStart, x];\n }\n patternStart += counters[0] + counters[1];\n counters[0] = counters[2];\n counters[1] = counters[3];\n counters[2] = 0;\n counters[3] = 0;\n counterPosition--;\n }\n else {\n counterPosition++;\n }\n counters[counterPosition] = 1;\n isWhite = !isWhite;\n }\n }\n throw new NotFoundException();\n };\n RSS14Reader.prototype.parseFoundFinderPattern = function (row, rowNumber, right, startEnd) {\n // Actually we found elements 2-5\n var firstIsBlack = row.get(startEnd[0]);\n var firstElementStart = startEnd[0] - 1;\n // Locate element 1\n while (firstElementStart >= 0 && firstIsBlack !== row.get(firstElementStart)) {\n firstElementStart--;\n }\n firstElementStart++;\n var firstCounter = startEnd[0] - firstElementStart;\n // Make 'counters' hold 1-4\n var counters = this.getDecodeFinderCounters();\n var copy = new Int32Array(counters.length);\n System.arraycopy(counters, 0, copy, 1, counters.length - 1);\n copy[0] = firstCounter;\n var value = this.parseFinderValue(copy, RSS14Reader.FINDER_PATTERNS);\n var start = firstElementStart;\n var end = startEnd[1];\n if (right) {\n // row is actually reversed\n start = row.getSize() - 1 - start;\n end = row.getSize() - 1 - end;\n }\n return new FinderPattern(value, [firstElementStart, startEnd[1]], start, end, rowNumber);\n };\n RSS14Reader.prototype.adjustOddEvenCounts = function (outsideChar, numModules) {\n var oddSum = MathUtils.sum(new Int32Array(this.getOddCounts()));\n var evenSum = MathUtils.sum(new Int32Array(this.getEvenCounts()));\n var incrementOdd = false;\n var decrementOdd = false;\n var incrementEven = false;\n var decrementEven = false;\n if (outsideChar) {\n if (oddSum > 12) {\n decrementOdd = true;\n }\n else if (oddSum < 4) {\n incrementOdd = true;\n }\n if (evenSum > 12) {\n decrementEven = true;\n }\n else if (evenSum < 4) {\n incrementEven = true;\n }\n }\n else {\n if (oddSum > 11) {\n decrementOdd = true;\n }\n else if (oddSum < 5) {\n incrementOdd = true;\n }\n if (evenSum > 10) {\n decrementEven = true;\n }\n else if (evenSum < 4) {\n incrementEven = true;\n }\n }\n var mismatch = oddSum + evenSum - numModules;\n var oddParityBad = (oddSum & 0x01) === (outsideChar ? 1 : 0);\n var evenParityBad = (evenSum & 0x01) === 1;\n if (mismatch === 1) {\n if (oddParityBad) {\n if (evenParityBad) {\n throw new NotFoundException();\n }\n decrementOdd = true;\n }\n else {\n if (!evenParityBad) {\n throw new NotFoundException();\n }\n decrementEven = true;\n }\n }\n else if (mismatch === -1) {\n if (oddParityBad) {\n if (evenParityBad) {\n throw new NotFoundException();\n }\n incrementOdd = true;\n }\n else {\n if (!evenParityBad) {\n throw new NotFoundException();\n }\n incrementEven = true;\n }\n }\n else if (mismatch === 0) {\n if (oddParityBad) {\n if (!evenParityBad) {\n throw new NotFoundException();\n }\n // Both bad\n if (oddSum < evenSum) {\n incrementOdd = true;\n decrementEven = true;\n }\n else {\n decrementOdd = true;\n incrementEven = true;\n }\n }\n else {\n if (evenParityBad) {\n throw new NotFoundException();\n }\n // Nothing to do!\n }\n }\n else {\n throw new NotFoundException();\n }\n if (incrementOdd) {\n if (decrementOdd) {\n throw new NotFoundException();\n }\n AbstractRSSReader.increment(this.getOddCounts(), this.getOddRoundingErrors());\n }\n if (decrementOdd) {\n AbstractRSSReader.decrement(this.getOddCounts(), this.getOddRoundingErrors());\n }\n if (incrementEven) {\n if (decrementEven) {\n throw new NotFoundException();\n }\n AbstractRSSReader.increment(this.getEvenCounts(), this.getOddRoundingErrors());\n }\n if (decrementEven) {\n AbstractRSSReader.decrement(this.getEvenCounts(), this.getEvenRoundingErrors());\n }\n };\n RSS14Reader.OUTSIDE_EVEN_TOTAL_SUBSET = [1, 10, 34, 70, 126];\n RSS14Reader.INSIDE_ODD_TOTAL_SUBSET = [4, 20, 48, 81];\n RSS14Reader.OUTSIDE_GSUM = [0, 161, 961, 2015, 2715];\n RSS14Reader.INSIDE_GSUM = [0, 336, 1036, 1516];\n RSS14Reader.OUTSIDE_ODD_WIDEST = [8, 6, 4, 3, 1];\n RSS14Reader.INSIDE_ODD_WIDEST = [2, 4, 6, 8];\n RSS14Reader.FINDER_PATTERNS = [\n Int32Array.from([3, 8, 2, 1]),\n Int32Array.from([3, 5, 5, 1]),\n Int32Array.from([3, 3, 7, 1]),\n Int32Array.from([3, 1, 9, 1]),\n Int32Array.from([2, 7, 4, 1]),\n Int32Array.from([2, 5, 6, 1]),\n Int32Array.from([2, 3, 8, 1]),\n Int32Array.from([1, 5, 7, 1]),\n Int32Array.from([1, 3, 9, 1]),\n ];\n return RSS14Reader;\n}(AbstractRSSReader));\nexport default RSS14Reader;\n","var __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/**\n * RSS util functions.\n */\nvar RSSUtils = /** @class */ (function () {\n function RSSUtils() {\n }\n RSSUtils.getRSSvalue = function (widths, maxWidth, noNarrow) {\n var e_1, _a;\n var n = 0;\n try {\n for (var widths_1 = __values(widths), widths_1_1 = widths_1.next(); !widths_1_1.done; widths_1_1 = widths_1.next()) {\n var width = widths_1_1.value;\n n += width;\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (widths_1_1 && !widths_1_1.done && (_a = widths_1.return)) _a.call(widths_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n var val = 0;\n var narrowMask = 0;\n var elements = widths.length;\n for (var bar = 0; bar < elements - 1; bar++) {\n var elmWidth = void 0;\n for (elmWidth = 1, narrowMask |= 1 << bar; elmWidth < widths[bar]; elmWidth++, narrowMask &= ~(1 << bar)) {\n var subVal = RSSUtils.combins(n - elmWidth - 1, elements - bar - 2);\n if (noNarrow && (narrowMask === 0) && (n - elmWidth - (elements - bar - 1) >= elements - bar - 1)) {\n subVal -= RSSUtils.combins(n - elmWidth - (elements - bar), elements - bar - 2);\n }\n if (elements - bar - 1 > 1) {\n var lessVal = 0;\n for (var mxwElement = n - elmWidth - (elements - bar - 2); mxwElement > maxWidth; mxwElement--) {\n lessVal += RSSUtils.combins(n - elmWidth - mxwElement - 1, elements - bar - 3);\n }\n subVal -= lessVal * (elements - 1 - bar);\n }\n else if (n - elmWidth > maxWidth) {\n subVal--;\n }\n val += subVal;\n }\n n -= elmWidth;\n }\n return val;\n };\n RSSUtils.combins = function (n, r) {\n var maxDenom;\n var minDenom;\n if (n - r > r) {\n minDenom = r;\n maxDenom = n - r;\n }\n else {\n minDenom = n - r;\n maxDenom = r;\n }\n var val = 1;\n var j = 1;\n for (var i = n; i > maxDenom; i--) {\n val *= i;\n if (j <= minDenom) {\n val /= j;\n j++;\n }\n }\n while ((j <= minDenom)) {\n val /= j;\n j++;\n }\n return val;\n };\n return RSSUtils;\n}());\nexport default RSSUtils;\n","import BitArray from '../../../common/BitArray';\nvar BitArrayBuilder = /** @class */ (function () {\n function BitArrayBuilder() {\n }\n BitArrayBuilder.buildBitArray = function (pairs) {\n var charNumber = pairs.length * 2 - 1;\n if (pairs[pairs.length - 1].getRightChar() == null) {\n charNumber -= 1;\n }\n var size = 12 * charNumber;\n var binary = new BitArray(size);\n var accPos = 0;\n var firstPair = pairs[0];\n var firstValue = firstPair.getRightChar().getValue();\n for (var i = 11; i >= 0; --i) {\n if ((firstValue & (1 << i)) !== 0) {\n binary.set(accPos);\n }\n accPos++;\n }\n for (var i = 1; i < pairs.length; ++i) {\n var currentPair = pairs[i];\n var leftValue = currentPair.getLeftChar().getValue();\n for (var j = 11; j >= 0; --j) {\n if ((leftValue & (1 << j)) !== 0) {\n binary.set(accPos);\n }\n accPos++;\n }\n if (currentPair.getRightChar() !== null) {\n var rightValue = currentPair.getRightChar().getValue();\n for (var j = 11; j >= 0; --j) {\n if ((rightValue & (1 << j)) !== 0) {\n binary.set(accPos);\n }\n accPos++;\n }\n }\n }\n return binary;\n };\n return BitArrayBuilder;\n}());\nexport default BitArrayBuilder;\n","var ExpandedPair = /** @class */ (function () {\n function ExpandedPair(leftChar, rightChar, finderPatter, mayBeLast) {\n this.leftchar = leftChar;\n this.rightchar = rightChar;\n this.finderpattern = finderPatter;\n this.maybeLast = mayBeLast;\n }\n ExpandedPair.prototype.mayBeLast = function () {\n return this.maybeLast;\n };\n ExpandedPair.prototype.getLeftChar = function () {\n return this.leftchar;\n };\n ExpandedPair.prototype.getRightChar = function () {\n return this.rightchar;\n };\n ExpandedPair.prototype.getFinderPattern = function () {\n return this.finderpattern;\n };\n ExpandedPair.prototype.mustBeLast = function () {\n return this.rightchar == null;\n };\n ExpandedPair.prototype.toString = function () {\n return '[ ' + this.leftchar + ', ' + this.rightchar + ' : ' + (this.finderpattern == null ? 'null' : this.finderpattern.getValue()) + ' ]';\n };\n ExpandedPair.equals = function (o1, o2) {\n if (!(o1 instanceof ExpandedPair)) {\n return false;\n }\n return ExpandedPair.equalsOrNull(o1.leftchar, o2.leftchar) &&\n ExpandedPair.equalsOrNull(o1.rightchar, o2.rightchar) &&\n ExpandedPair.equalsOrNull(o1.finderpattern, o2.finderpattern);\n };\n ExpandedPair.equalsOrNull = function (o1, o2) {\n return o1 === null ? o2 === null : ExpandedPair.equals(o1, o2);\n };\n ExpandedPair.prototype.hashCode = function () {\n // return ExpandedPair.hashNotNull(leftChar) ^ hashNotNull(rightChar) ^ hashNotNull(finderPattern);\n var value = this.leftchar.getValue() ^ this.rightchar.getValue() ^ this.finderpattern.getValue();\n return value;\n };\n return ExpandedPair;\n}());\nexport default ExpandedPair;\n","var ExpandedRow = /** @class */ (function () {\n function ExpandedRow(pairs, rowNumber, wasReversed) {\n this.pairs = pairs;\n this.rowNumber = rowNumber;\n this.wasReversed = wasReversed;\n }\n ExpandedRow.prototype.getPairs = function () {\n return this.pairs;\n };\n ExpandedRow.prototype.getRowNumber = function () {\n return this.rowNumber;\n };\n ExpandedRow.prototype.isReversed = function () {\n return this.wasReversed;\n };\n // check implementation\n ExpandedRow.prototype.isEquivalent = function (otherPairs) {\n return this.checkEqualitity(this, otherPairs);\n };\n // @Override\n ExpandedRow.prototype.toString = function () {\n return '{ ' + this.pairs + ' }';\n };\n /**\n * Two rows are equal if they contain the same pairs in the same order.\n */\n // @Override\n // check implementation\n ExpandedRow.prototype.equals = function (o1, o2) {\n if (!(o1 instanceof ExpandedRow)) {\n return false;\n }\n return this.checkEqualitity(o1, o2) && o1.wasReversed === o2.wasReversed;\n };\n ExpandedRow.prototype.checkEqualitity = function (pair1, pair2) {\n if (!pair1 || !pair2)\n return;\n var result;\n pair1.forEach(function (e1, i) {\n pair2.forEach(function (e2) {\n if (e1.getLeftChar().getValue() === e2.getLeftChar().getValue() && e1.getRightChar().getValue() === e2.getRightChar().getValue() && e1.getFinderPatter().getValue() === e2.getFinderPatter().getValue()) {\n result = true;\n }\n });\n });\n return result;\n };\n return ExpandedRow;\n}());\nexport default ExpandedRow;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport BarcodeFormat from '../../../BarcodeFormat';\nimport MathUtils from '../../../common/detector/MathUtils';\n// import FormatException from '../../../FormatException';\nimport NotFoundException from '../../../NotFoundException';\nimport Result from '../../../Result';\nimport System from '../../../util/System';\nimport AbstractRSSReader from '../../rss/AbstractRSSReader';\nimport DataCharacter from '../../rss/DataCharacter';\nimport FinderPattern from '../../rss/FinderPattern';\nimport RSSUtils from '../../rss/RSSUtils';\nimport BitArrayBuilder from './BitArrayBuilder';\nimport { createDecoder } from './decoders/AbstractExpandedDecoderComplement';\nimport ExpandedPair from './ExpandedPair';\nimport ExpandedRow from './ExpandedRow';\n// import java.util.ArrayList;\n// import java.util.Iterator;\n// import java.util.List;\n// import java.util.Map;\n// import java.util.Collections;\n/** @experimental */\nvar RSSExpandedReader = /** @class */ (function (_super) {\n __extends(RSSExpandedReader, _super);\n function RSSExpandedReader() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this.pairs = new Array(RSSExpandedReader.MAX_PAIRS);\n _this.rows = new Array();\n _this.startEnd = [2];\n return _this;\n }\n RSSExpandedReader.prototype.decodeRow = function (rowNumber, row, hints) {\n // Rows can start with even pattern in case in prev rows there where odd number of patters.\n // So lets try twice\n // this.pairs.clear();\n this.pairs.length = 0;\n this.startFromEven = false;\n try {\n return RSSExpandedReader.constructResult(this.decodeRow2pairs(rowNumber, row));\n }\n catch (e) {\n // OK\n // console.log(e);\n }\n this.pairs.length = 0;\n this.startFromEven = true;\n return RSSExpandedReader.constructResult(this.decodeRow2pairs(rowNumber, row));\n };\n RSSExpandedReader.prototype.reset = function () {\n this.pairs.length = 0;\n this.rows.length = 0;\n };\n // Not private for testing\n RSSExpandedReader.prototype.decodeRow2pairs = function (rowNumber, row) {\n var done = false;\n while (!done) {\n try {\n this.pairs.push(this.retrieveNextPair(row, this.pairs, rowNumber));\n }\n catch (error) {\n if (error instanceof NotFoundException) {\n if (!this.pairs.length) {\n throw new NotFoundException();\n }\n // exit this loop when retrieveNextPair() fails and throws\n done = true;\n }\n }\n }\n // TODO: verify sequence of finder patterns as in checkPairSequence()\n if (this.checkChecksum()) {\n return this.pairs;\n }\n var tryStackedDecode;\n if (this.rows.length) {\n tryStackedDecode = true;\n }\n else {\n tryStackedDecode = false;\n }\n // let tryStackedDecode = !this.rows.isEmpty();\n this.storeRow(rowNumber, false); // TODO: deal with reversed rows\n if (tryStackedDecode) {\n // When the image is 180-rotated, then rows are sorted in wrong direction.\n // Try twice with both the directions.\n var ps = this.checkRowsBoolean(false);\n if (ps != null) {\n return ps;\n }\n ps = this.checkRowsBoolean(true);\n if (ps != null) {\n return ps;\n }\n }\n throw new NotFoundException();\n };\n // Need to Verify\n RSSExpandedReader.prototype.checkRowsBoolean = function (reverse) {\n // Limit number of rows we are checking\n // We use recursive algorithm with pure complexity and don't want it to take forever\n // Stacked barcode can have up to 11 rows, so 25 seems reasonable enough\n if (this.rows.length > 25) {\n this.rows.length = 0; // We will never have a chance to get result, so clear it\n return null;\n }\n this.pairs.length = 0;\n if (reverse) {\n this.rows = this.rows.reverse();\n // Collections.reverse(this.rows);\n }\n var ps = null;\n try {\n ps = this.checkRows(new Array(), 0);\n }\n catch (e) {\n // OK\n console.log(e);\n }\n if (reverse) {\n this.rows = this.rows.reverse();\n // Collections.reverse(this.rows);\n }\n return ps;\n };\n // Try to construct a valid rows sequence\n // Recursion is used to implement backtracking\n RSSExpandedReader.prototype.checkRows = function (collectedRows, currentRow) {\n var e_1, _a;\n for (var i = currentRow; i < this.rows.length; i++) {\n var row = this.rows[i];\n this.pairs.length = 0;\n try {\n for (var collectedRows_1 = (e_1 = void 0, __values(collectedRows)), collectedRows_1_1 = collectedRows_1.next(); !collectedRows_1_1.done; collectedRows_1_1 = collectedRows_1.next()) {\n var collectedRow = collectedRows_1_1.value;\n this.pairs.push(collectedRow.getPairs());\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (collectedRows_1_1 && !collectedRows_1_1.done && (_a = collectedRows_1.return)) _a.call(collectedRows_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n this.pairs.push(row.getPairs());\n if (!RSSExpandedReader.isValidSequence(this.pairs)) {\n continue;\n }\n if (this.checkChecksum()) {\n return this.pairs;\n }\n var rs = new Array(collectedRows);\n rs.push(row);\n try {\n // Recursion: try to add more rows\n return this.checkRows(rs, i + 1);\n }\n catch (e) {\n // We failed, try the next candidate\n console.log(e);\n }\n }\n throw new NotFoundException();\n };\n // Whether the pairs form a valid find pattern sequence,\n // either complete or a prefix\n RSSExpandedReader.isValidSequence = function (pairs) {\n var e_2, _a;\n try {\n for (var _b = __values(RSSExpandedReader.FINDER_PATTERN_SEQUENCES), _c = _b.next(); !_c.done; _c = _b.next()) {\n var sequence = _c.value;\n if (pairs.length > sequence.length) {\n continue;\n }\n var stop_1 = true;\n for (var j = 0; j < pairs.length; j++) {\n if (pairs[j].getFinderPattern().getValue() !== sequence[j]) {\n stop_1 = false;\n break;\n }\n }\n if (stop_1) {\n return true;\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return false;\n };\n RSSExpandedReader.prototype.storeRow = function (rowNumber, wasReversed) {\n // Discard if duplicate above or below; otherwise insert in order by row number.\n var insertPos = 0;\n var prevIsSame = false;\n var nextIsSame = false;\n while (insertPos < this.rows.length) {\n var erow = this.rows[insertPos];\n if (erow.getRowNumber() > rowNumber) {\n nextIsSame = erow.isEquivalent(this.pairs);\n break;\n }\n prevIsSame = erow.isEquivalent(this.pairs);\n insertPos++;\n }\n if (nextIsSame || prevIsSame) {\n return;\n }\n // When the row was partially decoded (e.g. 2 pairs found instead of 3),\n // it will prevent us from detecting the barcode.\n // Try to merge partial rows\n // Check whether the row is part of an allready detected row\n if (RSSExpandedReader.isPartialRow(this.pairs, this.rows)) {\n return;\n }\n this.rows.push(insertPos, new ExpandedRow(this.pairs, rowNumber, wasReversed));\n this.removePartialRows(this.pairs, this.rows);\n };\n // Remove all the rows that contains only specified pairs\n RSSExpandedReader.prototype.removePartialRows = function (pairs, rows) {\n var e_3, _a, e_4, _b, e_5, _c;\n try {\n // for (IteratorThis class contains the methods for decoding the PDF417 codewords.
\n *\n * @author SITA Lab (kevin.osullivan@sita.aero)\n * @author Guenther Grau\n */\nvar DecodedBitStreamParser = /** @class */ (function () {\n function DecodedBitStreamParser() {\n }\n // private DecodedBitStreamParser() {\n // }\n /**\n *\n * @param codewords\n * @param ecLevel\n *\n * @throws FormatException\n */\n DecodedBitStreamParser.decode = function (codewords, ecLevel) {\n // pass encoding to result (will be used for decode symbols in byte mode)\n var result = new StringBuilder('');\n // let encoding: Charset = StandardCharsets.ISO_8859_1;\n var encoding = CharacterSetECI.ISO8859_1;\n /**\n * @note the next command is specific from this TypeScript library\n * because TS can't properly cast some values to char and\n * convert it to string later correctly due to encoding\n * differences from Java version. As reported here:\n * https://github.com/zxing-js/library/pull/264/files#r382831593\n */\n result.enableDecoding(encoding);\n // Get compaction mode\n var codeIndex = 1;\n var code = codewords[codeIndex++];\n var resultMetadata = new PDF417ResultMetadata();\n while (codeIndex < codewords[0]) {\n switch (code) {\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex, result);\n break;\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6:\n codeIndex = DecodedBitStreamParser.byteCompaction(code, codewords, encoding, codeIndex, result);\n break;\n case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:\n result.append(/*(char)*/ codewords[codeIndex++]);\n break;\n case DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH:\n codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex, result);\n break;\n case DecodedBitStreamParser.ECI_CHARSET:\n var charsetECI = CharacterSetECI.getCharacterSetECIByValue(codewords[codeIndex++]);\n // encoding = Charset.forName(charsetECI.getName());\n break;\n case DecodedBitStreamParser.ECI_GENERAL_PURPOSE:\n // Can't do anything with generic ECI; skip its 2 characters\n codeIndex += 2;\n break;\n case DecodedBitStreamParser.ECI_USER_DEFINED:\n // Can't do anything with user ECI; skip its 1 character\n codeIndex++;\n break;\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK:\n codeIndex = DecodedBitStreamParser.decodeMacroBlock(codewords, codeIndex, resultMetadata);\n break;\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:\n case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR:\n // Should not see these outside a macro block\n throw new FormatException();\n default:\n // Default to text compaction. During testing numerous barcodes\n // appeared to be missing the starting mode. In these cases defaulting\n // to text compaction seems to work.\n codeIndex--;\n codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex, result);\n break;\n }\n if (codeIndex < codewords.length) {\n code = codewords[codeIndex++];\n }\n else {\n throw FormatException.getFormatInstance();\n }\n }\n if (result.length() === 0) {\n throw FormatException.getFormatInstance();\n }\n var decoderResult = new DecoderResult(null, result.toString(), null, ecLevel);\n decoderResult.setOther(resultMetadata);\n return decoderResult;\n };\n /**\n *\n * @param int\n * @param param1\n * @param codewords\n * @param int\n * @param codeIndex\n * @param PDF417ResultMetadata\n * @param resultMetadata\n *\n * @throws FormatException\n */\n // @SuppressWarnings(\"deprecation\")\n DecodedBitStreamParser.decodeMacroBlock = function (codewords, codeIndex, resultMetadata) {\n if (codeIndex + DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS > codewords[0]) {\n // we must have at least two bytes left for the segment index\n throw FormatException.getFormatInstance();\n }\n var segmentIndexArray = new Int32Array(DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS);\n for (var i /*int*/ = 0; i < DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS; i++, codeIndex++) {\n segmentIndexArray[i] = codewords[codeIndex];\n }\n resultMetadata.setSegmentIndex(Integer.parseInt(DecodedBitStreamParser.decodeBase900toBase10(segmentIndexArray, DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS)));\n var fileId = new StringBuilder();\n codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex, fileId);\n resultMetadata.setFileId(fileId.toString());\n var optionalFieldsStart = -1;\n if (codewords[codeIndex] === DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD) {\n optionalFieldsStart = codeIndex + 1;\n }\n while (codeIndex < codewords[0]) {\n switch (codewords[codeIndex]) {\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:\n codeIndex++;\n switch (codewords[codeIndex]) {\n case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME:\n var fileName = new StringBuilder();\n codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex + 1, fileName);\n resultMetadata.setFileName(fileName.toString());\n break;\n case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_SENDER:\n var sender = new StringBuilder();\n codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex + 1, sender);\n resultMetadata.setSender(sender.toString());\n break;\n case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE:\n var addressee = new StringBuilder();\n codeIndex = DecodedBitStreamParser.textCompaction(codewords, codeIndex + 1, addressee);\n resultMetadata.setAddressee(addressee.toString());\n break;\n case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT:\n var segmentCount = new StringBuilder();\n codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex + 1, segmentCount);\n resultMetadata.setSegmentCount(Integer.parseInt(segmentCount.toString()));\n break;\n case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP:\n var timestamp = new StringBuilder();\n codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex + 1, timestamp);\n resultMetadata.setTimestamp(Long.parseLong(timestamp.toString()));\n break;\n case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM:\n var checksum = new StringBuilder();\n codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex + 1, checksum);\n resultMetadata.setChecksum(Integer.parseInt(checksum.toString()));\n break;\n case DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE:\n var fileSize = new StringBuilder();\n codeIndex = DecodedBitStreamParser.numericCompaction(codewords, codeIndex + 1, fileSize);\n resultMetadata.setFileSize(Long.parseLong(fileSize.toString()));\n break;\n default:\n throw FormatException.getFormatInstance();\n }\n break;\n case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR:\n codeIndex++;\n resultMetadata.setLastSegment(true);\n break;\n default:\n throw FormatException.getFormatInstance();\n }\n }\n // copy optional fields to additional options\n if (optionalFieldsStart !== -1) {\n var optionalFieldsLength = codeIndex - optionalFieldsStart;\n if (resultMetadata.isLastSegment()) {\n // do not include terminator\n optionalFieldsLength--;\n }\n resultMetadata.setOptionalData(Arrays.copyOfRange(codewords, optionalFieldsStart, optionalFieldsStart + optionalFieldsLength));\n }\n return codeIndex;\n };\n /**\n * Text Compaction mode (see 5.4.1.5) permits all printable ASCII characters to be\n * encoded, i.e. values 32 - 126 inclusive in accordance with ISO/IEC 646 (IRV), as\n * well as selected control characters.\n *\n * @param codewords The array of codewords (data + error)\n * @param codeIndex The current index into the codeword array.\n * @param result The decoded data is appended to the result.\n * @return The next index into the codeword array.\n */\n DecodedBitStreamParser.textCompaction = function (codewords, codeIndex, result) {\n // 2 character per codeword\n var textCompactionData = new Int32Array((codewords[0] - codeIndex) * 2);\n // Used to hold the byte compaction value if there is a mode shift\n var byteCompactionData = new Int32Array((codewords[0] - codeIndex) * 2);\n var index = 0;\n var end = false;\n while ((codeIndex < codewords[0]) && !end) {\n var code = codewords[codeIndex++];\n if (code < DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH) {\n textCompactionData[index] = code / 30;\n textCompactionData[index + 1] = code % 30;\n index += 2;\n }\n else {\n switch (code) {\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n // reinitialize text compaction mode to alpha sub mode\n textCompactionData[index++] = DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH;\n break;\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6:\n case DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK:\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:\n case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR:\n codeIndex--;\n end = true;\n break;\n case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:\n // The Mode Shift codeword 913 shall cause a temporary\n // switch from Text Compaction mode to Byte Compaction mode.\n // This switch shall be in effect for only the next codeword,\n // after which the mode shall revert to the prevailing sub-mode\n // of the Text Compaction mode. Codeword 913 is only available\n // in Text Compaction mode; its use is described in 5.4.2.4.\n textCompactionData[index] = DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE;\n code = codewords[codeIndex++];\n byteCompactionData[index] = code;\n index++;\n break;\n }\n }\n }\n DecodedBitStreamParser.decodeTextCompaction(textCompactionData, byteCompactionData, index, result);\n return codeIndex;\n };\n /**\n * The Text Compaction mode includes all the printable ASCII characters\n * (i.e. values from 32 to 126) and three ASCII control characters: HT or tab\n * (9: e), LF or line feed (10: e), and CR or carriage\n * return (13: e). The Text Compaction mode also includes various latch\n * and shift characters which are used exclusively within the mode. The Text\n * Compaction mode encodes up to 2 characters per codeword. The compaction rules\n * for converting data into PDF417 codewords are defined in 5.4.2.2. The sub-mode\n * switches are defined in 5.4.2.3.\n *\n * @param textCompactionData The text compaction data.\n * @param byteCompactionData The byte compaction data if there\n * was a mode shift.\n * @param length The size of the text compaction and byte compaction data.\n * @param result The decoded data is appended to the result.\n */\n DecodedBitStreamParser.decodeTextCompaction = function (textCompactionData, byteCompactionData, length, result) {\n // Beginning from an initial state of the Alpha sub-mode\n // The default compaction mode for PDF417 in effect at the start of each symbol shall always be Text\n // Compaction mode Alpha sub-mode (alphabetic: uppercase). A latch codeword from another mode to the Text\n // Compaction mode shall always switch to the Text Compaction Alpha sub-mode.\n var subMode = Mode.ALPHA;\n var priorToShiftMode = Mode.ALPHA;\n var i = 0;\n while (i < length) {\n var subModeCh = textCompactionData[i];\n var ch = /*char*/ '';\n switch (subMode) {\n case Mode.ALPHA:\n // Alpha (alphabetic: uppercase)\n if (subModeCh < 26) {\n // Upper case Alpha Character\n // Note: 65 = 'A' ASCII -> there is byte code of symbol\n ch = /*(char)('A' + subModeCh) */ String.fromCharCode(65 + subModeCh);\n }\n else {\n switch (subModeCh) {\n case 26:\n ch = ' ';\n break;\n case DecodedBitStreamParser.LL:\n subMode = Mode.LOWER;\n break;\n case DecodedBitStreamParser.ML:\n subMode = Mode.MIXED;\n break;\n case DecodedBitStreamParser.PS:\n // Shift to punctuation\n priorToShiftMode = subMode;\n subMode = Mode.PUNCT_SHIFT;\n break;\n case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:\n result.append(/*(char)*/ byteCompactionData[i]);\n break;\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n subMode = Mode.ALPHA;\n break;\n }\n }\n break;\n case Mode.LOWER:\n // Lower (alphabetic: lowercase)\n if (subModeCh < 26) {\n ch = /*(char)('a' + subModeCh)*/ String.fromCharCode(97 + subModeCh);\n }\n else {\n switch (subModeCh) {\n case 26:\n ch = ' ';\n break;\n case DecodedBitStreamParser.AS:\n // Shift to alpha\n priorToShiftMode = subMode;\n subMode = Mode.ALPHA_SHIFT;\n break;\n case DecodedBitStreamParser.ML:\n subMode = Mode.MIXED;\n break;\n case DecodedBitStreamParser.PS:\n // Shift to punctuation\n priorToShiftMode = subMode;\n subMode = Mode.PUNCT_SHIFT;\n break;\n case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:\n // TODO Does this need to use the current character encoding? See other occurrences below\n result.append(/*(char)*/ byteCompactionData[i]);\n break;\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n subMode = Mode.ALPHA;\n break;\n }\n }\n break;\n case Mode.MIXED:\n // Mixed (punctuation: e)\n if (subModeCh < DecodedBitStreamParser.PL) {\n ch = DecodedBitStreamParser.MIXED_CHARS[subModeCh];\n }\n else {\n switch (subModeCh) {\n case DecodedBitStreamParser.PL:\n subMode = Mode.PUNCT;\n break;\n case 26:\n ch = ' ';\n break;\n case DecodedBitStreamParser.LL:\n subMode = Mode.LOWER;\n break;\n case DecodedBitStreamParser.AL:\n subMode = Mode.ALPHA;\n break;\n case DecodedBitStreamParser.PS:\n // Shift to punctuation\n priorToShiftMode = subMode;\n subMode = Mode.PUNCT_SHIFT;\n break;\n case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:\n result.append(/*(char)*/ byteCompactionData[i]);\n break;\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n subMode = Mode.ALPHA;\n break;\n }\n }\n break;\n case Mode.PUNCT:\n // Punctuation\n if (subModeCh < DecodedBitStreamParser.PAL) {\n ch = DecodedBitStreamParser.PUNCT_CHARS[subModeCh];\n }\n else {\n switch (subModeCh) {\n case DecodedBitStreamParser.PAL:\n subMode = Mode.ALPHA;\n break;\n case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:\n result.append(/*(char)*/ byteCompactionData[i]);\n break;\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n subMode = Mode.ALPHA;\n break;\n }\n }\n break;\n case Mode.ALPHA_SHIFT:\n // Restore sub-mode\n subMode = priorToShiftMode;\n if (subModeCh < 26) {\n ch = /*(char)('A' + subModeCh)*/ String.fromCharCode(65 + subModeCh);\n }\n else {\n switch (subModeCh) {\n case 26:\n ch = ' ';\n break;\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n subMode = Mode.ALPHA;\n break;\n }\n }\n break;\n case Mode.PUNCT_SHIFT:\n // Restore sub-mode\n subMode = priorToShiftMode;\n if (subModeCh < DecodedBitStreamParser.PAL) {\n ch = DecodedBitStreamParser.PUNCT_CHARS[subModeCh];\n }\n else {\n switch (subModeCh) {\n case DecodedBitStreamParser.PAL:\n subMode = Mode.ALPHA;\n break;\n case DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE:\n // PS before Shift-to-Byte is used as a padding character,\n // see 5.4.2.4 of the specification\n result.append(/*(char)*/ byteCompactionData[i]);\n break;\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n subMode = Mode.ALPHA;\n break;\n }\n }\n break;\n }\n // if (ch !== 0) {\n if (ch !== '') {\n // Append decoded character to result\n result.append(ch);\n }\n i++;\n }\n };\n /**\n * Byte Compaction mode (see 5.4.3) permits all 256 possible 8-bit byte values to be encoded.\n * This includes all ASCII characters value 0 to 127 inclusive and provides for international\n * character set support.\n *\n * @param mode The byte compaction mode i.e. 901 or 924\n * @param codewords The array of codewords (data + error)\n * @param encoding Currently active character encoding\n * @param codeIndex The current index into the codeword array.\n * @param result The decoded data is appended to the result.\n * @return The next index into the codeword array.\n */\n DecodedBitStreamParser.byteCompaction = function (mode, codewords, encoding, codeIndex, result) {\n var decodedBytes = new ByteArrayOutputStream();\n var count = 0;\n var value = /*long*/ 0;\n var end = false;\n switch (mode) {\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH:\n // Total number of Byte Compaction characters to be encoded\n // is not a multiple of 6\n var byteCompactedCodewords = new Int32Array(6);\n var nextCode = codewords[codeIndex++];\n while ((codeIndex < codewords[0]) && !end) {\n byteCompactedCodewords[count++] = nextCode;\n // Base 900\n value = 900 * value + nextCode;\n nextCode = codewords[codeIndex++];\n // perhaps it should be ok to check only nextCode >= TEXT_COMPACTION_MODE_LATCH\n switch (nextCode) {\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6:\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK:\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:\n case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR:\n codeIndex--;\n end = true;\n break;\n default:\n if ((count % 5 === 0) && (count > 0)) {\n // Decode every 5 codewords\n // Convert to Base 256\n for (var j /*int*/ = 0; j < 6; ++j) {\n /* @note\n * JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.\n * So the next bitwise operation could not be done with simple numbers\n */\n decodedBytes.write(/*(byte)*/ Number(createBigInt(value) >> createBigInt(8 * (5 - j))));\n }\n value = 0;\n count = 0;\n }\n break;\n }\n }\n // if the end of all codewords is reached the last codeword needs to be added\n if (codeIndex === codewords[0] && nextCode < DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH) {\n byteCompactedCodewords[count++] = nextCode;\n }\n // If Byte Compaction mode is invoked with codeword 901,\n // the last group of codewords is interpreted directly\n // as one byte per codeword, without compaction.\n for (var i /*int*/ = 0; i < count; i++) {\n decodedBytes.write(/*(byte)*/ byteCompactedCodewords[i]);\n }\n break;\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6:\n // Total number of Byte Compaction characters to be encoded\n // is an integer multiple of 6\n while (codeIndex < codewords[0] && !end) {\n var code = codewords[codeIndex++];\n if (code < DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH) {\n count++;\n // Base 900\n value = 900 * value + code;\n }\n else {\n switch (code) {\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6:\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK:\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:\n case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR:\n codeIndex--;\n end = true;\n break;\n }\n }\n if ((count % 5 === 0) && (count > 0)) {\n // Decode every 5 codewords\n // Convert to Base 256\n /* @note\n * JavaScript stores numbers as 64 bits floating point numbers, but all bitwise operations are performed on 32 bits binary numbers.\n * So the next bitwise operation could not be done with simple numbers\n */\n for (var j /*int*/ = 0; j < 6; ++j) {\n decodedBytes.write(/*(byte)*/ Number(createBigInt(value) >> createBigInt(8 * (5 - j))));\n }\n value = 0;\n count = 0;\n }\n }\n break;\n }\n result.append(StringEncoding.decode(decodedBytes.toByteArray(), encoding));\n return codeIndex;\n };\n /**\n * Numeric Compaction mode (see 5.4.4) permits efficient encoding of numeric data strings.\n *\n * @param codewords The array of codewords (data + error)\n * @param codeIndex The current index into the codeword array.\n * @param result The decoded data is appended to the result.\n * @return The next index into the codeword array.\n *\n * @throws FormatException\n */\n DecodedBitStreamParser.numericCompaction = function (codewords, codeIndex /*int*/, result) {\n var count = 0;\n var end = false;\n var numericCodewords = new Int32Array(DecodedBitStreamParser.MAX_NUMERIC_CODEWORDS);\n while (codeIndex < codewords[0] && !end) {\n var code = codewords[codeIndex++];\n if (codeIndex === codewords[0]) {\n end = true;\n }\n if (code < DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH) {\n numericCodewords[count] = code;\n count++;\n }\n else {\n switch (code) {\n case DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH:\n case DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6:\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK:\n case DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD:\n case DecodedBitStreamParser.MACRO_PDF417_TERMINATOR:\n codeIndex--;\n end = true;\n break;\n }\n }\n if ((count % DecodedBitStreamParser.MAX_NUMERIC_CODEWORDS === 0 || code === DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH || end) && count > 0) {\n // Re-invoking Numeric Compaction mode (by using codeword 902\n // while in Numeric Compaction mode) serves to terminate the\n // current Numeric Compaction mode grouping as described in 5.4.4.2,\n // and then to start a new one grouping.\n result.append(DecodedBitStreamParser.decodeBase900toBase10(numericCodewords, count));\n count = 0;\n }\n }\n return codeIndex;\n };\n /**\n * Convert a list of Numeric Compacted codewords from Base 900 to Base 10.\n *\n * @param codewords The array of codewords\n * @param count The number of codewords\n * @return The decoded string representing the Numeric data.\n *\n * EXAMPLE\n * Encode the fifteen digit numeric string 000213298174000\n * Prefix the numeric string with a 1 and set the initial value of\n * t = 1 000 213 298 174 000\n * Calculate codeword 0\n * d0 = 1 000 213 298 174 000 mod 900 = 200\n *\n * t = 1 000 213 298 174 000 div 900 = 1 111 348 109 082\n * Calculate codeword 1\n * d1 = 1 111 348 109 082 mod 900 = 282\n *\n * t = 1 111 348 109 082 div 900 = 1 234 831 232\n * Calculate codeword 2\n * d2 = 1 234 831 232 mod 900 = 632\n *\n * t = 1 234 831 232 div 900 = 1 372 034\n * Calculate codeword 3\n * d3 = 1 372 034 mod 900 = 434\n *\n * t = 1 372 034 div 900 = 1 524\n * Calculate codeword 4\n * d4 = 1 524 mod 900 = 624\n *\n * t = 1 524 div 900 = 1\n * Calculate codeword 5\n * d5 = 1 mod 900 = 1\n * t = 1 div 900 = 0\n * Codeword sequence is: 1, 624, 434, 632, 282, 200\n *\n * Decode the above codewords involves\n * 1 x 900 power of 5 + 624 x 900 power of 4 + 434 x 900 power of 3 +\n * 632 x 900 power of 2 + 282 x 900 power of 1 + 200 x 900 power of 0 = 1000213298174000\n *\n * Remove leading 1 => Result is 000213298174000\n *\n * @throws FormatException\n */\n DecodedBitStreamParser.decodeBase900toBase10 = function (codewords, count) {\n var result = createBigInt(0);\n for (var i /*int*/ = 0; i < count; i++) {\n result += DecodedBitStreamParser.EXP900[count - i - 1] * createBigInt(codewords[i]);\n }\n var resultString = result.toString();\n if (resultString.charAt(0) !== '1') {\n throw new FormatException();\n }\n return resultString.substring(1);\n };\n DecodedBitStreamParser.TEXT_COMPACTION_MODE_LATCH = 900;\n DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH = 901;\n DecodedBitStreamParser.NUMERIC_COMPACTION_MODE_LATCH = 902;\n DecodedBitStreamParser.BYTE_COMPACTION_MODE_LATCH_6 = 924;\n DecodedBitStreamParser.ECI_USER_DEFINED = 925;\n DecodedBitStreamParser.ECI_GENERAL_PURPOSE = 926;\n DecodedBitStreamParser.ECI_CHARSET = 927;\n DecodedBitStreamParser.BEGIN_MACRO_PDF417_CONTROL_BLOCK = 928;\n DecodedBitStreamParser.BEGIN_MACRO_PDF417_OPTIONAL_FIELD = 923;\n DecodedBitStreamParser.MACRO_PDF417_TERMINATOR = 922;\n DecodedBitStreamParser.MODE_SHIFT_TO_BYTE_COMPACTION_MODE = 913;\n DecodedBitStreamParser.MAX_NUMERIC_CODEWORDS = 15;\n DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_FILE_NAME = 0;\n DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_SEGMENT_COUNT = 1;\n DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_TIME_STAMP = 2;\n DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_SENDER = 3;\n DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_ADDRESSEE = 4;\n DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_FILE_SIZE = 5;\n DecodedBitStreamParser.MACRO_PDF417_OPTIONAL_FIELD_CHECKSUM = 6;\n DecodedBitStreamParser.PL = 25;\n DecodedBitStreamParser.LL = 27;\n DecodedBitStreamParser.AS = 27;\n DecodedBitStreamParser.ML = 28;\n DecodedBitStreamParser.AL = 28;\n DecodedBitStreamParser.PS = 29;\n DecodedBitStreamParser.PAL = 29;\n DecodedBitStreamParser.PUNCT_CHARS = ';<>@[\\\\]_`~!\\r\\t,:\\n-.$/\"|*()?{}\\'';\n DecodedBitStreamParser.MIXED_CHARS = '0123456789&\\r\\t,:#-.$/+%*=^';\n /**\n * Table containing values for the exponent of 900.\n * This is used in the numeric compaction decode algorithm.\n */\n DecodedBitStreamParser.EXP900 = getBigIntConstructor() ? getEXP900() : [];\n DecodedBitStreamParser.NUMBER_OF_SEQUENCE_CODEWORDS = 2;\n return DecodedBitStreamParser;\n}());\nexport default DecodedBitStreamParser;\n","/*\n * Copyright 2013 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n// package com.google.zxing.pdf417.decoder;\n// import com.google.zxing.pdf417.PDF417Common;\nimport PDF417Common from '../PDF417Common';\nimport Formatter from '../../util/Formatter';\n/**\n * @author Guenther Grau\n */\nvar DetectionResult = /** @class */ (function () {\n function DetectionResult(barcodeMetadata, boundingBox) {\n /*final*/ this.ADJUST_ROW_NUMBER_SKIP = 2;\n this.barcodeMetadata = barcodeMetadata;\n this.barcodeColumnCount = barcodeMetadata.getColumnCount();\n this.boundingBox = boundingBox;\n // this.detectionResultColumns = new DetectionResultColumn[this.barcodeColumnCount + 2];\n this.detectionResultColumns = new Array(this.barcodeColumnCount + 2);\n }\n DetectionResult.prototype.getDetectionResultColumns = function () {\n this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[0]);\n this.adjustIndicatorColumnRowNumbers(this.detectionResultColumns[this.barcodeColumnCount + 1]);\n var unadjustedCodewordCount = PDF417Common.MAX_CODEWORDS_IN_BARCODE;\n var previousUnadjustedCount;\n do {\n previousUnadjustedCount = unadjustedCodewordCount;\n unadjustedCodewordCount = this.adjustRowNumbersAndGetCount();\n } while (unadjustedCodewordCount > 0 && unadjustedCodewordCount < previousUnadjustedCount);\n return this.detectionResultColumns;\n };\n DetectionResult.prototype.adjustIndicatorColumnRowNumbers = function (detectionResultColumn) {\n if (detectionResultColumn != null) {\n detectionResultColumn\n .adjustCompleteIndicatorColumnRowNumbers(this.barcodeMetadata);\n }\n };\n // TODO ensure that no detected codewords with unknown row number are left\n // we should be able to estimate the row height and use it as a hint for the row number\n // we should also fill the rows top to bottom and bottom to top\n /**\n * @return number of codewords which don't have a valid row number. Note that the count is not accurate as codewords\n * will be counted several times. It just serves as an indicator to see when we can stop adjusting row numbers\n */\n DetectionResult.prototype.adjustRowNumbersAndGetCount = function () {\n var unadjustedCount = this.adjustRowNumbersByRow();\n if (unadjustedCount === 0) {\n return 0;\n }\n for (var barcodeColumn /*int*/ = 1; barcodeColumn < this.barcodeColumnCount + 1; barcodeColumn++) {\n var codewords = this.detectionResultColumns[barcodeColumn].getCodewords();\n for (var codewordsRow /*int*/ = 0; codewordsRow < codewords.length; codewordsRow++) {\n if (codewords[codewordsRow] == null) {\n continue;\n }\n if (!codewords[codewordsRow].hasValidRowNumber()) {\n this.adjustRowNumbers(barcodeColumn, codewordsRow, codewords);\n }\n }\n }\n return unadjustedCount;\n };\n DetectionResult.prototype.adjustRowNumbersByRow = function () {\n this.adjustRowNumbersFromBothRI();\n // TODO we should only do full row adjustments if row numbers of left and right row indicator column match.\n // Maybe it's even better to calculated the height (rows: d) and divide it by the number of barcode\n // rows. This, together with the LRI and RRI row numbers should allow us to get a good estimate where a row\n // number starts and ends.\n var unadjustedCount = this.adjustRowNumbersFromLRI();\n return unadjustedCount + this.adjustRowNumbersFromRRI();\n };\n DetectionResult.prototype.adjustRowNumbersFromBothRI = function () {\n if (this.detectionResultColumns[0] == null || this.detectionResultColumns[this.barcodeColumnCount + 1] == null) {\n return;\n }\n var LRIcodewords = this.detectionResultColumns[0].getCodewords();\n var RRIcodewords = this.detectionResultColumns[this.barcodeColumnCount + 1].getCodewords();\n for (var codewordsRow /*int*/ = 0; codewordsRow < LRIcodewords.length; codewordsRow++) {\n if (LRIcodewords[codewordsRow] != null &&\n RRIcodewords[codewordsRow] != null &&\n LRIcodewords[codewordsRow].getRowNumber() === RRIcodewords[codewordsRow].getRowNumber()) {\n for (var barcodeColumn /*int*/ = 1; barcodeColumn <= this.barcodeColumnCount; barcodeColumn++) {\n var codeword = this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];\n if (codeword == null) {\n continue;\n }\n codeword.setRowNumber(LRIcodewords[codewordsRow].getRowNumber());\n if (!codeword.hasValidRowNumber()) {\n this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow] = null;\n }\n }\n }\n }\n };\n DetectionResult.prototype.adjustRowNumbersFromRRI = function () {\n if (this.detectionResultColumns[this.barcodeColumnCount + 1] == null) {\n return 0;\n }\n var unadjustedCount = 0;\n var codewords = this.detectionResultColumns[this.barcodeColumnCount + 1].getCodewords();\n for (var codewordsRow /*int*/ = 0; codewordsRow < codewords.length; codewordsRow++) {\n if (codewords[codewordsRow] == null) {\n continue;\n }\n var rowIndicatorRowNumber = codewords[codewordsRow].getRowNumber();\n var invalidRowCounts = 0;\n for (var barcodeColumn /*int*/ = this.barcodeColumnCount + 1; barcodeColumn > 0 && invalidRowCounts < this.ADJUST_ROW_NUMBER_SKIP; barcodeColumn--) {\n var codeword = this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];\n if (codeword != null) {\n invalidRowCounts = DetectionResult.adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword);\n if (!codeword.hasValidRowNumber()) {\n unadjustedCount++;\n }\n }\n }\n }\n return unadjustedCount;\n };\n DetectionResult.prototype.adjustRowNumbersFromLRI = function () {\n if (this.detectionResultColumns[0] == null) {\n return 0;\n }\n var unadjustedCount = 0;\n var codewords = this.detectionResultColumns[0].getCodewords();\n for (var codewordsRow /*int*/ = 0; codewordsRow < codewords.length; codewordsRow++) {\n if (codewords[codewordsRow] == null) {\n continue;\n }\n var rowIndicatorRowNumber = codewords[codewordsRow].getRowNumber();\n var invalidRowCounts = 0;\n for (var barcodeColumn /*int*/ = 1; barcodeColumn < this.barcodeColumnCount + 1 && invalidRowCounts < this.ADJUST_ROW_NUMBER_SKIP; barcodeColumn++) {\n var codeword = this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];\n if (codeword != null) {\n invalidRowCounts = DetectionResult.adjustRowNumberIfValid(rowIndicatorRowNumber, invalidRowCounts, codeword);\n if (!codeword.hasValidRowNumber()) {\n unadjustedCount++;\n }\n }\n }\n }\n return unadjustedCount;\n };\n DetectionResult.adjustRowNumberIfValid = function (rowIndicatorRowNumber, invalidRowCounts, codeword) {\n if (codeword == null) {\n return invalidRowCounts;\n }\n if (!codeword.hasValidRowNumber()) {\n if (codeword.isValidRowNumber(rowIndicatorRowNumber)) {\n codeword.setRowNumber(rowIndicatorRowNumber);\n invalidRowCounts = 0;\n }\n else {\n ++invalidRowCounts;\n }\n }\n return invalidRowCounts;\n };\n DetectionResult.prototype.adjustRowNumbers = function (barcodeColumn, codewordsRow, codewords) {\n var e_1, _a;\n if (this.detectionResultColumns[barcodeColumn - 1] == null) {\n return;\n }\n var codeword = codewords[codewordsRow];\n var previousColumnCodewords = this.detectionResultColumns[barcodeColumn - 1].getCodewords();\n var nextColumnCodewords = previousColumnCodewords;\n if (this.detectionResultColumns[barcodeColumn + 1] != null) {\n nextColumnCodewords = this.detectionResultColumns[barcodeColumn + 1].getCodewords();\n }\n // let otherCodewords: Codeword[] = new Codeword[14];\n var otherCodewords = new Array(14);\n otherCodewords[2] = previousColumnCodewords[codewordsRow];\n otherCodewords[3] = nextColumnCodewords[codewordsRow];\n if (codewordsRow > 0) {\n otherCodewords[0] = codewords[codewordsRow - 1];\n otherCodewords[4] = previousColumnCodewords[codewordsRow - 1];\n otherCodewords[5] = nextColumnCodewords[codewordsRow - 1];\n }\n if (codewordsRow > 1) {\n otherCodewords[8] = codewords[codewordsRow - 2];\n otherCodewords[10] = previousColumnCodewords[codewordsRow - 2];\n otherCodewords[11] = nextColumnCodewords[codewordsRow - 2];\n }\n if (codewordsRow < codewords.length - 1) {\n otherCodewords[1] = codewords[codewordsRow + 1];\n otherCodewords[6] = previousColumnCodewords[codewordsRow + 1];\n otherCodewords[7] = nextColumnCodewords[codewordsRow + 1];\n }\n if (codewordsRow < codewords.length - 2) {\n otherCodewords[9] = codewords[codewordsRow + 2];\n otherCodewords[12] = previousColumnCodewords[codewordsRow + 2];\n otherCodewords[13] = nextColumnCodewords[codewordsRow + 2];\n }\n try {\n for (var otherCodewords_1 = __values(otherCodewords), otherCodewords_1_1 = otherCodewords_1.next(); !otherCodewords_1_1.done; otherCodewords_1_1 = otherCodewords_1.next()) {\n var otherCodeword = otherCodewords_1_1.value;\n if (DetectionResult.adjustRowNumber(codeword, otherCodeword)) {\n return;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (otherCodewords_1_1 && !otherCodewords_1_1.done && (_a = otherCodewords_1.return)) _a.call(otherCodewords_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n };\n /**\n * @return true, if row number was adjusted, false otherwise\n */\n DetectionResult.adjustRowNumber = function (codeword, otherCodeword) {\n if (otherCodeword == null) {\n return false;\n }\n if (otherCodeword.hasValidRowNumber() && otherCodeword.getBucket() === codeword.getBucket()) {\n codeword.setRowNumber(otherCodeword.getRowNumber());\n return true;\n }\n return false;\n };\n DetectionResult.prototype.getBarcodeColumnCount = function () {\n return this.barcodeColumnCount;\n };\n DetectionResult.prototype.getBarcodeRowCount = function () {\n return this.barcodeMetadata.getRowCount();\n };\n DetectionResult.prototype.getBarcodeECLevel = function () {\n return this.barcodeMetadata.getErrorCorrectionLevel();\n };\n DetectionResult.prototype.setBoundingBox = function (boundingBox) {\n this.boundingBox = boundingBox;\n };\n DetectionResult.prototype.getBoundingBox = function () {\n return this.boundingBox;\n };\n DetectionResult.prototype.setDetectionResultColumn = function (barcodeColumn, detectionResultColumn) {\n this.detectionResultColumns[barcodeColumn] = detectionResultColumn;\n };\n DetectionResult.prototype.getDetectionResultColumn = function (barcodeColumn) {\n return this.detectionResultColumns[barcodeColumn];\n };\n // @Override\n DetectionResult.prototype.toString = function () {\n var rowIndicatorColumn = this.detectionResultColumns[0];\n if (rowIndicatorColumn == null) {\n rowIndicatorColumn = this.detectionResultColumns[this.barcodeColumnCount + 1];\n }\n // try (\n var formatter = new Formatter();\n // ) {\n for (var codewordsRow /*int*/ = 0; codewordsRow < rowIndicatorColumn.getCodewords().length; codewordsRow++) {\n formatter.format('CW %3d:', codewordsRow);\n for (var barcodeColumn /*int*/ = 0; barcodeColumn < this.barcodeColumnCount + 2; barcodeColumn++) {\n if (this.detectionResultColumns[barcodeColumn] == null) {\n formatter.format(' | ');\n continue;\n }\n var codeword = this.detectionResultColumns[barcodeColumn].getCodewords()[codewordsRow];\n if (codeword == null) {\n formatter.format(' | ');\n continue;\n }\n formatter.format(' %3d|%3d', codeword.getRowNumber(), codeword.getValue());\n }\n formatter.format('%n');\n }\n return formatter.toString();\n // }\n };\n return DetectionResult;\n}());\nexport default DetectionResult;\n","/*\n * Copyright 2013 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n// package com.google.zxing.pdf417.decoder;\n// import java.util.Formatter;\nimport Formatter from '../../util/Formatter';\nimport BoundingBox from './BoundingBox';\n/**\n * @author Guenther Grau\n */\nvar DetectionResultColumn = /** @class */ (function () {\n function DetectionResultColumn(boundingBox) {\n this.boundingBox = new BoundingBox(boundingBox);\n // this.codewords = new Codeword[boundingBox.getMaxY() - boundingBox.getMinY() + 1];\n this.codewords = new Array(boundingBox.getMaxY() - boundingBox.getMinY() + 1);\n }\n /*final*/ DetectionResultColumn.prototype.getCodewordNearby = function (imageRow) {\n var codeword = this.getCodeword(imageRow);\n if (codeword != null) {\n return codeword;\n }\n for (var i = 1; i < DetectionResultColumn.MAX_NEARBY_DISTANCE; i++) {\n var nearImageRow = this.imageRowToCodewordIndex(imageRow) - i;\n if (nearImageRow >= 0) {\n codeword = this.codewords[nearImageRow];\n if (codeword != null) {\n return codeword;\n }\n }\n nearImageRow = this.imageRowToCodewordIndex(imageRow) + i;\n if (nearImageRow < this.codewords.length) {\n codeword = this.codewords[nearImageRow];\n if (codeword != null) {\n return codeword;\n }\n }\n }\n return null;\n };\n /*final int*/ DetectionResultColumn.prototype.imageRowToCodewordIndex = function (imageRow) {\n return imageRow - this.boundingBox.getMinY();\n };\n /*final void*/ DetectionResultColumn.prototype.setCodeword = function (imageRow, codeword) {\n this.codewords[this.imageRowToCodewordIndex(imageRow)] = codeword;\n };\n /*final*/ DetectionResultColumn.prototype.getCodeword = function (imageRow) {\n return this.codewords[this.imageRowToCodewordIndex(imageRow)];\n };\n /*final*/ DetectionResultColumn.prototype.getBoundingBox = function () {\n return this.boundingBox;\n };\n /*final*/ DetectionResultColumn.prototype.getCodewords = function () {\n return this.codewords;\n };\n // @Override\n DetectionResultColumn.prototype.toString = function () {\n var e_1, _a;\n var formatter = new Formatter();\n var row = 0;\n try {\n for (var _b = __values(this.codewords), _c = _b.next(); !_c.done; _c = _b.next()) {\n var codeword = _c.value;\n if (codeword == null) {\n formatter.format('%3d: | %n', row++);\n continue;\n }\n formatter.format('%3d: %3d|%3d%n', row++, codeword.getRowNumber(), codeword.getValue());\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return formatter.toString();\n };\n DetectionResultColumn.MAX_NEARBY_DISTANCE = 5;\n return DetectionResultColumn;\n}());\nexport default DetectionResultColumn;\n","/*\n * Copyright 2013 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n// import com.google.zxing.pdf417.PDF417Common;\nimport PDF417Common from '../PDF417Common';\nimport BarcodeMetadata from './BarcodeMetadata';\nimport DetectionResultColumn from './DetectionResultColumn';\nimport BarcodeValue from './BarcodeValue';\n/**\n * @author Guenther Grau\n */\nvar DetectionResultRowIndicatorColumn = /** @class */ (function (_super) {\n __extends(DetectionResultRowIndicatorColumn, _super);\n function DetectionResultRowIndicatorColumn(boundingBox, isLeft) {\n var _this = _super.call(this, boundingBox) || this;\n _this._isLeft = isLeft;\n return _this;\n }\n DetectionResultRowIndicatorColumn.prototype.setRowNumbers = function () {\n var e_1, _a;\n try {\n for (var _b = __values(this.getCodewords()), _c = _b.next(); !_c.done; _c = _b.next()) {\n var codeword = _c.value /*Codeword*/;\n if (codeword != null) {\n codeword.setRowNumberAsRowIndicatorColumn();\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n };\n // TODO implement properly\n // TODO maybe we should add missing codewords to store the correct row number to make\n // finding row numbers for other columns easier\n // use row height count to make detection of invalid row numbers more reliable\n DetectionResultRowIndicatorColumn.prototype.adjustCompleteIndicatorColumnRowNumbers = function (barcodeMetadata) {\n var codewords = this.getCodewords();\n this.setRowNumbers();\n this.removeIncorrectCodewords(codewords, barcodeMetadata);\n var boundingBox = this.getBoundingBox();\n var top = this._isLeft ? boundingBox.getTopLeft() : boundingBox.getTopRight();\n var bottom = this._isLeft ? boundingBox.getBottomLeft() : boundingBox.getBottomRight();\n var firstRow = this.imageRowToCodewordIndex(Math.trunc(top.getY()));\n var lastRow = this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));\n // We need to be careful using the average row height. Barcode could be skewed so that we have smaller and\n // taller rows\n // float averageRowHeight = (lastRow - firstRow) / /*(float)*/ barcodeMetadata.getRowCount();\n var barcodeRow = -1;\n var maxRowHeight = 1;\n var currentRowHeight = 0;\n for (var codewordsRow /*int*/ = firstRow; codewordsRow < lastRow; codewordsRow++) {\n if (codewords[codewordsRow] == null) {\n continue;\n }\n var codeword = codewords[codewordsRow];\n // float expectedRowNumber = (codewordsRow - firstRow) / averageRowHeight;\n // if (Math.abs(codeword.getRowNumber() - expectedRowNumber) > 2) {\n // SimpleLog.log(LEVEL.WARNING,\n // \"Removing codeword, rowNumberSkew too high, codeword[\" + codewordsRow + \"]: Expected Row: \" +\n // expectedRowNumber + \", RealRow: \" + codeword.getRowNumber() + \", value: \" + codeword.getValue());\n // codewords[codewordsRow] = null;\n // }\n var rowDifference = codeword.getRowNumber() - barcodeRow;\n // TODO improve handling with case where first row indicator doesn't start with 0\n if (rowDifference === 0) {\n currentRowHeight++;\n }\n else if (rowDifference === 1) {\n maxRowHeight = Math.max(maxRowHeight, currentRowHeight);\n currentRowHeight = 1;\n barcodeRow = codeword.getRowNumber();\n }\n else if (rowDifference < 0 ||\n codeword.getRowNumber() >= barcodeMetadata.getRowCount() ||\n rowDifference > codewordsRow) {\n codewords[codewordsRow] = null;\n }\n else {\n var checkedRows = void 0;\n if (maxRowHeight > 2) {\n checkedRows = (maxRowHeight - 2) * rowDifference;\n }\n else {\n checkedRows = rowDifference;\n }\n var closePreviousCodewordFound = checkedRows >= codewordsRow;\n for (var i /*int*/ = 1; i <= checkedRows && !closePreviousCodewordFound; i++) {\n // there must be (height * rowDifference) number of codewords missing. For now we assume height = 1.\n // This should hopefully get rid of most problems already.\n closePreviousCodewordFound = codewords[codewordsRow - i] != null;\n }\n if (closePreviousCodewordFound) {\n codewords[codewordsRow] = null;\n }\n else {\n barcodeRow = codeword.getRowNumber();\n currentRowHeight = 1;\n }\n }\n }\n // return (int) (averageRowHeight + 0.5);\n };\n DetectionResultRowIndicatorColumn.prototype.getRowHeights = function () {\n var e_2, _a;\n var barcodeMetadata = this.getBarcodeMetadata();\n if (barcodeMetadata == null) {\n return null;\n }\n this.adjustIncompleteIndicatorColumnRowNumbers(barcodeMetadata);\n var result = new Int32Array(barcodeMetadata.getRowCount());\n try {\n for (var _b = __values(this.getCodewords()), _c = _b.next(); !_c.done; _c = _b.next()) {\n var codeword = _c.value /*Codeword*/;\n if (codeword != null) {\n var rowNumber = codeword.getRowNumber();\n if (rowNumber >= result.length) {\n // We have more rows than the barcode metadata allows for, ignore them.\n continue;\n }\n result[rowNumber]++;\n } // else throw exception?\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return result;\n };\n // TODO maybe we should add missing codewords to store the correct row number to make\n // finding row numbers for other columns easier\n // use row height count to make detection of invalid row numbers more reliable\n DetectionResultRowIndicatorColumn.prototype.adjustIncompleteIndicatorColumnRowNumbers = function (barcodeMetadata) {\n var boundingBox = this.getBoundingBox();\n var top = this._isLeft ? boundingBox.getTopLeft() : boundingBox.getTopRight();\n var bottom = this._isLeft ? boundingBox.getBottomLeft() : boundingBox.getBottomRight();\n var firstRow = this.imageRowToCodewordIndex(Math.trunc(top.getY()));\n var lastRow = this.imageRowToCodewordIndex(Math.trunc(bottom.getY()));\n // float averageRowHeight = (lastRow - firstRow) / /*(float)*/ barcodeMetadata.getRowCount();\n var codewords = this.getCodewords();\n var barcodeRow = -1;\n var maxRowHeight = 1;\n var currentRowHeight = 0;\n for (var codewordsRow /*int*/ = firstRow; codewordsRow < lastRow; codewordsRow++) {\n if (codewords[codewordsRow] == null) {\n continue;\n }\n var codeword = codewords[codewordsRow];\n codeword.setRowNumberAsRowIndicatorColumn();\n var rowDifference = codeword.getRowNumber() - barcodeRow;\n // TODO improve handling with case where first row indicator doesn't start with 0\n if (rowDifference === 0) {\n currentRowHeight++;\n }\n else if (rowDifference === 1) {\n maxRowHeight = Math.max(maxRowHeight, currentRowHeight);\n currentRowHeight = 1;\n barcodeRow = codeword.getRowNumber();\n }\n else if (codeword.getRowNumber() >= barcodeMetadata.getRowCount()) {\n codewords[codewordsRow] = null;\n }\n else {\n barcodeRow = codeword.getRowNumber();\n currentRowHeight = 1;\n }\n }\n // return (int) (averageRowHeight + 0.5);\n };\n DetectionResultRowIndicatorColumn.prototype.getBarcodeMetadata = function () {\n var e_3, _a;\n var codewords = this.getCodewords();\n var barcodeColumnCount = new BarcodeValue();\n var barcodeRowCountUpperPart = new BarcodeValue();\n var barcodeRowCountLowerPart = new BarcodeValue();\n var barcodeECLevel = new BarcodeValue();\n try {\n for (var codewords_1 = __values(codewords), codewords_1_1 = codewords_1.next(); !codewords_1_1.done; codewords_1_1 = codewords_1.next()) {\n var codeword = codewords_1_1.value /*Codeword*/;\n if (codeword == null) {\n continue;\n }\n codeword.setRowNumberAsRowIndicatorColumn();\n var rowIndicatorValue = codeword.getValue() % 30;\n var codewordRowNumber = codeword.getRowNumber();\n if (!this._isLeft) {\n codewordRowNumber += 2;\n }\n switch (codewordRowNumber % 3) {\n case 0:\n barcodeRowCountUpperPart.setValue(rowIndicatorValue * 3 + 1);\n break;\n case 1:\n barcodeECLevel.setValue(rowIndicatorValue / 3);\n barcodeRowCountLowerPart.setValue(rowIndicatorValue % 3);\n break;\n case 2:\n barcodeColumnCount.setValue(rowIndicatorValue + 1);\n break;\n }\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (codewords_1_1 && !codewords_1_1.done && (_a = codewords_1.return)) _a.call(codewords_1);\n }\n finally { if (e_3) throw e_3.error; }\n }\n // Maybe we should check if we have ambiguous values?\n if ((barcodeColumnCount.getValue().length === 0) ||\n (barcodeRowCountUpperPart.getValue().length === 0) ||\n (barcodeRowCountLowerPart.getValue().length === 0) ||\n (barcodeECLevel.getValue().length === 0) ||\n barcodeColumnCount.getValue()[0] < 1 ||\n barcodeRowCountUpperPart.getValue()[0] + barcodeRowCountLowerPart.getValue()[0] < PDF417Common.MIN_ROWS_IN_BARCODE ||\n barcodeRowCountUpperPart.getValue()[0] + barcodeRowCountLowerPart.getValue()[0] > PDF417Common.MAX_ROWS_IN_BARCODE) {\n return null;\n }\n var barcodeMetadata = new BarcodeMetadata(barcodeColumnCount.getValue()[0], barcodeRowCountUpperPart.getValue()[0], barcodeRowCountLowerPart.getValue()[0], barcodeECLevel.getValue()[0]);\n this.removeIncorrectCodewords(codewords, barcodeMetadata);\n return barcodeMetadata;\n };\n DetectionResultRowIndicatorColumn.prototype.removeIncorrectCodewords = function (codewords, barcodeMetadata) {\n // Remove codewords which do not match the metadata\n // TODO Maybe we should keep the incorrect codewords for the start and end positions?\n for (var codewordRow /*int*/ = 0; codewordRow < codewords.length; codewordRow++) {\n var codeword = codewords[codewordRow];\n if (codewords[codewordRow] == null) {\n continue;\n }\n var rowIndicatorValue = codeword.getValue() % 30;\n var codewordRowNumber = codeword.getRowNumber();\n if (codewordRowNumber > barcodeMetadata.getRowCount()) {\n codewords[codewordRow] = null;\n continue;\n }\n if (!this._isLeft) {\n codewordRowNumber += 2;\n }\n switch (codewordRowNumber % 3) {\n case 0:\n if (rowIndicatorValue * 3 + 1 !== barcodeMetadata.getRowCountUpperPart()) {\n codewords[codewordRow] = null;\n }\n break;\n case 1:\n if (Math.trunc(rowIndicatorValue / 3) !== barcodeMetadata.getErrorCorrectionLevel() ||\n rowIndicatorValue % 3 !== barcodeMetadata.getRowCountLowerPart()) {\n codewords[codewordRow] = null;\n }\n break;\n case 2:\n if (rowIndicatorValue + 1 !== barcodeMetadata.getColumnCount()) {\n codewords[codewordRow] = null;\n }\n break;\n }\n }\n };\n DetectionResultRowIndicatorColumn.prototype.isLeft = function () {\n return this._isLeft;\n };\n // @Override\n DetectionResultRowIndicatorColumn.prototype.toString = function () {\n return 'IsLeft: ' + this._isLeft + '\\n' + _super.prototype.toString.call(this);\n };\n return DetectionResultRowIndicatorColumn;\n}(DetectionResultColumn));\nexport default DetectionResultRowIndicatorColumn;\n","/*\n* Copyright 2013 ZXing authors\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// package com.google.zxing.pdf417.decoder;\n// import com.google.zxing.common.detector.MathUtils;\nimport MathUtils from '../../common/detector/MathUtils';\n// import com.google.zxing.pdf417.PDF417Common;\nimport PDF417Common from '../PDF417Common';\nimport Float from '../../util/Float';\n/**\n * @author Guenther Grau\n * @author creatale GmbH (christoph.schulz@creatale.de)\n */\nvar PDF417CodewordDecoder = /** @class */ (function () {\n function PDF417CodewordDecoder() {\n }\n /* @note\n * this action have to be performed before first use of class\n * - static constructor\n * working with 32bit float (based from Java logic)\n */\n PDF417CodewordDecoder.initialize = function () {\n // Pre-computes the symbol ratio table.\n for ( /*int*/var i = 0; i < PDF417Common.SYMBOL_TABLE.length; i++) {\n var currentSymbol = PDF417Common.SYMBOL_TABLE[i];\n var currentBit = currentSymbol & 0x1;\n for ( /*int*/var j = 0; j < PDF417Common.BARS_IN_MODULE; j++) {\n var size = 0.0;\n while ((currentSymbol & 0x1) === currentBit) {\n size += 1.0;\n currentSymbol >>= 1;\n }\n currentBit = currentSymbol & 0x1;\n if (!PDF417CodewordDecoder.RATIOS_TABLE[i]) {\n PDF417CodewordDecoder.RATIOS_TABLE[i] = new Array(PDF417Common.BARS_IN_MODULE);\n }\n PDF417CodewordDecoder.RATIOS_TABLE[i][PDF417Common.BARS_IN_MODULE - j - 1] = Math.fround(size / PDF417Common.MODULES_IN_CODEWORD);\n }\n }\n this.bSymbolTableReady = true;\n };\n PDF417CodewordDecoder.getDecodedValue = function (moduleBitCount) {\n var decodedValue = PDF417CodewordDecoder.getDecodedCodewordValue(PDF417CodewordDecoder.sampleBitCounts(moduleBitCount));\n if (decodedValue !== -1) {\n return decodedValue;\n }\n return PDF417CodewordDecoder.getClosestDecodedValue(moduleBitCount);\n };\n PDF417CodewordDecoder.sampleBitCounts = function (moduleBitCount) {\n var bitCountSum = MathUtils.sum(moduleBitCount);\n var result = new Int32Array(PDF417Common.BARS_IN_MODULE);\n var bitCountIndex = 0;\n var sumPreviousBits = 0;\n for ( /*int*/var i = 0; i < PDF417Common.MODULES_IN_CODEWORD; i++) {\n var sampleIndex = bitCountSum / (2 * PDF417Common.MODULES_IN_CODEWORD) +\n (i * bitCountSum) / PDF417Common.MODULES_IN_CODEWORD;\n if (sumPreviousBits + moduleBitCount[bitCountIndex] <= sampleIndex) {\n sumPreviousBits += moduleBitCount[bitCountIndex];\n bitCountIndex++;\n }\n result[bitCountIndex]++;\n }\n return result;\n };\n PDF417CodewordDecoder.getDecodedCodewordValue = function (moduleBitCount) {\n var decodedValue = PDF417CodewordDecoder.getBitValue(moduleBitCount);\n return PDF417Common.getCodeword(decodedValue) === -1 ? -1 : decodedValue;\n };\n PDF417CodewordDecoder.getBitValue = function (moduleBitCount) {\n var result = /*long*/ 0;\n for (var /*int*/ i = 0; i < moduleBitCount.length; i++) {\n for ( /*int*/var bit = 0; bit < moduleBitCount[i]; bit++) {\n result = (result << 1) | (i % 2 === 0 ? 1 : 0);\n }\n }\n return Math.trunc(result);\n };\n // working with 32bit float (as in Java)\n PDF417CodewordDecoder.getClosestDecodedValue = function (moduleBitCount) {\n var bitCountSum = MathUtils.sum(moduleBitCount);\n var bitCountRatios = new Array(PDF417Common.BARS_IN_MODULE);\n if (bitCountSum > 1) {\n for (var /*int*/ i = 0; i < bitCountRatios.length; i++) {\n bitCountRatios[i] = Math.fround(moduleBitCount[i] / bitCountSum);\n }\n }\n var bestMatchError = Float.MAX_VALUE;\n var bestMatch = -1;\n if (!this.bSymbolTableReady) {\n PDF417CodewordDecoder.initialize();\n }\n for ( /*int*/var j = 0; j < PDF417CodewordDecoder.RATIOS_TABLE.length; j++) {\n var error = 0.0;\n var ratioTableRow = PDF417CodewordDecoder.RATIOS_TABLE[j];\n for ( /*int*/var k = 0; k < PDF417Common.BARS_IN_MODULE; k++) {\n var diff = Math.fround(ratioTableRow[k] - bitCountRatios[k]);\n error += Math.fround(diff * diff);\n if (error >= bestMatchError) {\n break;\n }\n }\n if (error < bestMatchError) {\n bestMatchError = error;\n bestMatch = PDF417Common.SYMBOL_TABLE[j];\n }\n }\n return bestMatch;\n };\n // flag that the table is ready for use\n PDF417CodewordDecoder.bSymbolTableReady = false;\n PDF417CodewordDecoder.RATIOS_TABLE = new Array(PDF417Common.SYMBOL_TABLE.length).map(function (x) { return x = new Array(PDF417Common.BARS_IN_MODULE); });\n return PDF417CodewordDecoder;\n}());\nexport default PDF417CodewordDecoder;\n","/*\n* Copyright 2013 ZXing authors\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*/\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n// package com.google.zxing.pdf417.decoder;\n// import com.google.zxing.ChecksumException;\nimport ChecksumException from '../../ChecksumException';\n// import com.google.zxing.FormatException;\nimport FormatException from '../../FormatException';\n// import com.google.zxing.NotFoundException;\nimport NotFoundException from '../../NotFoundException';\n// import com.google.zxing.common.detector.MathUtils;\nimport MathUtils from '../../common/detector/MathUtils';\n// import com.google.zxing.pdf417.PDF417Common;\nimport PDF417Common from '../PDF417Common';\n// import com.google.zxing.pdf417.decoder.ec.ErrorCorrection;\nimport ErrorCorrection from './ec/ErrorCorrection';\n// local\nimport BoundingBox from './BoundingBox';\nimport DetectionResultRowIndicatorColumn from './DetectionResultRowIndicatorColumn';\nimport DetectionResult from './DetectionResult';\nimport DetectionResultColumn from './DetectionResultColumn';\nimport Codeword from './Codeword';\nimport BarcodeValue from './BarcodeValue';\nimport PDF417CodewordDecoder from './PDF417CodewordDecoder';\nimport DecodedBitStreamParser from './DecodedBitStreamParser';\n// utils\nimport Formatter from '../../util/Formatter';\n// import java.util.ArrayList;\n// import java.util.Collection;\n// import java.util.Formatter;\n// import java.util.List;\n/**\n * @author Guenther Grau\n */\nvar PDF417ScanningDecoder = /** @class */ (function () {\n function PDF417ScanningDecoder() {\n }\n /**\n * @TODO don't pass in minCodewordWidth and maxCodewordWidth, pass in barcode columns for start and stop pattern\n *\n * columns. That way width can be deducted from the pattern column.\n * This approach also allows to detect more details about the barcode, e.g. if a bar type (white or black) is wider\n * than it should be. This can happen if the scanner used a bad blackpoint.\n *\n * @param BitMatrix\n * @param image\n * @param ResultPoint\n * @param imageTopLeft\n * @param ResultPoint\n * @param imageBottomLeft\n * @param ResultPoint\n * @param imageTopRight\n * @param ResultPoint\n * @param imageBottomRight\n * @param int\n * @param minCodewordWidth\n * @param int\n * @param maxCodewordWidth\n *\n * @throws NotFoundException\n * @throws FormatException\n * @throws ChecksumException\n */\n PDF417ScanningDecoder.decode = function (image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight, minCodewordWidth, maxCodewordWidth) {\n var boundingBox = new BoundingBox(image, imageTopLeft, imageBottomLeft, imageTopRight, imageBottomRight);\n var leftRowIndicatorColumn = null;\n var rightRowIndicatorColumn = null;\n var detectionResult;\n for (var firstPass /*boolean*/ = true;; firstPass = false) {\n if (imageTopLeft != null) {\n leftRowIndicatorColumn = PDF417ScanningDecoder.getRowIndicatorColumn(image, boundingBox, imageTopLeft, true, minCodewordWidth, maxCodewordWidth);\n }\n if (imageTopRight != null) {\n rightRowIndicatorColumn = PDF417ScanningDecoder.getRowIndicatorColumn(image, boundingBox, imageTopRight, false, minCodewordWidth, maxCodewordWidth);\n }\n detectionResult = PDF417ScanningDecoder.merge(leftRowIndicatorColumn, rightRowIndicatorColumn);\n if (detectionResult == null) {\n throw NotFoundException.getNotFoundInstance();\n }\n var resultBox = detectionResult.getBoundingBox();\n if (firstPass && resultBox != null &&\n (resultBox.getMinY() < boundingBox.getMinY() || resultBox.getMaxY() > boundingBox.getMaxY())) {\n boundingBox = resultBox;\n }\n else {\n break;\n }\n }\n detectionResult.setBoundingBox(boundingBox);\n var maxBarcodeColumn = detectionResult.getBarcodeColumnCount() + 1;\n detectionResult.setDetectionResultColumn(0, leftRowIndicatorColumn);\n detectionResult.setDetectionResultColumn(maxBarcodeColumn, rightRowIndicatorColumn);\n var leftToRight = leftRowIndicatorColumn != null;\n for (var barcodeColumnCount /*int*/ = 1; barcodeColumnCount <= maxBarcodeColumn; barcodeColumnCount++) {\n var barcodeColumn = leftToRight ? barcodeColumnCount : maxBarcodeColumn - barcodeColumnCount;\n if (detectionResult.getDetectionResultColumn(barcodeColumn) !== /* null */ undefined) {\n // This will be the case for the opposite row indicator column, which doesn't need to be decoded again.\n continue;\n }\n var detectionResultColumn = void 0;\n if (barcodeColumn === 0 || barcodeColumn === maxBarcodeColumn) {\n detectionResultColumn = new DetectionResultRowIndicatorColumn(boundingBox, barcodeColumn === 0);\n }\n else {\n detectionResultColumn = new DetectionResultColumn(boundingBox);\n }\n detectionResult.setDetectionResultColumn(barcodeColumn, detectionResultColumn);\n var startColumn = -1;\n var previousStartColumn = startColumn;\n // TODO start at a row for which we know the start position, then detect upwards and downwards from there.\n for (var imageRow /*int*/ = boundingBox.getMinY(); imageRow <= boundingBox.getMaxY(); imageRow++) {\n startColumn = PDF417ScanningDecoder.getStartColumn(detectionResult, barcodeColumn, imageRow, leftToRight);\n if (startColumn < 0 || startColumn > boundingBox.getMaxX()) {\n if (previousStartColumn === -1) {\n continue;\n }\n startColumn = previousStartColumn;\n }\n var codeword = PDF417ScanningDecoder.detectCodeword(image, boundingBox.getMinX(), boundingBox.getMaxX(), leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth);\n if (codeword != null) {\n detectionResultColumn.setCodeword(imageRow, codeword);\n previousStartColumn = startColumn;\n minCodewordWidth = Math.min(minCodewordWidth, codeword.getWidth());\n maxCodewordWidth = Math.max(maxCodewordWidth, codeword.getWidth());\n }\n }\n }\n return PDF417ScanningDecoder.createDecoderResult(detectionResult);\n };\n /**\n *\n * @param leftRowIndicatorColumn\n * @param rightRowIndicatorColumn\n *\n * @throws NotFoundException\n */\n PDF417ScanningDecoder.merge = function (leftRowIndicatorColumn, rightRowIndicatorColumn) {\n if (leftRowIndicatorColumn == null && rightRowIndicatorColumn == null) {\n return null;\n }\n var barcodeMetadata = PDF417ScanningDecoder.getBarcodeMetadata(leftRowIndicatorColumn, rightRowIndicatorColumn);\n if (barcodeMetadata == null) {\n return null;\n }\n var boundingBox = BoundingBox.merge(PDF417ScanningDecoder.adjustBoundingBox(leftRowIndicatorColumn), PDF417ScanningDecoder.adjustBoundingBox(rightRowIndicatorColumn));\n return new DetectionResult(barcodeMetadata, boundingBox);\n };\n /**\n *\n * @param rowIndicatorColumn\n *\n * @throws NotFoundException\n */\n PDF417ScanningDecoder.adjustBoundingBox = function (rowIndicatorColumn) {\n var e_1, _a;\n if (rowIndicatorColumn == null) {\n return null;\n }\n var rowHeights = rowIndicatorColumn.getRowHeights();\n if (rowHeights == null) {\n return null;\n }\n var maxRowHeight = PDF417ScanningDecoder.getMax(rowHeights);\n var missingStartRows = 0;\n try {\n for (var rowHeights_1 = __values(rowHeights), rowHeights_1_1 = rowHeights_1.next(); !rowHeights_1_1.done; rowHeights_1_1 = rowHeights_1.next()) {\n var rowHeight = rowHeights_1_1.value /*int*/;\n missingStartRows += maxRowHeight - rowHeight;\n if (rowHeight > 0) {\n break;\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (rowHeights_1_1 && !rowHeights_1_1.done && (_a = rowHeights_1.return)) _a.call(rowHeights_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n var codewords = rowIndicatorColumn.getCodewords();\n for (var row /*int*/ = 0; missingStartRows > 0 && codewords[row] == null; row++) {\n missingStartRows--;\n }\n var missingEndRows = 0;\n for (var row /*int*/ = rowHeights.length - 1; row >= 0; row--) {\n missingEndRows += maxRowHeight - rowHeights[row];\n if (rowHeights[row] > 0) {\n break;\n }\n }\n for (var row /*int*/ = codewords.length - 1; missingEndRows > 0 && codewords[row] == null; row--) {\n missingEndRows--;\n }\n return rowIndicatorColumn.getBoundingBox().addMissingRows(missingStartRows, missingEndRows, rowIndicatorColumn.isLeft());\n };\n PDF417ScanningDecoder.getMax = function (values) {\n var e_2, _a;\n var maxValue = -1;\n try {\n for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {\n var value = values_1_1.value /*int*/;\n maxValue = Math.max(maxValue, value);\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);\n }\n finally { if (e_2) throw e_2.error; }\n }\n return maxValue;\n };\n PDF417ScanningDecoder.getBarcodeMetadata = function (leftRowIndicatorColumn, rightRowIndicatorColumn) {\n var leftBarcodeMetadata;\n if (leftRowIndicatorColumn == null ||\n (leftBarcodeMetadata = leftRowIndicatorColumn.getBarcodeMetadata()) == null) {\n return rightRowIndicatorColumn == null ? null : rightRowIndicatorColumn.getBarcodeMetadata();\n }\n var rightBarcodeMetadata;\n if (rightRowIndicatorColumn == null ||\n (rightBarcodeMetadata = rightRowIndicatorColumn.getBarcodeMetadata()) == null) {\n return leftBarcodeMetadata;\n }\n if (leftBarcodeMetadata.getColumnCount() !== rightBarcodeMetadata.getColumnCount() &&\n leftBarcodeMetadata.getErrorCorrectionLevel() !== rightBarcodeMetadata.getErrorCorrectionLevel() &&\n leftBarcodeMetadata.getRowCount() !== rightBarcodeMetadata.getRowCount()) {\n return null;\n }\n return leftBarcodeMetadata;\n };\n PDF417ScanningDecoder.getRowIndicatorColumn = function (image, boundingBox, startPoint, leftToRight, minCodewordWidth, maxCodewordWidth) {\n var rowIndicatorColumn = new DetectionResultRowIndicatorColumn(boundingBox, leftToRight);\n for (var i /*int*/ = 0; i < 2; i++) {\n var increment = i === 0 ? 1 : -1;\n var startColumn = Math.trunc(Math.trunc(startPoint.getX()));\n for (var imageRow /*int*/ = Math.trunc(Math.trunc(startPoint.getY())); imageRow <= boundingBox.getMaxY() &&\n imageRow >= boundingBox.getMinY(); imageRow += increment) {\n var codeword = PDF417ScanningDecoder.detectCodeword(image, 0, image.getWidth(), leftToRight, startColumn, imageRow, minCodewordWidth, maxCodewordWidth);\n if (codeword != null) {\n rowIndicatorColumn.setCodeword(imageRow, codeword);\n if (leftToRight) {\n startColumn = codeword.getStartX();\n }\n else {\n startColumn = codeword.getEndX();\n }\n }\n }\n }\n return rowIndicatorColumn;\n };\n /**\n *\n * @param detectionResult\n * @param BarcodeValue\n * @param param2\n * @param param3\n * @param barcodeMatrix\n *\n * @throws NotFoundException\n */\n PDF417ScanningDecoder.adjustCodewordCount = function (detectionResult, barcodeMatrix) {\n var barcodeMatrix01 = barcodeMatrix[0][1];\n var numberOfCodewords = barcodeMatrix01.getValue();\n var calculatedNumberOfCodewords = detectionResult.getBarcodeColumnCount() *\n detectionResult.getBarcodeRowCount() -\n PDF417ScanningDecoder.getNumberOfECCodeWords(detectionResult.getBarcodeECLevel());\n if (numberOfCodewords.length === 0) {\n if (calculatedNumberOfCodewords < 1 || calculatedNumberOfCodewords > PDF417Common.MAX_CODEWORDS_IN_BARCODE) {\n throw NotFoundException.getNotFoundInstance();\n }\n barcodeMatrix01.setValue(calculatedNumberOfCodewords);\n }\n else if (numberOfCodewords[0] !== calculatedNumberOfCodewords) {\n // The calculated one is more reliable as it is derived from the row indicator columns\n barcodeMatrix01.setValue(calculatedNumberOfCodewords);\n }\n };\n /**\n *\n * @param detectionResult\n *\n * @throws FormatException\n * @throws ChecksumException\n * @throws NotFoundException\n */\n PDF417ScanningDecoder.createDecoderResult = function (detectionResult) {\n var barcodeMatrix = PDF417ScanningDecoder.createBarcodeMatrix(detectionResult);\n PDF417ScanningDecoder.adjustCodewordCount(detectionResult, barcodeMatrix);\n var erasures /*CollectionGiven data and error-correction codewords received, possibly corrupted by errors, attempts to\n * correct the errors in-place.
\n *\n * @param codewords data and error correction codewords\n * @param erasures positions of any known erasures\n * @param numECCodewords number of error correction codewords that are available in codewords\n * @throws ChecksumException if error correction fails\n */\n PDF417ScanningDecoder.correctErrors = function (codewords, erasures, numECCodewords) {\n if (erasures != null &&\n erasures.length > numECCodewords / 2 + PDF417ScanningDecoder.MAX_ERRORS ||\n numECCodewords < 0 ||\n numECCodewords > PDF417ScanningDecoder.MAX_EC_CODEWORDS) {\n // Too many errors or EC Codewords is corrupted\n throw ChecksumException.getChecksumInstance();\n }\n return PDF417ScanningDecoder.errorCorrection.decode(codewords, numECCodewords, erasures);\n };\n /**\n * Verify that all is OK with the codeword array.\n * @throws FormatException\n */\n PDF417ScanningDecoder.verifyCodewordCount = function (codewords, numECCodewords) {\n if (codewords.length < 4) {\n // Codeword array size should be at least 4 allowing for\n // Count CW, At least one Data CW, Error Correction CW, Error Correction CW\n throw FormatException.getFormatInstance();\n }\n // The first codeword, the Symbol Length Descriptor, shall always encode the total number of data\n // codewords in the symbol, including the Symbol Length Descriptor itself, data codewords and pad\n // codewords, but excluding the number of error correction codewords.\n var numberOfCodewords = codewords[0];\n if (numberOfCodewords > codewords.length) {\n throw FormatException.getFormatInstance();\n }\n if (numberOfCodewords === 0) {\n // Reset to the length of the array - 8 (Allow for at least level 3 Error Correction (8 Error Codewords)\n if (numECCodewords < codewords.length) {\n codewords[0] = codewords.length - numECCodewords;\n }\n else {\n throw FormatException.getFormatInstance();\n }\n }\n };\n PDF417ScanningDecoder.getBitCountForCodeword = function (codeword) {\n var result = new Int32Array(8);\n var previousValue = 0;\n var i = result.length - 1;\n while (true) {\n if ((codeword & 0x1) !== previousValue) {\n previousValue = codeword & 0x1;\n i--;\n if (i < 0) {\n break;\n }\n }\n result[i]++;\n codeword >>= 1;\n }\n return result;\n };\n PDF417ScanningDecoder.getCodewordBucketNumber = function (codeword) {\n if (codeword instanceof Int32Array) {\n return this.getCodewordBucketNumber_Int32Array(codeword);\n }\n return this.getCodewordBucketNumber_number(codeword);\n };\n PDF417ScanningDecoder.getCodewordBucketNumber_number = function (codeword) {\n return PDF417ScanningDecoder.getCodewordBucketNumber(PDF417ScanningDecoder.getBitCountForCodeword(codeword));\n };\n PDF417ScanningDecoder.getCodewordBucketNumber_Int32Array = function (moduleBitCount) {\n return (moduleBitCount[0] - moduleBitCount[2] + moduleBitCount[4] - moduleBitCount[6] + 9) % 9;\n };\n PDF417ScanningDecoder.toString = function (barcodeMatrix) {\n var formatter = new Formatter();\n // try (let formatter = new Formatter()) {\n for (var row /*int*/ = 0; row < barcodeMatrix.length; row++) {\n formatter.format('Row %2d: ', row);\n for (var column /*int*/ = 0; column < barcodeMatrix[row].length; column++) {\n var barcodeValue = barcodeMatrix[row][column];\n if (barcodeValue.getValue().length === 0) {\n formatter.format(' ', null);\n }\n else {\n formatter.format('%4d(%2d)', barcodeValue.getValue()[0], barcodeValue.getConfidence(barcodeValue.getValue()[0]));\n }\n }\n formatter.format('%n');\n }\n return formatter.toString();\n // }\n };\n /*final*/ PDF417ScanningDecoder.CODEWORD_SKEW_SIZE = 2;\n /*final*/ PDF417ScanningDecoder.MAX_ERRORS = 3;\n /*final*/ PDF417ScanningDecoder.MAX_EC_CODEWORDS = 512;\n /*final*/ PDF417ScanningDecoder.errorCorrection = new ErrorCorrection();\n return PDF417ScanningDecoder;\n}());\nexport default PDF417ScanningDecoder;\n","/*\n* Copyright 2012 ZXing authors\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*/\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n// package com.google.zxing.pdf417.decoder.ec;\n// import com.google.zxing.ChecksumException;\nimport ChecksumException from '../../../ChecksumException';\nimport ModulusPoly from './ModulusPoly';\nimport ModulusGF from './ModulusGF';\n/**\n *PDF417 error correction implementation.
\n *\n *This example\n * is quite useful in understanding the algorithm.
\n *\n * @author Sean Owen\n * @see com.google.zxing.common.reedsolomon.ReedSolomonDecoder\n */\nvar ErrorCorrection = /** @class */ (function () {\n function ErrorCorrection() {\n this.field = ModulusGF.PDF417_GF;\n }\n /**\n * @param received received codewords\n * @param numECCodewords number of those codewords used for EC\n * @param erasures location of erasures\n * @return number of errors\n * @throws ChecksumException if errors cannot be corrected, maybe because of too many errors\n */\n ErrorCorrection.prototype.decode = function (received, numECCodewords, erasures) {\n var e_1, _a;\n var poly = new ModulusPoly(this.field, received);\n var S = new Int32Array(numECCodewords);\n var error = false;\n for (var i /*int*/ = numECCodewords; i > 0; i--) {\n var evaluation = poly.evaluateAt(this.field.exp(i));\n S[numECCodewords - i] = evaluation;\n if (evaluation !== 0) {\n error = true;\n }\n }\n if (!error) {\n return 0;\n }\n var knownErrors = this.field.getOne();\n if (erasures != null) {\n try {\n for (var erasures_1 = __values(erasures), erasures_1_1 = erasures_1.next(); !erasures_1_1.done; erasures_1_1 = erasures_1.next()) {\n var erasure = erasures_1_1.value;\n var b = this.field.exp(received.length - 1 - erasure);\n // Add (1 - bx) term:\n var term = new ModulusPoly(this.field, new Int32Array([this.field.subtract(0, b), 1]));\n knownErrors = knownErrors.multiply(term);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (erasures_1_1 && !erasures_1_1.done && (_a = erasures_1.return)) _a.call(erasures_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n }\n var syndrome = new ModulusPoly(this.field, S);\n // syndrome = syndrome.multiply(knownErrors);\n var sigmaOmega = this.runEuclideanAlgorithm(this.field.buildMonomial(numECCodewords, 1), syndrome, numECCodewords);\n var sigma = sigmaOmega[0];\n var omega = sigmaOmega[1];\n // sigma = sigma.multiply(knownErrors);\n var errorLocations = this.findErrorLocations(sigma);\n var errorMagnitudes = this.findErrorMagnitudes(omega, sigma, errorLocations);\n for (var i /*int*/ = 0; i < errorLocations.length; i++) {\n var position = received.length - 1 - this.field.log(errorLocations[i]);\n if (position < 0) {\n throw ChecksumException.getChecksumInstance();\n }\n received[position] = this.field.subtract(received[position], errorMagnitudes[i]);\n }\n return errorLocations.length;\n };\n /**\n *\n * @param ModulusPoly\n * @param a\n * @param ModulusPoly\n * @param b\n * @param int\n * @param R\n * @throws ChecksumException\n */\n ErrorCorrection.prototype.runEuclideanAlgorithm = function (a, b, R) {\n // Assume a's degree is >= b's\n if (a.getDegree() < b.getDegree()) {\n var temp = a;\n a = b;\n b = temp;\n }\n var rLast = a;\n var r = b;\n var tLast = this.field.getZero();\n var t = this.field.getOne();\n // Run Euclidean algorithm until r's degree is less than R/2\n while (r.getDegree() >= Math.round(R / 2)) {\n var rLastLast = rLast;\n var tLastLast = tLast;\n rLast = r;\n tLast = t;\n // Divide rLastLast by rLast, with quotient in q and remainder in r\n if (rLast.isZero()) {\n // Oops, Euclidean algorithm already terminated?\n throw ChecksumException.getChecksumInstance();\n }\n r = rLastLast;\n var q = this.field.getZero();\n var denominatorLeadingTerm = rLast.getCoefficient(rLast.getDegree());\n var dltInverse = this.field.inverse(denominatorLeadingTerm);\n while (r.getDegree() >= rLast.getDegree() && !r.isZero()) {\n var degreeDiff = r.getDegree() - rLast.getDegree();\n var scale = this.field.multiply(r.getCoefficient(r.getDegree()), dltInverse);\n q = q.add(this.field.buildMonomial(degreeDiff, scale));\n r = r.subtract(rLast.multiplyByMonomial(degreeDiff, scale));\n }\n t = q.multiply(tLast).subtract(tLastLast).negative();\n }\n var sigmaTildeAtZero = t.getCoefficient(0);\n if (sigmaTildeAtZero === 0) {\n throw ChecksumException.getChecksumInstance();\n }\n var inverse = this.field.inverse(sigmaTildeAtZero);\n var sigma = t.multiply(inverse);\n var omega = r.multiply(inverse);\n return [sigma, omega];\n };\n /**\n *\n * @param errorLocator\n * @throws ChecksumException\n */\n ErrorCorrection.prototype.findErrorLocations = function (errorLocator) {\n // This is a direct application of Chien's search\n var numErrors = errorLocator.getDegree();\n var result = new Int32Array(numErrors);\n var e = 0;\n for (var i /*int*/ = 1; i < this.field.getSize() && e < numErrors; i++) {\n if (errorLocator.evaluateAt(i) === 0) {\n result[e] = this.field.inverse(i);\n e++;\n }\n }\n if (e !== numErrors) {\n throw ChecksumException.getChecksumInstance();\n }\n return result;\n };\n ErrorCorrection.prototype.findErrorMagnitudes = function (errorEvaluator, errorLocator, errorLocations) {\n var errorLocatorDegree = errorLocator.getDegree();\n var formalDerivativeCoefficients = new Int32Array(errorLocatorDegree);\n for (var i /*int*/ = 1; i <= errorLocatorDegree; i++) {\n formalDerivativeCoefficients[errorLocatorDegree - i] =\n this.field.multiply(i, errorLocator.getCoefficient(i));\n }\n var formalDerivative = new ModulusPoly(this.field, formalDerivativeCoefficients);\n // This is directly applying Forney's Formula\n var s = errorLocations.length;\n var result = new Int32Array(s);\n for (var i /*int*/ = 0; i < s; i++) {\n var xiInverse = this.field.inverse(errorLocations[i]);\n var numerator = this.field.subtract(0, errorEvaluator.evaluateAt(xiInverse));\n var denominator = this.field.inverse(formalDerivative.evaluateAt(xiInverse));\n result[i] = this.field.multiply(numerator, denominator);\n }\n return result;\n };\n return ErrorCorrection;\n}());\nexport default ErrorCorrection;\n","import IllegalArgumentException from '../../../IllegalArgumentException';\nimport ArithmeticException from '../../../ArithmeticException';\nvar ModulusBase = /** @class */ (function () {\n function ModulusBase() {\n }\n ModulusBase.prototype.add = function (a, b) {\n return (a + b) % this.modulus;\n };\n ModulusBase.prototype.subtract = function (a, b) {\n return (this.modulus + a - b) % this.modulus;\n };\n ModulusBase.prototype.exp = function (a) {\n return this.expTable[a];\n };\n ModulusBase.prototype.log = function (a) {\n if (a === 0) {\n throw new IllegalArgumentException();\n }\n return this.logTable[a];\n };\n ModulusBase.prototype.inverse = function (a) {\n if (a === 0) {\n throw new ArithmeticException();\n }\n return this.expTable[this.modulus - this.logTable[a] - 1];\n };\n ModulusBase.prototype.multiply = function (a, b) {\n if (a === 0 || b === 0) {\n return 0;\n }\n return this.expTable[(this.logTable[a] + this.logTable[b]) % (this.modulus - 1)];\n };\n ModulusBase.prototype.getSize = function () {\n return this.modulus;\n };\n ModulusBase.prototype.equals = function (o) {\n return o === this;\n };\n return ModulusBase;\n}());\nexport default ModulusBase;\n","/*\n * Copyright 2012 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n// package com.google.zxing.pdf417.decoder.ec;\n// import com.google.zxing.pdf417.PDF417Common;\nimport PDF417Common from '../../PDF417Common';\nimport ModulusPoly from './ModulusPoly';\nimport IllegalArgumentException from '../../../IllegalArgumentException';\nimport ModulusBase from './ModulusBase';\n/**\n *A field based on powers of a generator integer, modulo some modulus.
\n *\n * @author Sean Owen\n * @see com.google.zxing.common.reedsolomon.GenericGF\n */\nvar ModulusGF = /** @class */ (function (_super) {\n __extends(ModulusGF, _super);\n // private /*final*/ modulus: /*int*/ number;\n function ModulusGF(modulus, generator) {\n var _this = _super.call(this) || this;\n _this.modulus = modulus;\n _this.expTable = new Int32Array(modulus);\n _this.logTable = new Int32Array(modulus);\n var x = /*int*/ 1;\n for (var i /*int*/ = 0; i < modulus; i++) {\n _this.expTable[i] = x;\n x = (x * generator) % modulus;\n }\n for (var i /*int*/ = 0; i < modulus - 1; i++) {\n _this.logTable[_this.expTable[i]] = i;\n }\n // logTable[0] == 0 but this should never be used\n _this.zero = new ModulusPoly(_this, new Int32Array([0]));\n _this.one = new ModulusPoly(_this, new Int32Array([1]));\n return _this;\n }\n ModulusGF.prototype.getZero = function () {\n return this.zero;\n };\n ModulusGF.prototype.getOne = function () {\n return this.one;\n };\n ModulusGF.prototype.buildMonomial = function (degree, coefficient) {\n if (degree < 0) {\n throw new IllegalArgumentException();\n }\n if (coefficient === 0) {\n return this.zero;\n }\n var coefficients = new Int32Array(degree + 1);\n coefficients[0] = coefficient;\n return new ModulusPoly(this, coefficients);\n };\n ModulusGF.PDF417_GF = new ModulusGF(PDF417Common.NUMBER_OF_CODEWORDS, 3);\n return ModulusGF;\n}(ModulusBase));\nexport default ModulusGF;\n","/*\n* Copyright 2012 ZXing authors\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*/\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n// package com.google.zxing.pdf417.decoder.ec;\nimport IllegalArgumentException from '../../../IllegalArgumentException';\nimport System from '../../../util/System';\nimport StringBuilder from '../../../util/StringBuilder';\n/**\n * @author Sean Owen\n * @see com.google.zxing.common.reedsolomon.GenericGFPoly\n */\nvar ModulusPoly = /** @class */ (function () {\n function ModulusPoly(field, coefficients) {\n if (coefficients.length === 0) {\n throw new IllegalArgumentException();\n }\n this.field = field;\n var coefficientsLength = /*int*/ coefficients.length;\n if (coefficientsLength > 1 && coefficients[0] === 0) {\n // Leading term must be non-zero for anything except the constant polynomial \"0\"\n var firstNonZero = /*int*/ 1;\n while (firstNonZero < coefficientsLength && coefficients[firstNonZero] === 0) {\n firstNonZero++;\n }\n if (firstNonZero === coefficientsLength) {\n this.coefficients = new Int32Array([0]);\n }\n else {\n this.coefficients = new Int32Array(coefficientsLength - firstNonZero);\n System.arraycopy(coefficients, firstNonZero, this.coefficients, 0, this.coefficients.length);\n }\n }\n else {\n this.coefficients = coefficients;\n }\n }\n ModulusPoly.prototype.getCoefficients = function () {\n return this.coefficients;\n };\n /**\n * @return degree of this polynomial\n */\n ModulusPoly.prototype.getDegree = function () {\n return this.coefficients.length - 1;\n };\n /**\n * @return true iff this polynomial is the monomial \"0\"\n */\n ModulusPoly.prototype.isZero = function () {\n return this.coefficients[0] === 0;\n };\n /**\n * @return coefficient of x^degree term in this polynomial\n */\n ModulusPoly.prototype.getCoefficient = function (degree) {\n return this.coefficients[this.coefficients.length - 1 - degree];\n };\n /**\n * @return evaluation of this polynomial at a given point\n */\n ModulusPoly.prototype.evaluateAt = function (a) {\n var e_1, _a;\n if (a === 0) {\n // Just return the x^0 coefficient\n return this.getCoefficient(0);\n }\n if (a === 1) {\n // Just the sum of the coefficients\n var sum = /*int*/ 0;\n try {\n for (var _b = __values(this.coefficients), _c = _b.next(); !_c.done; _c = _b.next()) {\n var coefficient = _c.value /*int*/;\n sum = this.field.add(sum, coefficient);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return sum;\n }\n var result = /*int*/ this.coefficients[0];\n var size = /*int*/ this.coefficients.length;\n for (var i /*int*/ = 1; i < size; i++) {\n result = this.field.add(this.field.multiply(a, result), this.coefficients[i]);\n }\n return result;\n };\n ModulusPoly.prototype.add = function (other) {\n if (!this.field.equals(other.field)) {\n throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');\n }\n if (this.isZero()) {\n return other;\n }\n if (other.isZero()) {\n return this;\n }\n var smallerCoefficients = this.coefficients;\n var largerCoefficients = other.coefficients;\n if (smallerCoefficients.length > largerCoefficients.length) {\n var temp = smallerCoefficients;\n smallerCoefficients = largerCoefficients;\n largerCoefficients = temp;\n }\n var sumDiff = new Int32Array(largerCoefficients.length);\n var lengthDiff = /*int*/ largerCoefficients.length - smallerCoefficients.length;\n // Copy high-order terms only found in higher-degree polynomial's coefficients\n System.arraycopy(largerCoefficients, 0, sumDiff, 0, lengthDiff);\n for (var i /*int*/ = lengthDiff; i < largerCoefficients.length; i++) {\n sumDiff[i] = this.field.add(smallerCoefficients[i - lengthDiff], largerCoefficients[i]);\n }\n return new ModulusPoly(this.field, sumDiff);\n };\n ModulusPoly.prototype.subtract = function (other) {\n if (!this.field.equals(other.field)) {\n throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');\n }\n if (other.isZero()) {\n return this;\n }\n return this.add(other.negative());\n };\n ModulusPoly.prototype.multiply = function (other) {\n if (other instanceof ModulusPoly) {\n return this.multiplyOther(other);\n }\n return this.multiplyScalar(other);\n };\n ModulusPoly.prototype.multiplyOther = function (other) {\n if (!this.field.equals(other.field)) {\n throw new IllegalArgumentException('ModulusPolys do not have same ModulusGF field');\n }\n if (this.isZero() || other.isZero()) {\n // return this.field.getZero();\n return new ModulusPoly(this.field, new Int32Array([0]));\n }\n var aCoefficients = this.coefficients;\n var aLength = /*int*/ aCoefficients.length;\n var bCoefficients = other.coefficients;\n var bLength = /*int*/ bCoefficients.length;\n var product = new Int32Array(aLength + bLength - 1);\n for (var i /*int*/ = 0; i < aLength; i++) {\n var aCoeff = /*int*/ aCoefficients[i];\n for (var j /*int*/ = 0; j < bLength; j++) {\n product[i + j] = this.field.add(product[i + j], this.field.multiply(aCoeff, bCoefficients[j]));\n }\n }\n return new ModulusPoly(this.field, product);\n };\n ModulusPoly.prototype.negative = function () {\n var size = /*int*/ this.coefficients.length;\n var negativeCoefficients = new Int32Array(size);\n for (var i /*int*/ = 0; i < size; i++) {\n negativeCoefficients[i] = this.field.subtract(0, this.coefficients[i]);\n }\n return new ModulusPoly(this.field, negativeCoefficients);\n };\n ModulusPoly.prototype.multiplyScalar = function (scalar) {\n if (scalar === 0) {\n return new ModulusPoly(this.field, new Int32Array([0]));\n }\n if (scalar === 1) {\n return this;\n }\n var size = /*int*/ this.coefficients.length;\n var product = new Int32Array(size);\n for (var i /*int*/ = 0; i < size; i++) {\n product[i] = this.field.multiply(this.coefficients[i], scalar);\n }\n return new ModulusPoly(this.field, product);\n };\n ModulusPoly.prototype.multiplyByMonomial = function (degree, coefficient) {\n if (degree < 0) {\n throw new IllegalArgumentException();\n }\n if (coefficient === 0) {\n return new ModulusPoly(this.field, new Int32Array([0]));\n }\n var size = /*int*/ this.coefficients.length;\n var product = new Int32Array(size + degree);\n for (var i /*int*/ = 0; i < size; i++) {\n product[i] = this.field.multiply(this.coefficients[i], coefficient);\n }\n return new ModulusPoly(this.field, product);\n };\n /*\n ModulusPoly[] divide(other: ModulusPoly) {\n if (!field.equals(other.field)) {\n throw new IllegalArgumentException(\"ModulusPolys do not have same ModulusGF field\");\n }\n if (other.isZero()) {\n throw new IllegalArgumentException(\"Divide by 0\");\n }\n \n let quotient: ModulusPoly = field.getZero();\n let remainder: ModulusPoly = this;\n \n let denominatorLeadingTerm: /*int/ number = other.getCoefficient(other.getDegree());\n let inverseDenominatorLeadingTerm: /*int/ number = field.inverse(denominatorLeadingTerm);\n \n while (remainder.getDegree() >= other.getDegree() && !remainder.isZero()) {\n let degreeDifference: /*int/ number = remainder.getDegree() - other.getDegree();\n let scale: /*int/ number = field.multiply(remainder.getCoefficient(remainder.getDegree()), inverseDenominatorLeadingTerm);\n let term: ModulusPoly = other.multiplyByMonomial(degreeDifference, scale);\n let iterationQuotient: ModulusPoly = field.buildMonomial(degreeDifference, scale);\n quotient = quotient.add(iterationQuotient);\n remainder = remainder.subtract(term);\n }\n \n return new ModulusPoly[] { quotient, remainder };\n }\n */\n // @Override\n ModulusPoly.prototype.toString = function () {\n var result = new StringBuilder( /*8 * this.getDegree()*/); // dynamic string size in JS\n for (var degree /*int*/ = this.getDegree(); degree >= 0; degree--) {\n var coefficient = /*int*/ this.getCoefficient(degree);\n if (coefficient !== 0) {\n if (coefficient < 0) {\n result.append(' - ');\n coefficient = -coefficient;\n }\n else {\n if (result.length() > 0) {\n result.append(' + ');\n }\n }\n if (degree === 0 || coefficient !== 1) {\n result.append(coefficient);\n }\n if (degree !== 0) {\n if (degree === 1) {\n result.append('x');\n }\n else {\n result.append('x^');\n result.append(degree);\n }\n }\n }\n }\n return result.toString();\n };\n return ModulusPoly;\n}());\nexport default ModulusPoly;\n","/*\n* Copyright 2009 ZXing authors\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*/\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n// import com.google.zxing.NotFoundException;\n// import com.google.zxing.ResultPoint;\nimport ResultPoint from '../../ResultPoint';\nimport System from '../../util/System';\nimport Arrays from '../../util/Arrays';\nimport PDF417DetectorResult from './PDF417DetectorResult';\n// import java.util.ArrayList;\n// import java.util.Arrays;\n// import java.util.List;\n// import java.util.Map;\n/**\n *Encapsulates logic that can detect a PDF417 Code in an image, even if the\n * PDF417 Code is rotated or skewed, or partially obscured.
\n *\n * @author SITA Lab (kevin.osullivan@sita.aero)\n * @author dswitkin@google.com (Daniel Switkin)\n * @author Guenther Grau\n */\nvar Detector = /** @class */ (function () {\n function Detector() {\n }\n /**\n *Detects a PDF417 Code in an image. Only checks 0 and 180 degree rotations.
\n *\n * @param image barcode image to decode\n * @param hints optional hints to detector\n * @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will\n * be found and returned\n * @return {@link PDF417DetectorResult} encapsulating results of detecting a PDF417 code\n * @throws NotFoundException if no PDF417 Code can be found\n */\n Detector.detectMultiple = function (image, hints, multiple) {\n // TODO detection improvement, tryHarder could try several different luminance thresholds/blackpoints or even\n // different binarizers\n // boolean tryHarder = hints != null && hints.containsKey(DecodeHintType.TRY_HARDER);\n var bitMatrix = image.getBlackMatrix();\n var barcodeCoordinates = Detector.detect(multiple, bitMatrix);\n if (!barcodeCoordinates.length) {\n bitMatrix = bitMatrix.clone();\n bitMatrix.rotate180();\n barcodeCoordinates = Detector.detect(multiple, bitMatrix);\n }\n return new PDF417DetectorResult(bitMatrix, barcodeCoordinates);\n };\n /**\n * Detects PDF417 codes in an image. Only checks 0 degree rotation\n * @param multiple if true, then the image is searched for multiple codes. If false, then at most one code will\n * be found and returned\n * @param bitMatrix bit matrix to detect barcodes in\n * @return List of ResultPoint arrays containing the coordinates of found barcodes\n */\n Detector.detect = function (multiple, bitMatrix) {\n var e_1, _a;\n var barcodeCoordinates = new Array();\n var row = 0;\n var column = 0;\n var foundBarcodeInRow = false;\n while (row < bitMatrix.getHeight()) {\n var vertices = Detector.findVertices(bitMatrix, row, column);\n if (vertices[0] == null && vertices[3] == null) {\n if (!foundBarcodeInRow) {\n // we didn't find any barcode so that's the end of searching\n break;\n }\n // we didn't find a barcode starting at the given column and row. Try again from the first column and slightly\n // below the lowest barcode we found so far.\n foundBarcodeInRow = false;\n column = 0;\n try {\n for (var barcodeCoordinates_1 = (e_1 = void 0, __values(barcodeCoordinates)), barcodeCoordinates_1_1 = barcodeCoordinates_1.next(); !barcodeCoordinates_1_1.done; barcodeCoordinates_1_1 = barcodeCoordinates_1.next()) {\n var barcodeCoordinate = barcodeCoordinates_1_1.value;\n if (barcodeCoordinate[1] != null) {\n row = Math.trunc(Math.max(row, barcodeCoordinate[1].getY()));\n }\n if (barcodeCoordinate[3] != null) {\n row = Math.max(row, Math.trunc(barcodeCoordinate[3].getY()));\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (barcodeCoordinates_1_1 && !barcodeCoordinates_1_1.done && (_a = barcodeCoordinates_1.return)) _a.call(barcodeCoordinates_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n row += Detector.ROW_STEP;\n continue;\n }\n foundBarcodeInRow = true;\n barcodeCoordinates.push(vertices);\n if (!multiple) {\n break;\n }\n // if we didn't find a right row indicator column, then continue the search for the next barcode after the\n // start pattern of the barcode just found.\n if (vertices[2] != null) {\n column = Math.trunc(vertices[2].getX());\n row = Math.trunc(vertices[2].getY());\n }\n else {\n column = Math.trunc(vertices[4].getX());\n row = Math.trunc(vertices[4].getY());\n }\n }\n return barcodeCoordinates;\n };\n /**\n * Locate the vertices and the codewords area of a black blob using the Start\n * and Stop patterns as locators.\n *\n * @param matrix the scanned barcode image.\n * @return an array containing the vertices:\n * vertices[0] x, y top left barcode\n * vertices[1] x, y bottom left barcode\n * vertices[2] x, y top right barcode\n * vertices[3] x, y bottom right barcode\n * vertices[4] x, y top left codeword area\n * vertices[5] x, y bottom left codeword area\n * vertices[6] x, y top right codeword area\n * vertices[7] x, y bottom right codeword area\n */\n Detector.findVertices = function (matrix, startRow, startColumn) {\n var height = matrix.getHeight();\n var width = matrix.getWidth();\n // const result = new ResultPoint[8];\n var result = new Array(8);\n Detector.copyToResult(result, Detector.findRowsWithPattern(matrix, height, width, startRow, startColumn, Detector.START_PATTERN), Detector.INDEXES_START_PATTERN);\n if (result[4] != null) {\n startColumn = Math.trunc(result[4].getX());\n startRow = Math.trunc(result[4].getY());\n }\n Detector.copyToResult(result, Detector.findRowsWithPattern(matrix, height, width, startRow, startColumn, Detector.STOP_PATTERN), Detector.INDEXES_STOP_PATTERN);\n return result;\n };\n Detector.copyToResult = function (result, tmpResult, destinationIndexes) {\n for (var i = 0; i < destinationIndexes.length; i++) {\n result[destinationIndexes[i]] = tmpResult[i];\n }\n };\n Detector.findRowsWithPattern = function (matrix, height, width, startRow, startColumn, pattern) {\n // const result = new ResultPoint[4];\n var result = new Array(4);\n var found = false;\n var counters = new Int32Array(pattern.length);\n for (; startRow < height; startRow += Detector.ROW_STEP) {\n var loc = Detector.findGuardPattern(matrix, startColumn, startRow, width, false, pattern, counters);\n if (loc != null) {\n while (startRow > 0) {\n var previousRowLoc = Detector.findGuardPattern(matrix, startColumn, --startRow, width, false, pattern, counters);\n if (previousRowLoc != null) {\n loc = previousRowLoc;\n }\n else {\n startRow++;\n break;\n }\n }\n result[0] = new ResultPoint(loc[0], startRow);\n result[1] = new ResultPoint(loc[1], startRow);\n found = true;\n break;\n }\n }\n var stopRow = startRow + 1;\n // Last row of the current symbol that contains pattern\n if (found) {\n var skippedRowCount = 0;\n var previousRowLoc = Int32Array.from([Math.trunc(result[0].getX()), Math.trunc(result[1].getX())]);\n for (; stopRow < height; stopRow++) {\n var loc = Detector.findGuardPattern(matrix, previousRowLoc[0], stopRow, width, false, pattern, counters);\n // a found pattern is only considered to belong to the same barcode if the start and end positions\n // don't differ too much. Pattern drift should be not bigger than two for consecutive rows. With\n // a higher number of skipped rows drift could be larger. To keep it simple for now, we allow a slightly\n // larger drift and don't check for skipped rows.\n if (loc != null &&\n Math.abs(previousRowLoc[0] - loc[0]) < Detector.MAX_PATTERN_DRIFT &&\n Math.abs(previousRowLoc[1] - loc[1]) < Detector.MAX_PATTERN_DRIFT) {\n previousRowLoc = loc;\n skippedRowCount = 0;\n }\n else {\n if (skippedRowCount > Detector.SKIPPED_ROW_COUNT_MAX) {\n break;\n }\n else {\n skippedRowCount++;\n }\n }\n }\n stopRow -= skippedRowCount + 1;\n result[2] = new ResultPoint(previousRowLoc[0], stopRow);\n result[3] = new ResultPoint(previousRowLoc[1], stopRow);\n }\n if (stopRow - startRow < Detector.BARCODE_MIN_HEIGHT) {\n Arrays.fill(result, null);\n }\n return result;\n };\n /**\n * @param matrix row of black/white values to search\n * @param column x position to start search\n * @param row y position to start search\n * @param width the number of pixels to search on this row\n * @param pattern pattern of counts of number of black and white pixels that are\n * being searched for as a pattern\n * @param counters array of counters, as long as pattern, to re-use\n * @return start/end horizontal offset of guard pattern, as an array of two ints.\n */\n Detector.findGuardPattern = function (matrix, column, row, width, whiteFirst, pattern, counters) {\n Arrays.fillWithin(counters, 0, counters.length, 0);\n var patternStart = column;\n var pixelDrift = 0;\n // if there are black pixels left of the current pixel shift to the left, but only for MAX_PIXEL_DRIFT pixels\n while (matrix.get(patternStart, row) && patternStart > 0 && pixelDrift++ < Detector.MAX_PIXEL_DRIFT) {\n patternStart--;\n }\n var x = patternStart;\n var counterPosition = 0;\n var patternLength = pattern.length;\n for (var isWhite = whiteFirst; x < width; x++) {\n var pixel = matrix.get(x, row);\n if (pixel !== isWhite) {\n counters[counterPosition]++;\n }\n else {\n if (counterPosition === patternLength - 1) {\n if (Detector.patternMatchVariance(counters, pattern, Detector.MAX_INDIVIDUAL_VARIANCE) < Detector.MAX_AVG_VARIANCE) {\n return new Int32Array([patternStart, x]);\n }\n patternStart += counters[0] + counters[1];\n System.arraycopy(counters, 2, counters, 0, counterPosition - 1);\n counters[counterPosition - 1] = 0;\n counters[counterPosition] = 0;\n counterPosition--;\n }\n else {\n counterPosition++;\n }\n counters[counterPosition] = 1;\n isWhite = !isWhite;\n }\n }\n if (counterPosition === patternLength - 1 &&\n Detector.patternMatchVariance(counters, pattern, Detector.MAX_INDIVIDUAL_VARIANCE) < Detector.MAX_AVG_VARIANCE) {\n return new Int32Array([patternStart, x - 1]);\n }\n return null;\n };\n /**\n * Determines how closely a set of observed counts of runs of black/white\n * values matches a given target pattern. This is reported as the ratio of\n * the total variance from the expected pattern proportions across all\n * pattern elements, to the length of the pattern.\n *\n * @param counters observed counters\n * @param pattern expected pattern\n * @param maxIndividualVariance The most any counter can differ before we give up\n * @return ratio of total variance between counters and pattern compared to total pattern size\n */\n Detector.patternMatchVariance = function (counters, pattern, maxIndividualVariance) {\n var numCounters = counters.length;\n var total = 0;\n var patternLength = 0;\n for (var i = 0; i < numCounters; i++) {\n total += counters[i];\n patternLength += pattern[i];\n }\n if (total < patternLength) {\n // If we don't even have one pixel per unit of bar width, assume this\n // is too small to reliably match, so fail:\n return /*Float.POSITIVE_INFINITY*/ Infinity;\n }\n // We're going to fake floating-point math in integers. We just need to use more bits.\n // Scale up patternLength so that intermediate values below like scaledCounter will have\n // more \"significant digits\".\n var unitBarWidth = total / patternLength;\n maxIndividualVariance *= unitBarWidth;\n var totalVariance = 0.0;\n for (var x = 0; x < numCounters; x++) {\n var counter = counters[x];\n var scaledPattern = pattern[x] * unitBarWidth;\n var variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;\n if (variance > maxIndividualVariance) {\n return /*Float.POSITIVE_INFINITY*/ Infinity;\n }\n totalVariance += variance;\n }\n return totalVariance / total;\n };\n Detector.INDEXES_START_PATTERN = Int32Array.from([0, 4, 1, 5]);\n Detector.INDEXES_STOP_PATTERN = Int32Array.from([6, 2, 7, 3]);\n Detector.MAX_AVG_VARIANCE = 0.42;\n Detector.MAX_INDIVIDUAL_VARIANCE = 0.8;\n // B S B S B S B S Bar/Space pattern\n // 11111111 0 1 0 1 0 1 000\n Detector.START_PATTERN = Int32Array.from([8, 1, 1, 1, 1, 1, 1, 3]);\n // 1111111 0 1 000 1 0 1 00 1\n Detector.STOP_PATTERN = Int32Array.from([7, 1, 1, 3, 1, 1, 1, 2, 1]);\n Detector.MAX_PIXEL_DRIFT = 3;\n Detector.MAX_PATTERN_DRIFT = 5;\n // if we set the value too low, then we don't detect the correct height of the bar if the start patterns are damaged.\n // if we set the value too high, then we might detect the start pattern from a neighbor barcode.\n Detector.SKIPPED_ROW_COUNT_MAX = 25;\n // A PDF471 barcode should have at least 3 rows, with each row being >= 3 times the module width. Therefore it should be at least\n // 9 pixels tall. To be conservative, we use about half the size to ensure we don't miss it.\n Detector.ROW_STEP = 5;\n Detector.BARCODE_MIN_HEIGHT = 10;\n return Detector;\n}());\nexport default Detector;\n","/*\n* Copyright 2007 ZXing authors\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// import java.util.List;\n/**\n * @author Guenther Grau\n */\nvar PDF417DetectorResult = /** @class */ (function () {\n function PDF417DetectorResult(bits, points) {\n this.bits = bits;\n this.points = points;\n }\n PDF417DetectorResult.prototype.getBits = function () {\n return this.bits;\n };\n PDF417DetectorResult.prototype.getPoints = function () {\n return this.points;\n };\n return PDF417DetectorResult;\n}());\nexport default PDF417DetectorResult;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.qrcode {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport BitMatrix from '../common/BitMatrix';\nimport DecodeHintType from '../DecodeHintType';\nimport NotFoundException from '../NotFoundException';\nimport Result from '../Result';\nimport ResultMetadataType from '../ResultMetadataType';\n// import DetectorResult from '../common/DetectorResult';\nimport Decoder from './decoder/Decoder';\nimport QRCodeDecoderMetaData from './decoder/QRCodeDecoderMetaData';\nimport Detector from './detector/Detector';\n/*import java.util.List;*/\n/*import java.util.Map;*/\n/**\n * This implementation can detect and decode QR Codes in an image.\n *\n * @author Sean Owen\n */\nvar QRCodeReader = /** @class */ (function () {\n function QRCodeReader() {\n this.decoder = new Decoder();\n }\n QRCodeReader.prototype.getDecoder = function () {\n return this.decoder;\n };\n /**\n * Locates and decodes a QR code in an image.\n *\n * @return a representing: string the content encoded by the QR code\n * @throws NotFoundException if a QR code cannot be found\n * @throws FormatException if a QR code cannot be decoded\n * @throws ChecksumException if error correction fails\n */\n /*@Override*/\n // public decode(image: BinaryBitmap): Result /*throws NotFoundException, ChecksumException, FormatException */ {\n // return this.decode(image, null)\n // }\n /*@Override*/\n QRCodeReader.prototype.decode = function (image, hints) {\n var decoderResult;\n var points;\n if (hints !== undefined && hints !== null && undefined !== hints.get(DecodeHintType.PURE_BARCODE)) {\n var bits = QRCodeReader.extractPureBits(image.getBlackMatrix());\n decoderResult = this.decoder.decodeBitMatrix(bits, hints);\n points = QRCodeReader.NO_POINTS;\n }\n else {\n var detectorResult = new Detector(image.getBlackMatrix()).detect(hints);\n decoderResult = this.decoder.decodeBitMatrix(detectorResult.getBits(), hints);\n points = detectorResult.getPoints();\n }\n // If the code was mirrored: swap the bottom-left and the top-right points.\n if (decoderResult.getOther() instanceof QRCodeDecoderMetaData) {\n decoderResult.getOther().applyMirroredCorrection(points);\n }\n var result = new Result(decoderResult.getText(), decoderResult.getRawBytes(), undefined, points, BarcodeFormat.QR_CODE, undefined);\n var byteSegments = decoderResult.getByteSegments();\n if (byteSegments !== null) {\n result.putMetadata(ResultMetadataType.BYTE_SEGMENTS, byteSegments);\n }\n var ecLevel = decoderResult.getECLevel();\n if (ecLevel !== null) {\n result.putMetadata(ResultMetadataType.ERROR_CORRECTION_LEVEL, ecLevel);\n }\n if (decoderResult.hasStructuredAppend()) {\n result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_SEQUENCE, decoderResult.getStructuredAppendSequenceNumber());\n result.putMetadata(ResultMetadataType.STRUCTURED_APPEND_PARITY, decoderResult.getStructuredAppendParity());\n }\n return result;\n };\n /*@Override*/\n QRCodeReader.prototype.reset = function () {\n // do nothing\n };\n /**\n * This method detects a code in a \"pure\" image -- that is, pure monochrome image\n * which contains only an unrotated, unskewed, image of a code, with some white border\n * around it. This is a specialized method that works exceptionally fast in this special\n * case.\n *\n * @see com.google.zxing.datamatrix.DataMatrixReader#extractPureBits(BitMatrix)\n */\n QRCodeReader.extractPureBits = function (image) {\n var leftTopBlack = image.getTopLeftOnBit();\n var rightBottomBlack = image.getBottomRightOnBit();\n if (leftTopBlack === null || rightBottomBlack === null) {\n throw new NotFoundException();\n }\n var moduleSize = this.moduleSize(leftTopBlack, image);\n var top = leftTopBlack[1];\n var bottom = rightBottomBlack[1];\n var left = leftTopBlack[0];\n var right = rightBottomBlack[0];\n // Sanity check!\n if (left >= right || top >= bottom) {\n throw new NotFoundException();\n }\n if (bottom - top !== right - left) {\n // Special case, where bottom-right module wasn't black so we found something else in the last row\n // Assume it's a square, so use height as the width\n right = left + (bottom - top);\n if (right >= image.getWidth()) {\n // Abort if that would not make sense -- off image\n throw new NotFoundException();\n }\n }\n var matrixWidth = Math.round((right - left + 1) / moduleSize);\n var matrixHeight = Math.round((bottom - top + 1) / moduleSize);\n if (matrixWidth <= 0 || matrixHeight <= 0) {\n throw new NotFoundException();\n }\n if (matrixHeight !== matrixWidth) {\n // Only possibly decode square regions\n throw new NotFoundException();\n }\n // Push in the \"border\" by half the module width so that we start\n // sampling in the middle of the module. Just in case the image is a\n // little off, this will help recover.\n var nudge = /*(int) */ Math.floor(moduleSize / 2.0);\n top += nudge;\n left += nudge;\n // But careful that this does not sample off the edge\n // \"right\" is the farthest-right valid pixel location -- right+1 is not necessarily\n // This is positive by how much the inner x loop below would be too large\n var nudgedTooFarRight = left + /*(int) */ Math.floor((matrixWidth - 1) * moduleSize) - right;\n if (nudgedTooFarRight > 0) {\n if (nudgedTooFarRight > nudge) {\n // Neither way fits; abort\n throw new NotFoundException();\n }\n left -= nudgedTooFarRight;\n }\n // See logic above\n var nudgedTooFarDown = top + /*(int) */ Math.floor((matrixHeight - 1) * moduleSize) - bottom;\n if (nudgedTooFarDown > 0) {\n if (nudgedTooFarDown > nudge) {\n // Neither way fits; abort\n throw new NotFoundException();\n }\n top -= nudgedTooFarDown;\n }\n // Now just read off the bits\n var bits = new BitMatrix(matrixWidth, matrixHeight);\n for (var y = 0; y < matrixHeight; y++) {\n var iOffset = top + /*(int) */ Math.floor(y * moduleSize);\n for (var x = 0; x < matrixWidth; x++) {\n if (image.get(left + /*(int) */ Math.floor(x * moduleSize), iOffset)) {\n bits.set(x, y);\n }\n }\n }\n return bits;\n };\n QRCodeReader.moduleSize = function (leftTopBlack, image) {\n var height = image.getHeight();\n var width = image.getWidth();\n var x = leftTopBlack[0];\n var y = leftTopBlack[1];\n var inBlack = true;\n var transitions = 0;\n while (x < width && y < height) {\n if (inBlack !== image.get(x, y)) {\n if (++transitions === 5) {\n break;\n }\n inBlack = !inBlack;\n }\n x++;\n y++;\n }\n if (x === width || y === height) {\n throw new NotFoundException();\n }\n return (x - leftTopBlack[0]) / 7.0;\n };\n QRCodeReader.NO_POINTS = new Array();\n return QRCodeReader;\n}());\nexport default QRCodeReader;\n","/*\n * Copyright 2008 ZXing authors\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/*namespace com.google.zxing.qrcode {*/\nimport BarcodeFormat from '../BarcodeFormat';\nimport EncodeHintType from '../EncodeHintType';\nimport BitMatrix from '../common/BitMatrix';\nimport ErrorCorrectionLevel from './decoder/ErrorCorrectionLevel';\nimport Encoder from './encoder/Encoder';\nimport IllegalArgumentException from '../IllegalArgumentException';\nimport IllegalStateException from '../IllegalStateException';\n/*import java.util.Map;*/\n/**\n * This object renders a QR Code as a BitMatrix 2D array of greyscale values.\n *\n * @author dswitkin@google.com (Daniel Switkin)\n */\nvar QRCodeWriter = /** @class */ (function () {\n function QRCodeWriter() {\n }\n /*@Override*/\n // public encode(contents: string, format: BarcodeFormat, width: number /*int*/, height: number /*int*/): BitMatrix\n // /*throws WriterException */ {\n // return encode(contents, format, width, height, null)\n // }\n /*@Override*/\n QRCodeWriter.prototype.encode = function (contents, format, width /*int*/, height /*int*/, hints) {\n if (contents.length === 0) {\n throw new IllegalArgumentException('Found empty contents');\n }\n if (format !== BarcodeFormat.QR_CODE) {\n throw new IllegalArgumentException('Can only encode QR_CODE, but got ' + format);\n }\n if (width < 0 || height < 0) {\n throw new IllegalArgumentException(\"Requested dimensions are too small: \" + width + \"x\" + height);\n }\n var errorCorrectionLevel = ErrorCorrectionLevel.L;\n var quietZone = QRCodeWriter.QUIET_ZONE_SIZE;\n if (hints !== null) {\n if (undefined !== hints.get(EncodeHintType.ERROR_CORRECTION)) {\n errorCorrectionLevel = ErrorCorrectionLevel.fromString(hints.get(EncodeHintType.ERROR_CORRECTION).toString());\n }\n if (undefined !== hints.get(EncodeHintType.MARGIN)) {\n quietZone = Number.parseInt(hints.get(EncodeHintType.MARGIN).toString(), 10);\n }\n }\n var code = Encoder.encode(contents, errorCorrectionLevel, hints);\n return QRCodeWriter.renderResult(code, width, height, quietZone);\n };\n // Note that the input matrix uses 0 == white, 1 == black, while the output matrix uses\n // 0 == black, 255 == white (i.e. an 8 bit greyscale bitmap).\n QRCodeWriter.renderResult = function (code, width /*int*/, height /*int*/, quietZone /*int*/) {\n var input = code.getMatrix();\n if (input === null) {\n throw new IllegalStateException();\n }\n var inputWidth = input.getWidth();\n var inputHeight = input.getHeight();\n var qrWidth = inputWidth + (quietZone * 2);\n var qrHeight = inputHeight + (quietZone * 2);\n var outputWidth = Math.max(width, qrWidth);\n var outputHeight = Math.max(height, qrHeight);\n var multiple = Math.min(Math.floor(outputWidth / qrWidth), Math.floor(outputHeight / qrHeight));\n // Padding includes both the quiet zone and the extra white pixels to accommodate the requested\n // dimensions. For example, if input is 25x25 the QR will be 33x33 including the quiet zone.\n // If the requested size is 200x160, the multiple will be 4, for a QR of 132x132. These will\n // handle all the padding from 100x100 (the actual QR) up to 200x160.\n var leftPadding = Math.floor((outputWidth - (inputWidth * multiple)) / 2);\n var topPadding = Math.floor((outputHeight - (inputHeight * multiple)) / 2);\n var output = new BitMatrix(outputWidth, outputHeight);\n for (var inputY = 0, outputY = topPadding; inputY < inputHeight; inputY++, outputY += multiple) {\n // Write the contents of this row of the barcode\n for (var inputX = 0, outputX = leftPadding; inputX < inputWidth; inputX++, outputX += multiple) {\n if (input.get(inputX, inputY) === 1) {\n output.setRegion(outputX, outputY, multiple, multiple);\n }\n }\n }\n return output;\n };\n QRCodeWriter.QUIET_ZONE_SIZE = 4;\n return QRCodeWriter;\n}());\nexport default QRCodeWriter;\n","/*\n * Copyright 2007 ZXing authors\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 */\nimport Version from './Version';\nimport FormatInformation from './FormatInformation';\nimport DataMask from './DataMask';\nimport FormatException from '../../FormatException';\n/**\n * @author Sean Owen\n */\nvar BitMatrixParser = /** @class */ (function () {\n /**\n * @param bitMatrix {@link BitMatrix} to parse\n * @throws FormatException if dimension is not >= 21 and 1 mod 4\n */\n function BitMatrixParser(bitMatrix) {\n var dimension = bitMatrix.getHeight();\n if (dimension < 21 || (dimension & 0x03) !== 1) {\n throw new FormatException();\n }\n this.bitMatrix = bitMatrix;\n }\n /**\n *Reads format information from one of its two locations within the QR Code.
\n *\n * @return {@link FormatInformation} encapsulating the QR Code's format info\n * @throws FormatException if both format information locations cannot be parsed as\n * the valid encoding of format information\n */\n BitMatrixParser.prototype.readFormatInformation = function () {\n if (this.parsedFormatInfo !== null && this.parsedFormatInfo !== undefined) {\n return this.parsedFormatInfo;\n }\n // Read top-left format info bits\n var formatInfoBits1 = 0;\n for (var i = 0; i < 6; i++) {\n formatInfoBits1 = this.copyBit(i, 8, formatInfoBits1);\n }\n // .. and skip a bit in the timing pattern ...\n formatInfoBits1 = this.copyBit(7, 8, formatInfoBits1);\n formatInfoBits1 = this.copyBit(8, 8, formatInfoBits1);\n formatInfoBits1 = this.copyBit(8, 7, formatInfoBits1);\n // .. and skip a bit in the timing pattern ...\n for (var j = 5; j >= 0; j--) {\n formatInfoBits1 = this.copyBit(8, j, formatInfoBits1);\n }\n // Read the top-right/bottom-left pattern too\n var dimension = this.bitMatrix.getHeight();\n var formatInfoBits2 = 0;\n var jMin = dimension - 7;\n for (var j = dimension - 1; j >= jMin; j--) {\n formatInfoBits2 = this.copyBit(8, j, formatInfoBits2);\n }\n for (var i = dimension - 8; i < dimension; i++) {\n formatInfoBits2 = this.copyBit(i, 8, formatInfoBits2);\n }\n this.parsedFormatInfo = FormatInformation.decodeFormatInformation(formatInfoBits1, formatInfoBits2);\n if (this.parsedFormatInfo !== null) {\n return this.parsedFormatInfo;\n }\n throw new FormatException();\n };\n /**\n *Reads version information from one of its two locations within the QR Code.
\n *\n * @return {@link Version} encapsulating the QR Code's version\n * @throws FormatException if both version information locations cannot be parsed as\n * the valid encoding of version information\n */\n BitMatrixParser.prototype.readVersion = function () {\n if (this.parsedVersion !== null && this.parsedVersion !== undefined) {\n return this.parsedVersion;\n }\n var dimension = this.bitMatrix.getHeight();\n var provisionalVersion = Math.floor((dimension - 17) / 4);\n if (provisionalVersion <= 6) {\n return Version.getVersionForNumber(provisionalVersion);\n }\n // Read top-right version info: 3 wide by 6 tall\n var versionBits = 0;\n var ijMin = dimension - 11;\n for (var j = 5; j >= 0; j--) {\n for (var i = dimension - 9; i >= ijMin; i--) {\n versionBits = this.copyBit(i, j, versionBits);\n }\n }\n var theParsedVersion = Version.decodeVersionInformation(versionBits);\n if (theParsedVersion !== null && theParsedVersion.getDimensionForVersion() === dimension) {\n this.parsedVersion = theParsedVersion;\n return theParsedVersion;\n }\n // Hmm, failed. Try bottom left: 6 wide by 3 tall\n versionBits = 0;\n for (var i = 5; i >= 0; i--) {\n for (var j = dimension - 9; j >= ijMin; j--) {\n versionBits = this.copyBit(i, j, versionBits);\n }\n }\n theParsedVersion = Version.decodeVersionInformation(versionBits);\n if (theParsedVersion !== null && theParsedVersion.getDimensionForVersion() === dimension) {\n this.parsedVersion = theParsedVersion;\n return theParsedVersion;\n }\n throw new FormatException();\n };\n BitMatrixParser.prototype.copyBit = function (i /*int*/, j /*int*/, versionBits /*int*/) {\n var bit = this.isMirror ? this.bitMatrix.get(j, i) : this.bitMatrix.get(i, j);\n return bit ? (versionBits << 1) | 0x1 : versionBits << 1;\n };\n /**\n *Reads the bits in the {@link BitMatrix} representing the finder pattern in the\n * correct order in order to reconstruct the codewords bytes contained within the\n * QR Code.
\n *\n * @return bytes encoded within the QR Code\n * @throws FormatException if the exact number of bytes expected is not read\n */\n BitMatrixParser.prototype.readCodewords = function () {\n var formatInfo = this.readFormatInformation();\n var version = this.readVersion();\n // Get the data mask for the format used in this QR Code. This will exclude\n // some bits from reading as we wind through the bit matrix.\n var dataMask = DataMask.values.get(formatInfo.getDataMask());\n var dimension = this.bitMatrix.getHeight();\n dataMask.unmaskBitMatrix(this.bitMatrix, dimension);\n var functionPattern = version.buildFunctionPattern();\n var readingUp = true;\n var result = new Uint8Array(version.getTotalCodewords());\n var resultOffset = 0;\n var currentByte = 0;\n var bitsRead = 0;\n // Read columns in pairs, from right to left\n for (var j = dimension - 1; j > 0; j -= 2) {\n if (j === 6) {\n // Skip whole column with vertical alignment pattern\n // saves time and makes the other code proceed more cleanly\n j--;\n }\n // Read alternatingly from bottom to top then top to bottom\n for (var count = 0; count < dimension; count++) {\n var i = readingUp ? dimension - 1 - count : count;\n for (var col = 0; col < 2; col++) {\n // Ignore bits covered by the function pattern\n if (!functionPattern.get(j - col, i)) {\n // Read a bit\n bitsRead++;\n currentByte <<= 1;\n if (this.bitMatrix.get(j - col, i)) {\n currentByte |= 1;\n }\n // If we've made a whole byte, save it off\n if (bitsRead === 8) {\n result[resultOffset++] = /*(byte) */ currentByte;\n bitsRead = 0;\n currentByte = 0;\n }\n }\n }\n }\n readingUp = !readingUp; // readingUp ^= true; // readingUp = !readingUp; // switch directions\n }\n if (resultOffset !== version.getTotalCodewords()) {\n throw new FormatException();\n }\n return result;\n };\n /**\n * Revert the mask removal done while reading the code words. The bit matrix should revert to its original state.\n */\n BitMatrixParser.prototype.remask = function () {\n if (this.parsedFormatInfo === null) {\n return; // We have no format information, and have no data mask\n }\n var dataMask = DataMask.values.get(this.parsedFormatInfo.getDataMask());\n var dimension = this.bitMatrix.getHeight();\n dataMask.unmaskBitMatrix(this.bitMatrix, dimension);\n };\n /**\n * Prepare the parser for a mirrored operation.\n * This flag has effect only on the {@link #readFormatInformation()} and the\n * {@link #readVersion()}. Before proceeding with {@link #readCodewords()} the\n * {@link #mirror()} method should be called.\n *\n * @param mirror Whether to read version and format information mirrored.\n */\n BitMatrixParser.prototype.setMirror = function (isMirror) {\n this.parsedVersion = null;\n this.parsedFormatInfo = null;\n this.isMirror = isMirror;\n };\n /** Mirror the bit matrix in order to attempt a second reading. */\n BitMatrixParser.prototype.mirror = function () {\n var bitMatrix = this.bitMatrix;\n for (var x = 0, width = bitMatrix.getWidth(); x < width; x++) {\n for (var y = x + 1, height = bitMatrix.getHeight(); y < height; y++) {\n if (bitMatrix.get(x, y) !== bitMatrix.get(y, x)) {\n bitMatrix.flip(y, x);\n bitMatrix.flip(x, y);\n }\n }\n }\n };\n return BitMatrixParser;\n}());\nexport default BitMatrixParser;\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport IllegalArgumentException from '../../IllegalArgumentException';\n/**\n *Encapsulates a block of data within a QR Code. QR Codes may split their data into\n * multiple blocks, each of which is a unit of data and error-correction codewords. Each\n * is represented by an instance of this class.
\n *\n * @author Sean Owen\n */\nvar DataBlock = /** @class */ (function () {\n function DataBlock(numDataCodewords /*int*/, codewords) {\n this.numDataCodewords = numDataCodewords;\n this.codewords = codewords;\n }\n /**\n *When QR Codes use multiple data blocks, they are actually interleaved.\n * That is, the first byte of data block 1 to n is written, then the second bytes, and so on. This\n * method will separate the data into original blocks.
\n *\n * @param rawCodewords bytes as read directly from the QR Code\n * @param version version of the QR Code\n * @param ecLevel error-correction level of the QR Code\n * @return DataBlocks containing original bytes, \"de-interleaved\" from representation in the\n * QR Code\n */\n DataBlock.getDataBlocks = function (rawCodewords, version, ecLevel) {\n var e_1, _a, e_2, _b;\n if (rawCodewords.length !== version.getTotalCodewords()) {\n throw new IllegalArgumentException();\n }\n // Figure out the number and size of data blocks used by this version and\n // error correction level\n var ecBlocks = version.getECBlocksForLevel(ecLevel);\n // First count the total number of data blocks\n var totalBlocks = 0;\n var ecBlockArray = ecBlocks.getECBlocks();\n try {\n for (var ecBlockArray_1 = __values(ecBlockArray), ecBlockArray_1_1 = ecBlockArray_1.next(); !ecBlockArray_1_1.done; ecBlockArray_1_1 = ecBlockArray_1.next()) {\n var ecBlock = ecBlockArray_1_1.value;\n totalBlocks += ecBlock.getCount();\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (ecBlockArray_1_1 && !ecBlockArray_1_1.done && (_a = ecBlockArray_1.return)) _a.call(ecBlockArray_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Now establish DataBlocks of the appropriate size and number of data codewords\n var result = new Array(totalBlocks);\n var numResultBlocks = 0;\n try {\n for (var ecBlockArray_2 = __values(ecBlockArray), ecBlockArray_2_1 = ecBlockArray_2.next(); !ecBlockArray_2_1.done; ecBlockArray_2_1 = ecBlockArray_2.next()) {\n var ecBlock = ecBlockArray_2_1.value;\n for (var i = 0; i < ecBlock.getCount(); i++) {\n var numDataCodewords = ecBlock.getDataCodewords();\n var numBlockCodewords = ecBlocks.getECCodewordsPerBlock() + numDataCodewords;\n result[numResultBlocks++] = new DataBlock(numDataCodewords, new Uint8Array(numBlockCodewords));\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (ecBlockArray_2_1 && !ecBlockArray_2_1.done && (_b = ecBlockArray_2.return)) _b.call(ecBlockArray_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n // All blocks have the same amount of data, except that the last n\n // (where n may be 0) have 1 more byte. Figure out where these start.\n var shorterBlocksTotalCodewords = result[0].codewords.length;\n var longerBlocksStartAt = result.length - 1;\n // TYPESCRIPTPORT: check length is correct here\n while (longerBlocksStartAt >= 0) {\n var numCodewords = result[longerBlocksStartAt].codewords.length;\n if (numCodewords === shorterBlocksTotalCodewords) {\n break;\n }\n longerBlocksStartAt--;\n }\n longerBlocksStartAt++;\n var shorterBlocksNumDataCodewords = shorterBlocksTotalCodewords - ecBlocks.getECCodewordsPerBlock();\n // The last elements of result may be 1 element longer\n // first fill out as many elements as all of them have\n var rawCodewordsOffset = 0;\n for (var i = 0; i < shorterBlocksNumDataCodewords; i++) {\n for (var j = 0; j < numResultBlocks; j++) {\n result[j].codewords[i] = rawCodewords[rawCodewordsOffset++];\n }\n }\n // Fill out the last data block in the longer ones\n for (var j = longerBlocksStartAt; j < numResultBlocks; j++) {\n result[j].codewords[shorterBlocksNumDataCodewords] = rawCodewords[rawCodewordsOffset++];\n }\n // Now add in error correction blocks\n var max = result[0].codewords.length;\n for (var i = shorterBlocksNumDataCodewords; i < max; i++) {\n for (var j = 0; j < numResultBlocks; j++) {\n var iOffset = j < longerBlocksStartAt ? i : i + 1;\n result[j].codewords[iOffset] = rawCodewords[rawCodewordsOffset++];\n }\n }\n return result;\n };\n DataBlock.prototype.getNumDataCodewords = function () {\n return this.numDataCodewords;\n };\n DataBlock.prototype.getCodewords = function () {\n return this.codewords;\n };\n return DataBlock;\n}());\nexport default DataBlock;\n","/*\n * Copyright 2007 ZXing authors\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 */\nexport var DataMaskValues;\n(function (DataMaskValues) {\n DataMaskValues[DataMaskValues[\"DATA_MASK_000\"] = 0] = \"DATA_MASK_000\";\n DataMaskValues[DataMaskValues[\"DATA_MASK_001\"] = 1] = \"DATA_MASK_001\";\n DataMaskValues[DataMaskValues[\"DATA_MASK_010\"] = 2] = \"DATA_MASK_010\";\n DataMaskValues[DataMaskValues[\"DATA_MASK_011\"] = 3] = \"DATA_MASK_011\";\n DataMaskValues[DataMaskValues[\"DATA_MASK_100\"] = 4] = \"DATA_MASK_100\";\n DataMaskValues[DataMaskValues[\"DATA_MASK_101\"] = 5] = \"DATA_MASK_101\";\n DataMaskValues[DataMaskValues[\"DATA_MASK_110\"] = 6] = \"DATA_MASK_110\";\n DataMaskValues[DataMaskValues[\"DATA_MASK_111\"] = 7] = \"DATA_MASK_111\";\n})(DataMaskValues || (DataMaskValues = {}));\n/**\n *Encapsulates data masks for the data bits in a QR code, per ISO 18004:2006 6.8. Implementations\n * of this class can un-mask a raw BitMatrix. For simplicity, they will unmask the entire BitMatrix,\n * including areas used for finder patterns, timing patterns, etc. These areas should be unused\n * after the point they are unmasked anyway.
\n *\n *Note that the diagram in section 6.8.1 is misleading since it indicates that i is column position\n * and j is row position. In fact, as the text says, i is row position and j is column position.
\n *\n * @author Sean Owen\n */\nvar DataMask = /** @class */ (function () {\n // See ISO 18004:2006 6.8.1\n function DataMask(value, isMasked) {\n this.value = value;\n this.isMasked = isMasked;\n }\n // End of enum constants.\n /**\n *Implementations of this method reverse the data masking process applied to a QR Code and\n * make its bits ready to read.
\n *\n * @param bits representation of QR Code bits\n * @param dimension dimension of QR Code, represented by bits, being unmasked\n */\n DataMask.prototype.unmaskBitMatrix = function (bits, dimension /*int*/) {\n for (var i = 0; i < dimension; i++) {\n for (var j = 0; j < dimension; j++) {\n if (this.isMasked(i, j)) {\n bits.flip(j, i);\n }\n }\n }\n };\n DataMask.values = new Map([\n /**\n * 000: mask bits for which (x + y) mod 2 == 0\n */\n [DataMaskValues.DATA_MASK_000, new DataMask(DataMaskValues.DATA_MASK_000, function (i /*int*/, j /*int*/) { return ((i + j) & 0x01) === 0; })],\n /**\n * 001: mask bits for which x mod 2 == 0\n */\n [DataMaskValues.DATA_MASK_001, new DataMask(DataMaskValues.DATA_MASK_001, function (i /*int*/, j /*int*/) { return (i & 0x01) === 0; })],\n /**\n * 010: mask bits for which y mod 3 == 0\n */\n [DataMaskValues.DATA_MASK_010, new DataMask(DataMaskValues.DATA_MASK_010, function (i /*int*/, j /*int*/) { return j % 3 === 0; })],\n /**\n * 011: mask bits for which (x + y) mod 3 == 0\n */\n [DataMaskValues.DATA_MASK_011, new DataMask(DataMaskValues.DATA_MASK_011, function (i /*int*/, j /*int*/) { return (i + j) % 3 === 0; })],\n /**\n * 100: mask bits for which (x/2 + y/3) mod 2 == 0\n */\n [DataMaskValues.DATA_MASK_100, new DataMask(DataMaskValues.DATA_MASK_100, function (i /*int*/, j /*int*/) { return ((Math.floor(i / 2) + Math.floor(j / 3)) & 0x01) === 0; })],\n /**\n * 101: mask bits for which xy mod 2 + xy mod 3 == 0\n * equivalently, such that xy mod 6 == 0\n */\n [DataMaskValues.DATA_MASK_101, new DataMask(DataMaskValues.DATA_MASK_101, function (i /*int*/, j /*int*/) { return (i * j) % 6 === 0; })],\n /**\n * 110: mask bits for which (xy mod 2 + xy mod 3) mod 2 == 0\n * equivalently, such that xy mod 6 < 3\n */\n [DataMaskValues.DATA_MASK_110, new DataMask(DataMaskValues.DATA_MASK_110, function (i /*int*/, j /*int*/) { return ((i * j) % 6) < 3; })],\n /**\n * 111: mask bits for which ((x+y)mod 2 + xy mod 3) mod 2 == 0\n * equivalently, such that (x + y + xy mod 3) mod 2 == 0\n */\n [DataMaskValues.DATA_MASK_111, new DataMask(DataMaskValues.DATA_MASK_111, function (i /*int*/, j /*int*/) { return ((i + j + ((i * j) % 3)) & 0x01) === 0; })],\n ]);\n return DataMask;\n}());\nexport default DataMask;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.qrcode.decoder {*/\nimport BitSource from '../../common/BitSource';\nimport CharacterSetECI from '../../common/CharacterSetECI';\nimport DecoderResult from '../../common/DecoderResult';\nimport StringUtils from '../../common/StringUtils';\nimport FormatException from '../../FormatException';\nimport StringBuilder from '../../util/StringBuilder';\nimport StringEncoding from '../../util/StringEncoding';\nimport Mode from './Mode';\n/*import java.io.UnsupportedEncodingException;*/\n/*import java.util.ArrayList;*/\n/*import java.util.Collection;*/\n/*import java.util.List;*/\n/*import java.util.Map;*/\n/**\n *QR Codes can encode text as bits in one of several modes, and can use multiple modes\n * in one QR Code. This class decodes the bits back into text.
\n *\n *See ISO 18004:2006, 6.4.3 - 6.4.7
\n *\n * @author Sean Owen\n */\nvar DecodedBitStreamParser = /** @class */ (function () {\n function DecodedBitStreamParser() {\n }\n DecodedBitStreamParser.decode = function (bytes, version, ecLevel, hints) {\n var bits = new BitSource(bytes);\n var result = new StringBuilder();\n var byteSegments = new Array(); // 1\n // TYPESCRIPTPORT: I do not use constructor with size 1 as in original Java means capacity and the array length is checked below\n var symbolSequence = -1;\n var parityData = -1;\n try {\n var currentCharacterSetECI = null;\n var fc1InEffect = false;\n var mode = void 0;\n do {\n // While still another segment to read...\n if (bits.available() < 4) {\n // OK, assume we're done. Really, a TERMINATOR mode should have been recorded here\n mode = Mode.TERMINATOR;\n }\n else {\n var modeBits = bits.readBits(4);\n mode = Mode.forBits(modeBits); // mode is encoded by 4 bits\n }\n switch (mode) {\n case Mode.TERMINATOR:\n break;\n case Mode.FNC1_FIRST_POSITION:\n case Mode.FNC1_SECOND_POSITION:\n // We do little with FNC1 except alter the parsed result a bit according to the spec\n fc1InEffect = true;\n break;\n case Mode.STRUCTURED_APPEND:\n if (bits.available() < 16) {\n throw new FormatException();\n }\n // sequence number and parity is added later to the result metadata\n // Read next 8 bits (symbol sequence #) and 8 bits (data: parity), then continue\n symbolSequence = bits.readBits(8);\n parityData = bits.readBits(8);\n break;\n case Mode.ECI:\n // Count doesn't apply to ECI\n var value = DecodedBitStreamParser.parseECIValue(bits);\n currentCharacterSetECI = CharacterSetECI.getCharacterSetECIByValue(value);\n if (currentCharacterSetECI === null) {\n throw new FormatException();\n }\n break;\n case Mode.HANZI:\n // First handle Hanzi mode which does not start with character count\n // Chinese mode contains a sub set indicator right after mode indicator\n var subset = bits.readBits(4);\n var countHanzi = bits.readBits(mode.getCharacterCountBits(version));\n if (subset === DecodedBitStreamParser.GB2312_SUBSET) {\n DecodedBitStreamParser.decodeHanziSegment(bits, result, countHanzi);\n }\n break;\n default:\n // \"Normal\" QR code modes:\n // How many characters will follow, encoded in this mode?\n var count = bits.readBits(mode.getCharacterCountBits(version));\n switch (mode) {\n case Mode.NUMERIC:\n DecodedBitStreamParser.decodeNumericSegment(bits, result, count);\n break;\n case Mode.ALPHANUMERIC:\n DecodedBitStreamParser.decodeAlphanumericSegment(bits, result, count, fc1InEffect);\n break;\n case Mode.BYTE:\n DecodedBitStreamParser.decodeByteSegment(bits, result, count, currentCharacterSetECI, byteSegments, hints);\n break;\n case Mode.KANJI:\n DecodedBitStreamParser.decodeKanjiSegment(bits, result, count);\n break;\n default:\n throw new FormatException();\n }\n break;\n }\n } while (mode !== Mode.TERMINATOR);\n }\n catch (iae /*: IllegalArgumentException*/) {\n // from readBits() calls\n throw new FormatException();\n }\n return new DecoderResult(bytes, result.toString(), byteSegments.length === 0 ? null : byteSegments, ecLevel === null ? null : ecLevel.toString(), symbolSequence, parityData);\n };\n /**\n * See specification GBT 18284-2000\n */\n DecodedBitStreamParser.decodeHanziSegment = function (bits, result, count /*int*/) {\n // Don't crash trying to read more bits than we have available.\n if (count * 13 > bits.available()) {\n throw new FormatException();\n }\n // Each character will require 2 bytes. Read the characters as 2-byte pairs\n // and decode as GB2312 afterwards\n var buffer = new Uint8Array(2 * count);\n var offset = 0;\n while (count > 0) {\n // Each 13 bits encodes a 2-byte character\n var twoBytes = bits.readBits(13);\n var assembledTwoBytes = (((twoBytes / 0x060) << 8) & 0xFFFFFFFF) | (twoBytes % 0x060);\n if (assembledTwoBytes < 0x003BF) {\n // In the 0xA1A1 to 0xAAFE range\n assembledTwoBytes += 0x0A1A1;\n }\n else {\n // In the 0xB0A1 to 0xFAFE range\n assembledTwoBytes += 0x0A6A1;\n }\n buffer[offset] = /*(byte) */ ((assembledTwoBytes >> 8) & 0xFF);\n buffer[offset + 1] = /*(byte) */ (assembledTwoBytes & 0xFF);\n offset += 2;\n count--;\n }\n try {\n result.append(StringEncoding.decode(buffer, StringUtils.GB2312));\n // TYPESCRIPTPORT: TODO: implement GB2312 decode. StringView from MDN could be a starting point\n }\n catch (ignored /*: UnsupportedEncodingException*/) {\n throw new FormatException(ignored);\n }\n };\n DecodedBitStreamParser.decodeKanjiSegment = function (bits, result, count /*int*/) {\n // Don't crash trying to read more bits than we have available.\n if (count * 13 > bits.available()) {\n throw new FormatException();\n }\n // Each character will require 2 bytes. Read the characters as 2-byte pairs\n // and decode as Shift_JIS afterwards\n var buffer = new Uint8Array(2 * count);\n var offset = 0;\n while (count > 0) {\n // Each 13 bits encodes a 2-byte character\n var twoBytes = bits.readBits(13);\n var assembledTwoBytes = (((twoBytes / 0x0C0) << 8) & 0xFFFFFFFF) | (twoBytes % 0x0C0);\n if (assembledTwoBytes < 0x01F00) {\n // In the 0x8140 to 0x9FFC range\n assembledTwoBytes += 0x08140;\n }\n else {\n // In the 0xE040 to 0xEBBF range\n assembledTwoBytes += 0x0C140;\n }\n buffer[offset] = /*(byte) */ (assembledTwoBytes >> 8);\n buffer[offset + 1] = /*(byte) */ assembledTwoBytes;\n offset += 2;\n count--;\n }\n // Shift_JIS may not be supported in some environments:\n try {\n result.append(StringEncoding.decode(buffer, StringUtils.SHIFT_JIS));\n // TYPESCRIPTPORT: TODO: implement SHIFT_JIS decode. StringView from MDN could be a starting point\n }\n catch (ignored /*: UnsupportedEncodingException*/) {\n throw new FormatException(ignored);\n }\n };\n DecodedBitStreamParser.decodeByteSegment = function (bits, result, count /*int*/, currentCharacterSetECI, byteSegments, hints) {\n // Don't crash trying to read more bits than we have available.\n if (8 * count > bits.available()) {\n throw new FormatException();\n }\n var readBytes = new Uint8Array(count);\n for (var i = 0; i < count; i++) {\n readBytes[i] = /*(byte) */ bits.readBits(8);\n }\n var encoding;\n if (currentCharacterSetECI === null) {\n // The spec isn't clear on this mode; see\n // section 6.4.5: t does not say which encoding to assuming\n // upon decoding. I have seen ISO-8859-1 used as well as\n // Shift_JIS -- without anything like an ECI designator to\n // give a hint.\n encoding = StringUtils.guessEncoding(readBytes, hints);\n }\n else {\n encoding = currentCharacterSetECI.getName();\n }\n try {\n result.append(StringEncoding.decode(readBytes, encoding));\n }\n catch (ignored /*: UnsupportedEncodingException*/) {\n throw new FormatException(ignored);\n }\n byteSegments.push(readBytes);\n };\n DecodedBitStreamParser.toAlphaNumericChar = function (value /*int*/) {\n if (value >= DecodedBitStreamParser.ALPHANUMERIC_CHARS.length) {\n throw new FormatException();\n }\n return DecodedBitStreamParser.ALPHANUMERIC_CHARS[value];\n };\n DecodedBitStreamParser.decodeAlphanumericSegment = function (bits, result, count /*int*/, fc1InEffect) {\n // Read two characters at a time\n var start = result.length();\n while (count > 1) {\n if (bits.available() < 11) {\n throw new FormatException();\n }\n var nextTwoCharsBits = bits.readBits(11);\n result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(nextTwoCharsBits / 45)));\n result.append(DecodedBitStreamParser.toAlphaNumericChar(nextTwoCharsBits % 45));\n count -= 2;\n }\n if (count === 1) {\n // special case: one character left\n if (bits.available() < 6) {\n throw new FormatException();\n }\n result.append(DecodedBitStreamParser.toAlphaNumericChar(bits.readBits(6)));\n }\n // See section 6.4.8.1, 6.4.8.2\n if (fc1InEffect) {\n // We need to massage the result a bit if in an FNC1 mode:\n for (var i = start; i < result.length(); i++) {\n if (result.charAt(i) === '%') {\n if (i < result.length() - 1 && result.charAt(i + 1) === '%') {\n // %% is rendered as %\n result.deleteCharAt(i + 1);\n }\n else {\n // In alpha mode, % should be converted to FNC1 separator 0x1D\n result.setCharAt(i, String.fromCharCode(0x1D));\n }\n }\n }\n }\n };\n DecodedBitStreamParser.decodeNumericSegment = function (bits, result, count /*int*/) {\n // Read three digits at a time\n while (count >= 3) {\n // Each 10 bits encodes three digits\n if (bits.available() < 10) {\n throw new FormatException();\n }\n var threeDigitsBits = bits.readBits(10);\n if (threeDigitsBits >= 1000) {\n throw new FormatException();\n }\n result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(threeDigitsBits / 100)));\n result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(threeDigitsBits / 10) % 10));\n result.append(DecodedBitStreamParser.toAlphaNumericChar(threeDigitsBits % 10));\n count -= 3;\n }\n if (count === 2) {\n // Two digits left over to read, encoded in 7 bits\n if (bits.available() < 7) {\n throw new FormatException();\n }\n var twoDigitsBits = bits.readBits(7);\n if (twoDigitsBits >= 100) {\n throw new FormatException();\n }\n result.append(DecodedBitStreamParser.toAlphaNumericChar(Math.floor(twoDigitsBits / 10)));\n result.append(DecodedBitStreamParser.toAlphaNumericChar(twoDigitsBits % 10));\n }\n else if (count === 1) {\n // One digit left over to read\n if (bits.available() < 4) {\n throw new FormatException();\n }\n var digitBits = bits.readBits(4);\n if (digitBits >= 10) {\n throw new FormatException();\n }\n result.append(DecodedBitStreamParser.toAlphaNumericChar(digitBits));\n }\n };\n DecodedBitStreamParser.parseECIValue = function (bits) {\n var firstByte = bits.readBits(8);\n if ((firstByte & 0x80) === 0) {\n // just one byte\n return firstByte & 0x7F;\n }\n if ((firstByte & 0xC0) === 0x80) {\n // two bytes\n var secondByte = bits.readBits(8);\n return (((firstByte & 0x3F) << 8) & 0xFFFFFFFF) | secondByte;\n }\n if ((firstByte & 0xE0) === 0xC0) {\n // three bytes\n var secondThirdBytes = bits.readBits(16);\n return (((firstByte & 0x1F) << 16) & 0xFFFFFFFF) | secondThirdBytes;\n }\n throw new FormatException();\n };\n /**\n * See ISO 18004:2006, 6.4.4 Table 5\n */\n DecodedBitStreamParser.ALPHANUMERIC_CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:';\n DecodedBitStreamParser.GB2312_SUBSET = 1;\n return DecodedBitStreamParser;\n}());\nexport default DecodedBitStreamParser;\n// function Uint8ArrayToString(a: Uint8Array): string {\n// const CHUNK_SZ = 0x8000;\n// const c = new StringBuilder();\n// for (let i = 0, length = a.length; i < length; i += CHUNK_SZ) {\n// c.append(String.fromCharCode.apply(null, a.subarray(i, i + CHUNK_SZ)));\n// }\n// return c.toString();\n// }\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.qrcode.decoder {*/\nimport ChecksumException from '../../ChecksumException';\nimport BitMatrix from '../../common/BitMatrix';\nimport GenericGF from '../../common/reedsolomon/GenericGF';\nimport ReedSolomonDecoder from '../../common/reedsolomon/ReedSolomonDecoder';\nimport BitMatrixParser from './BitMatrixParser';\nimport DataBlock from './DataBlock';\nimport DecodedBitStreamParser from './DecodedBitStreamParser';\nimport QRCodeDecoderMetaData from './QRCodeDecoderMetaData';\n/*import java.util.Map;*/\n/**\n *The main class which implements QR Code decoding -- as opposed to locating and extracting\n * the QR Code from an image.
\n *\n * @author Sean Owen\n */\nvar Decoder = /** @class */ (function () {\n function Decoder() {\n this.rsDecoder = new ReedSolomonDecoder(GenericGF.QR_CODE_FIELD_256);\n }\n // public decode(image: boolean[][]): DecoderResult /*throws ChecksumException, FormatException*/ {\n // return decode(image, null)\n // }\n /**\n *Convenience method that can decode a QR Code represented as a 2D array of booleans.\n * \"true\" is taken to mean a black module.
\n *\n * @param image booleans representing white/black QR Code modules\n * @param hints decoding hints that should be used to influence decoding\n * @return text and bytes encoded within the QR Code\n * @throws FormatException if the QR Code cannot be decoded\n * @throws ChecksumException if error correction fails\n */\n Decoder.prototype.decodeBooleanArray = function (image, hints) {\n return this.decodeBitMatrix(BitMatrix.parseFromBooleanArray(image), hints);\n };\n // public decodeBitMatrix(bits: BitMatrix): DecoderResult /*throws ChecksumException, FormatException*/ {\n // return decode(bits, null)\n // }\n /**\n *Decodes a QR Code represented as a {@link BitMatrix}. A 1 or \"true\" is taken to mean a black module.
\n *\n * @param bits booleans representing white/black QR Code modules\n * @param hints decoding hints that should be used to influence decoding\n * @return text and bytes encoded within the QR Code\n * @throws FormatException if the QR Code cannot be decoded\n * @throws ChecksumException if error correction fails\n */\n Decoder.prototype.decodeBitMatrix = function (bits, hints) {\n // Construct a parser and read version, error-correction level\n var parser = new BitMatrixParser(bits);\n var ex = null;\n try {\n return this.decodeBitMatrixParser(parser, hints);\n }\n catch (e /*: FormatException, ChecksumException*/) {\n ex = e;\n }\n try {\n // Revert the bit matrix\n parser.remask();\n // Will be attempting a mirrored reading of the version and format info.\n parser.setMirror(true);\n // Preemptively read the version.\n parser.readVersion();\n // Preemptively read the format information.\n parser.readFormatInformation();\n /*\n * Since we're here, this means we have successfully detected some kind\n * of version and format information when mirrored. This is a good sign,\n * that the QR code may be mirrored, and we should try once more with a\n * mirrored content.\n */\n // Prepare for a mirrored reading.\n parser.mirror();\n var result = this.decodeBitMatrixParser(parser, hints);\n // Success! Notify the caller that the code was mirrored.\n result.setOther(new QRCodeDecoderMetaData(true));\n return result;\n }\n catch (e /*FormatException | ChecksumException*/) {\n // Throw the exception from the original reading\n if (ex !== null) {\n throw ex;\n }\n throw e;\n }\n };\n Decoder.prototype.decodeBitMatrixParser = function (parser, hints) {\n var e_1, _a, e_2, _b;\n var version = parser.readVersion();\n var ecLevel = parser.readFormatInformation().getErrorCorrectionLevel();\n // Read codewords\n var codewords = parser.readCodewords();\n // Separate into data blocks\n var dataBlocks = DataBlock.getDataBlocks(codewords, version, ecLevel);\n // Count total number of data bytes\n var totalBytes = 0;\n try {\n for (var dataBlocks_1 = __values(dataBlocks), dataBlocks_1_1 = dataBlocks_1.next(); !dataBlocks_1_1.done; dataBlocks_1_1 = dataBlocks_1.next()) {\n var dataBlock = dataBlocks_1_1.value;\n totalBytes += dataBlock.getNumDataCodewords();\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (dataBlocks_1_1 && !dataBlocks_1_1.done && (_a = dataBlocks_1.return)) _a.call(dataBlocks_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n var resultBytes = new Uint8Array(totalBytes);\n var resultOffset = 0;\n try {\n // Error-correct and copy data blocks together into a stream of bytes\n for (var dataBlocks_2 = __values(dataBlocks), dataBlocks_2_1 = dataBlocks_2.next(); !dataBlocks_2_1.done; dataBlocks_2_1 = dataBlocks_2.next()) {\n var dataBlock = dataBlocks_2_1.value;\n var codewordBytes = dataBlock.getCodewords();\n var numDataCodewords = dataBlock.getNumDataCodewords();\n this.correctErrors(codewordBytes, numDataCodewords);\n for (var i = 0; i < numDataCodewords; i++) {\n resultBytes[resultOffset++] = codewordBytes[i];\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (dataBlocks_2_1 && !dataBlocks_2_1.done && (_b = dataBlocks_2.return)) _b.call(dataBlocks_2);\n }\n finally { if (e_2) throw e_2.error; }\n }\n // Decode the contents of that stream of bytes\n return DecodedBitStreamParser.decode(resultBytes, version, ecLevel, hints);\n };\n /**\n *Given data and error-correction codewords received, possibly corrupted by errors, attempts to\n * correct the errors in-place using Reed-Solomon error correction.
\n *\n * @param codewordBytes data and error correction codewords\n * @param numDataCodewords number of codewords that are data bytes\n * @throws ChecksumException if error correction fails\n */\n Decoder.prototype.correctErrors = function (codewordBytes, numDataCodewords /*int*/) {\n // const numCodewords = codewordBytes.length;\n // First read into an array of ints\n var codewordsInts = new Int32Array(codewordBytes);\n // TYPESCRIPTPORT: not realy necessary to transform to ints? could redesign everything to work with unsigned bytes?\n // const codewordsInts = new Int32Array(numCodewords)\n // for (let i = 0; i < numCodewords; i++) {\n // codewordsInts[i] = codewordBytes[i] & 0xFF\n // }\n try {\n this.rsDecoder.decode(codewordsInts, codewordBytes.length - numDataCodewords);\n }\n catch (ignored /*: ReedSolomonException*/) {\n throw new ChecksumException();\n }\n // Copy back into array of bytes -- only need to worry about the bytes that were data\n // We don't care about errors in the error-correction codewords\n for (var i = 0; i < numDataCodewords; i++) {\n codewordBytes[i] = /*(byte) */ codewordsInts[i];\n }\n };\n return Decoder;\n}());\nexport default Decoder;\n","/**\n *Encapsulates the parameters for one error-correction block in one symbol version.\n * This includes the number of data codewords, and the number of times a block with these\n * parameters is used consecutively in the QR code version's format.
\n */\nvar ECB = /** @class */ (function () {\n function ECB(count /*int*/, dataCodewords /*int*/) {\n this.count = count;\n this.dataCodewords = dataCodewords;\n }\n ECB.prototype.getCount = function () {\n return this.count;\n };\n ECB.prototype.getDataCodewords = function () {\n return this.dataCodewords;\n };\n return ECB;\n}());\nexport default ECB;\n","var __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/**\n *Encapsulates a set of error-correction blocks in one symbol version. Most versions will\n * use blocks of differing sizes within one version, so, this encapsulates the parameters for\n * each set of blocks. It also holds the number of error-correction codewords per block since it\n * will be the same across all blocks within one version.
\n */\nvar ECBlocks = /** @class */ (function () {\n function ECBlocks(ecCodewordsPerBlock /*int*/) {\n var ecBlocks = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n ecBlocks[_i - 1] = arguments[_i];\n }\n this.ecCodewordsPerBlock = ecCodewordsPerBlock;\n this.ecBlocks = ecBlocks;\n }\n ECBlocks.prototype.getECCodewordsPerBlock = function () {\n return this.ecCodewordsPerBlock;\n };\n ECBlocks.prototype.getNumBlocks = function () {\n var e_1, _a;\n var total = 0;\n var ecBlocks = this.ecBlocks;\n try {\n for (var ecBlocks_1 = __values(ecBlocks), ecBlocks_1_1 = ecBlocks_1.next(); !ecBlocks_1_1.done; ecBlocks_1_1 = ecBlocks_1.next()) {\n var ecBlock = ecBlocks_1_1.value;\n total += ecBlock.getCount();\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (ecBlocks_1_1 && !ecBlocks_1_1.done && (_a = ecBlocks_1.return)) _a.call(ecBlocks_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return total;\n };\n ECBlocks.prototype.getTotalECCodewords = function () {\n return this.ecCodewordsPerBlock * this.getNumBlocks();\n };\n ECBlocks.prototype.getECBlocks = function () {\n return this.ecBlocks;\n };\n return ECBlocks;\n}());\nexport default ECBlocks;\n","/*\n * Copyright 2007 ZXing authors\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/*namespace com.google.zxing.qrcode.decoder {*/\nimport ArgumentException from '../../ArgumentException';\nimport IllegalArgumentException from '../../IllegalArgumentException';\nexport var ErrorCorrectionLevelValues;\n(function (ErrorCorrectionLevelValues) {\n ErrorCorrectionLevelValues[ErrorCorrectionLevelValues[\"L\"] = 0] = \"L\";\n ErrorCorrectionLevelValues[ErrorCorrectionLevelValues[\"M\"] = 1] = \"M\";\n ErrorCorrectionLevelValues[ErrorCorrectionLevelValues[\"Q\"] = 2] = \"Q\";\n ErrorCorrectionLevelValues[ErrorCorrectionLevelValues[\"H\"] = 3] = \"H\";\n})(ErrorCorrectionLevelValues || (ErrorCorrectionLevelValues = {}));\n/**\n *See ISO 18004:2006, 6.5.1. This enum encapsulates the four error correction levels\n * defined by the QR code standard.
\n *\n * @author Sean Owen\n */\nvar ErrorCorrectionLevel = /** @class */ (function () {\n function ErrorCorrectionLevel(value, stringValue, bits /*int*/) {\n this.value = value;\n this.stringValue = stringValue;\n this.bits = bits;\n ErrorCorrectionLevel.FOR_BITS.set(bits, this);\n ErrorCorrectionLevel.FOR_VALUE.set(value, this);\n }\n ErrorCorrectionLevel.prototype.getValue = function () {\n return this.value;\n };\n ErrorCorrectionLevel.prototype.getBits = function () {\n return this.bits;\n };\n ErrorCorrectionLevel.fromString = function (s) {\n switch (s) {\n case 'L': return ErrorCorrectionLevel.L;\n case 'M': return ErrorCorrectionLevel.M;\n case 'Q': return ErrorCorrectionLevel.Q;\n case 'H': return ErrorCorrectionLevel.H;\n default: throw new ArgumentException(s + 'not available');\n }\n };\n ErrorCorrectionLevel.prototype.toString = function () {\n return this.stringValue;\n };\n ErrorCorrectionLevel.prototype.equals = function (o) {\n if (!(o instanceof ErrorCorrectionLevel)) {\n return false;\n }\n var other = o;\n return this.value === other.value;\n };\n /**\n * @param bits int containing the two bits encoding a QR Code's error correction level\n * @return ErrorCorrectionLevel representing the encoded error correction level\n */\n ErrorCorrectionLevel.forBits = function (bits /*int*/) {\n if (bits < 0 || bits >= ErrorCorrectionLevel.FOR_BITS.size) {\n throw new IllegalArgumentException();\n }\n return ErrorCorrectionLevel.FOR_BITS.get(bits);\n };\n ErrorCorrectionLevel.FOR_BITS = new Map();\n ErrorCorrectionLevel.FOR_VALUE = new Map();\n /** L = ~7% correction */\n ErrorCorrectionLevel.L = new ErrorCorrectionLevel(ErrorCorrectionLevelValues.L, 'L', 0x01);\n /** M = ~15% correction */\n ErrorCorrectionLevel.M = new ErrorCorrectionLevel(ErrorCorrectionLevelValues.M, 'M', 0x00);\n /** Q = ~25% correction */\n ErrorCorrectionLevel.Q = new ErrorCorrectionLevel(ErrorCorrectionLevelValues.Q, 'Q', 0x03);\n /** H = ~30% correction */\n ErrorCorrectionLevel.H = new ErrorCorrectionLevel(ErrorCorrectionLevelValues.H, 'H', 0x02);\n return ErrorCorrectionLevel;\n}());\nexport default ErrorCorrectionLevel;\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.qrcode.decoder {*/\nimport ErrorCorrectionLevel from './ErrorCorrectionLevel';\nimport Integer from '../../util/Integer';\n/**\n *Encapsulates a QR Code's format information, including the data mask used and\n * error correction level.
\n *\n * @author Sean Owen\n * @see DataMask\n * @see ErrorCorrectionLevel\n */\nvar FormatInformation = /** @class */ (function () {\n function FormatInformation(formatInfo /*int*/) {\n // Bits 3,4\n this.errorCorrectionLevel = ErrorCorrectionLevel.forBits((formatInfo >> 3) & 0x03);\n // Bottom 3 bits\n this.dataMask = /*(byte) */ (formatInfo & 0x07);\n }\n FormatInformation.numBitsDiffering = function (a /*int*/, b /*int*/) {\n return Integer.bitCount(a ^ b);\n };\n /**\n * @param maskedFormatInfo1 format info indicator, with mask still applied\n * @param maskedFormatInfo2 second copy of same info; both are checked at the same time\n * to establish best match\n * @return information about the format it specifies, or {@code null}\n * if doesn't seem to match any known pattern\n */\n FormatInformation.decodeFormatInformation = function (maskedFormatInfo1 /*int*/, maskedFormatInfo2 /*int*/) {\n var formatInfo = FormatInformation.doDecodeFormatInformation(maskedFormatInfo1, maskedFormatInfo2);\n if (formatInfo !== null) {\n return formatInfo;\n }\n // Should return null, but, some QR codes apparently\n // do not mask this info. Try again by actually masking the pattern\n // first\n return FormatInformation.doDecodeFormatInformation(maskedFormatInfo1 ^ FormatInformation.FORMAT_INFO_MASK_QR, maskedFormatInfo2 ^ FormatInformation.FORMAT_INFO_MASK_QR);\n };\n FormatInformation.doDecodeFormatInformation = function (maskedFormatInfo1 /*int*/, maskedFormatInfo2 /*int*/) {\n var e_1, _a;\n // Find the int in FORMAT_INFO_DECODE_LOOKUP with fewest bits differing\n var bestDifference = Number.MAX_SAFE_INTEGER;\n var bestFormatInfo = 0;\n try {\n for (var _b = __values(FormatInformation.FORMAT_INFO_DECODE_LOOKUP), _c = _b.next(); !_c.done; _c = _b.next()) {\n var decodeInfo = _c.value;\n var targetInfo = decodeInfo[0];\n if (targetInfo === maskedFormatInfo1 || targetInfo === maskedFormatInfo2) {\n // Found an exact match\n return new FormatInformation(decodeInfo[1]);\n }\n var bitsDifference = FormatInformation.numBitsDiffering(maskedFormatInfo1, targetInfo);\n if (bitsDifference < bestDifference) {\n bestFormatInfo = decodeInfo[1];\n bestDifference = bitsDifference;\n }\n if (maskedFormatInfo1 !== maskedFormatInfo2) {\n // also try the other option\n bitsDifference = FormatInformation.numBitsDiffering(maskedFormatInfo2, targetInfo);\n if (bitsDifference < bestDifference) {\n bestFormatInfo = decodeInfo[1];\n bestDifference = bitsDifference;\n }\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Hamming distance of the 32 masked codes is 7, by construction, so <= 3 bits\n // differing means we found a match\n if (bestDifference <= 3) {\n return new FormatInformation(bestFormatInfo);\n }\n return null;\n };\n FormatInformation.prototype.getErrorCorrectionLevel = function () {\n return this.errorCorrectionLevel;\n };\n FormatInformation.prototype.getDataMask = function () {\n return this.dataMask;\n };\n /*@Override*/\n FormatInformation.prototype.hashCode = function () {\n return (this.errorCorrectionLevel.getBits() << 3) | this.dataMask;\n };\n /*@Override*/\n FormatInformation.prototype.equals = function (o) {\n if (!(o instanceof FormatInformation)) {\n return false;\n }\n var other = o;\n return this.errorCorrectionLevel === other.errorCorrectionLevel &&\n this.dataMask === other.dataMask;\n };\n FormatInformation.FORMAT_INFO_MASK_QR = 0x5412;\n /**\n * See ISO 18004:2006, Annex C, Table C.1\n */\n FormatInformation.FORMAT_INFO_DECODE_LOOKUP = [\n Int32Array.from([0x5412, 0x00]),\n Int32Array.from([0x5125, 0x01]),\n Int32Array.from([0x5E7C, 0x02]),\n Int32Array.from([0x5B4B, 0x03]),\n Int32Array.from([0x45F9, 0x04]),\n Int32Array.from([0x40CE, 0x05]),\n Int32Array.from([0x4F97, 0x06]),\n Int32Array.from([0x4AA0, 0x07]),\n Int32Array.from([0x77C4, 0x08]),\n Int32Array.from([0x72F3, 0x09]),\n Int32Array.from([0x7DAA, 0x0A]),\n Int32Array.from([0x789D, 0x0B]),\n Int32Array.from([0x662F, 0x0C]),\n Int32Array.from([0x6318, 0x0D]),\n Int32Array.from([0x6C41, 0x0E]),\n Int32Array.from([0x6976, 0x0F]),\n Int32Array.from([0x1689, 0x10]),\n Int32Array.from([0x13BE, 0x11]),\n Int32Array.from([0x1CE7, 0x12]),\n Int32Array.from([0x19D0, 0x13]),\n Int32Array.from([0x0762, 0x14]),\n Int32Array.from([0x0255, 0x15]),\n Int32Array.from([0x0D0C, 0x16]),\n Int32Array.from([0x083B, 0x17]),\n Int32Array.from([0x355F, 0x18]),\n Int32Array.from([0x3068, 0x19]),\n Int32Array.from([0x3F31, 0x1A]),\n Int32Array.from([0x3A06, 0x1B]),\n Int32Array.from([0x24B4, 0x1C]),\n Int32Array.from([0x2183, 0x1D]),\n Int32Array.from([0x2EDA, 0x1E]),\n Int32Array.from([0x2BED, 0x1F]),\n ];\n return FormatInformation;\n}());\nexport default FormatInformation;\n","/*\n * Copyright 2007 ZXing authors\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 */\nimport IllegalArgumentException from '../../IllegalArgumentException';\nexport var ModeValues;\n(function (ModeValues) {\n ModeValues[ModeValues[\"TERMINATOR\"] = 0] = \"TERMINATOR\";\n ModeValues[ModeValues[\"NUMERIC\"] = 1] = \"NUMERIC\";\n ModeValues[ModeValues[\"ALPHANUMERIC\"] = 2] = \"ALPHANUMERIC\";\n ModeValues[ModeValues[\"STRUCTURED_APPEND\"] = 3] = \"STRUCTURED_APPEND\";\n ModeValues[ModeValues[\"BYTE\"] = 4] = \"BYTE\";\n ModeValues[ModeValues[\"ECI\"] = 5] = \"ECI\";\n ModeValues[ModeValues[\"KANJI\"] = 6] = \"KANJI\";\n ModeValues[ModeValues[\"FNC1_FIRST_POSITION\"] = 7] = \"FNC1_FIRST_POSITION\";\n ModeValues[ModeValues[\"FNC1_SECOND_POSITION\"] = 8] = \"FNC1_SECOND_POSITION\";\n /** See GBT 18284-2000; \"Hanzi\" is a transliteration of this mode name. */\n ModeValues[ModeValues[\"HANZI\"] = 9] = \"HANZI\";\n})(ModeValues || (ModeValues = {}));\n/**\n *See ISO 18004:2006, 6.4.1, Tables 2 and 3. This enum encapsulates the various modes in which\n * data can be encoded to bits in the QR code standard.
\n *\n * @author Sean Owen\n */\nvar Mode = /** @class */ (function () {\n function Mode(value, stringValue, characterCountBitsForVersions, bits /*int*/) {\n this.value = value;\n this.stringValue = stringValue;\n this.characterCountBitsForVersions = characterCountBitsForVersions;\n this.bits = bits;\n Mode.FOR_BITS.set(bits, this);\n Mode.FOR_VALUE.set(value, this);\n }\n /**\n * @param bits four bits encoding a QR Code data mode\n * @return Mode encoded by these bits\n * @throws IllegalArgumentException if bits do not correspond to a known mode\n */\n Mode.forBits = function (bits /*int*/) {\n var mode = Mode.FOR_BITS.get(bits);\n if (undefined === mode) {\n throw new IllegalArgumentException();\n }\n return mode;\n };\n /**\n * @param version version in question\n * @return number of bits used, in this QR Code symbol {@link Version}, to encode the\n * count of characters that will follow encoded in this Mode\n */\n Mode.prototype.getCharacterCountBits = function (version) {\n var versionNumber = version.getVersionNumber();\n var offset;\n if (versionNumber <= 9) {\n offset = 0;\n }\n else if (versionNumber <= 26) {\n offset = 1;\n }\n else {\n offset = 2;\n }\n return this.characterCountBitsForVersions[offset];\n };\n Mode.prototype.getValue = function () {\n return this.value;\n };\n Mode.prototype.getBits = function () {\n return this.bits;\n };\n Mode.prototype.equals = function (o) {\n if (!(o instanceof Mode)) {\n return false;\n }\n var other = o;\n return this.value === other.value;\n };\n Mode.prototype.toString = function () {\n return this.stringValue;\n };\n Mode.FOR_BITS = new Map();\n Mode.FOR_VALUE = new Map();\n Mode.TERMINATOR = new Mode(ModeValues.TERMINATOR, 'TERMINATOR', Int32Array.from([0, 0, 0]), 0x00); // Not really a mode...\n Mode.NUMERIC = new Mode(ModeValues.NUMERIC, 'NUMERIC', Int32Array.from([10, 12, 14]), 0x01);\n Mode.ALPHANUMERIC = new Mode(ModeValues.ALPHANUMERIC, 'ALPHANUMERIC', Int32Array.from([9, 11, 13]), 0x02);\n Mode.STRUCTURED_APPEND = new Mode(ModeValues.STRUCTURED_APPEND, 'STRUCTURED_APPEND', Int32Array.from([0, 0, 0]), 0x03); // Not supported\n Mode.BYTE = new Mode(ModeValues.BYTE, 'BYTE', Int32Array.from([8, 16, 16]), 0x04);\n Mode.ECI = new Mode(ModeValues.ECI, 'ECI', Int32Array.from([0, 0, 0]), 0x07); // character counts don't apply\n Mode.KANJI = new Mode(ModeValues.KANJI, 'KANJI', Int32Array.from([8, 10, 12]), 0x08);\n Mode.FNC1_FIRST_POSITION = new Mode(ModeValues.FNC1_FIRST_POSITION, 'FNC1_FIRST_POSITION', Int32Array.from([0, 0, 0]), 0x05);\n Mode.FNC1_SECOND_POSITION = new Mode(ModeValues.FNC1_SECOND_POSITION, 'FNC1_SECOND_POSITION', Int32Array.from([0, 0, 0]), 0x09);\n /** See GBT 18284-2000; \"Hanzi\" is a transliteration of this mode name. */\n Mode.HANZI = new Mode(ModeValues.HANZI, 'HANZI', Int32Array.from([8, 10, 12]), 0x0D);\n return Mode;\n}());\nexport default Mode;\n","/*\n * Copyright 2013 ZXing authors\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 * Meta-data container for QR Code decoding. Instances of this class may be used to convey information back to the\n * decoding caller. Callers are expected to process this.\n *\n * @see com.google.zxing.common.DecoderResult#getOther()\n */\nvar QRCodeDecoderMetaData = /** @class */ (function () {\n function QRCodeDecoderMetaData(mirrored) {\n this.mirrored = mirrored;\n }\n /**\n * @return true if the QR Code was mirrored.\n */\n QRCodeDecoderMetaData.prototype.isMirrored = function () {\n return this.mirrored;\n };\n /**\n * Apply the result points' order correction due to mirroring.\n *\n * @param points Array of points to apply mirror correction to.\n */\n QRCodeDecoderMetaData.prototype.applyMirroredCorrection = function (points) {\n if (!this.mirrored || points === null || points.length < 3) {\n return;\n }\n var bottomLeft = points[0];\n points[0] = points[2];\n points[2] = bottomLeft;\n // No need to 'fix' top-left and alignment pattern.\n };\n return QRCodeDecoderMetaData;\n}());\nexport default QRCodeDecoderMetaData;\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.qrcode.decoder {*/\nimport BitMatrix from '../../common/BitMatrix';\nimport FormatInformation from './FormatInformation';\nimport ECBlocks from './ECBlocks';\nimport ECB from './ECB';\nimport FormatException from '../../FormatException';\nimport IllegalArgumentException from '../../IllegalArgumentException';\n/**\n * See ISO 18004:2006 Annex D\n *\n * @author Sean Owen\n */\nvar Version = /** @class */ (function () {\n function Version(versionNumber /*int*/, alignmentPatternCenters) {\n var e_1, _a;\n var ecBlocks = [];\n for (var _i = 2; _i < arguments.length; _i++) {\n ecBlocks[_i - 2] = arguments[_i];\n }\n this.versionNumber = versionNumber;\n this.alignmentPatternCenters = alignmentPatternCenters;\n this.ecBlocks = ecBlocks;\n var total = 0;\n var ecCodewords = ecBlocks[0].getECCodewordsPerBlock();\n var ecbArray = ecBlocks[0].getECBlocks();\n try {\n for (var ecbArray_1 = __values(ecbArray), ecbArray_1_1 = ecbArray_1.next(); !ecbArray_1_1.done; ecbArray_1_1 = ecbArray_1.next()) {\n var ecBlock = ecbArray_1_1.value;\n total += ecBlock.getCount() * (ecBlock.getDataCodewords() + ecCodewords);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (ecbArray_1_1 && !ecbArray_1_1.done && (_a = ecbArray_1.return)) _a.call(ecbArray_1);\n }\n finally { if (e_1) throw e_1.error; }\n }\n this.totalCodewords = total;\n }\n Version.prototype.getVersionNumber = function () {\n return this.versionNumber;\n };\n Version.prototype.getAlignmentPatternCenters = function () {\n return this.alignmentPatternCenters;\n };\n Version.prototype.getTotalCodewords = function () {\n return this.totalCodewords;\n };\n Version.prototype.getDimensionForVersion = function () {\n return 17 + 4 * this.versionNumber;\n };\n Version.prototype.getECBlocksForLevel = function (ecLevel) {\n return this.ecBlocks[ecLevel.getValue()];\n // TYPESCRIPTPORT: original was using ordinal, and using the order of levels as defined in ErrorCorrectionLevel enum (LMQH)\n // I will use the direct value from ErrorCorrectionLevelValues enum which in typescript goes to a number\n };\n /**\n *Deduces version information purely from QR Code dimensions.
\n *\n * @param dimension dimension in modules\n * @return Version for a QR Code of that dimension\n * @throws FormatException if dimension is not 1 mod 4\n */\n Version.getProvisionalVersionForDimension = function (dimension /*int*/) {\n if (dimension % 4 !== 1) {\n throw new FormatException();\n }\n try {\n return this.getVersionForNumber((dimension - 17) / 4);\n }\n catch (ignored /*: IllegalArgumentException*/) {\n throw new FormatException();\n }\n };\n Version.getVersionForNumber = function (versionNumber /*int*/) {\n if (versionNumber < 1 || versionNumber > 40) {\n throw new IllegalArgumentException();\n }\n return Version.VERSIONS[versionNumber - 1];\n };\n Version.decodeVersionInformation = function (versionBits /*int*/) {\n var bestDifference = Number.MAX_SAFE_INTEGER;\n var bestVersion = 0;\n for (var i = 0; i < Version.VERSION_DECODE_INFO.length; i++) {\n var targetVersion = Version.VERSION_DECODE_INFO[i];\n // Do the version info bits match exactly? done.\n if (targetVersion === versionBits) {\n return Version.getVersionForNumber(i + 7);\n }\n // Otherwise see if this is the closest to a real version info bit string\n // we have seen so far\n var bitsDifference = FormatInformation.numBitsDiffering(versionBits, targetVersion);\n if (bitsDifference < bestDifference) {\n bestVersion = i + 7;\n bestDifference = bitsDifference;\n }\n }\n // We can tolerate up to 3 bits of error since no two version info codewords will\n // differ in less than 8 bits.\n if (bestDifference <= 3) {\n return Version.getVersionForNumber(bestVersion);\n }\n // If we didn't find a close enough match, fail\n return null;\n };\n /**\n * See ISO 18004:2006 Annex E\n */\n Version.prototype.buildFunctionPattern = function () {\n var dimension = this.getDimensionForVersion();\n var bitMatrix = new BitMatrix(dimension);\n // Top left finder pattern + separator + format\n bitMatrix.setRegion(0, 0, 9, 9);\n // Top right finder pattern + separator + format\n bitMatrix.setRegion(dimension - 8, 0, 8, 9);\n // Bottom left finder pattern + separator + format\n bitMatrix.setRegion(0, dimension - 8, 9, 8);\n // Alignment patterns\n var max = this.alignmentPatternCenters.length;\n for (var x = 0; x < max; x++) {\n var i = this.alignmentPatternCenters[x] - 2;\n for (var y = 0; y < max; y++) {\n if ((x === 0 && (y === 0 || y === max - 1)) || (x === max - 1 && y === 0)) {\n // No alignment patterns near the three finder patterns\n continue;\n }\n bitMatrix.setRegion(this.alignmentPatternCenters[y] - 2, i, 5, 5);\n }\n }\n // Vertical timing pattern\n bitMatrix.setRegion(6, 9, 1, dimension - 17);\n // Horizontal timing pattern\n bitMatrix.setRegion(9, 6, dimension - 17, 1);\n if (this.versionNumber > 6) {\n // Version info, top right\n bitMatrix.setRegion(dimension - 11, 0, 3, 6);\n // Version info, bottom left\n bitMatrix.setRegion(0, dimension - 11, 6, 3);\n }\n return bitMatrix;\n };\n /*@Override*/\n Version.prototype.toString = function () {\n return '' + this.versionNumber;\n };\n /**\n * See ISO 18004:2006 Annex D.\n * Element i represents the raw version bits that specify version i + 7\n */\n Version.VERSION_DECODE_INFO = Int32Array.from([\n 0x07C94, 0x085BC, 0x09A99, 0x0A4D3, 0x0BBF6,\n 0x0C762, 0x0D847, 0x0E60D, 0x0F928, 0x10B78,\n 0x1145D, 0x12A17, 0x13532, 0x149A6, 0x15683,\n 0x168C9, 0x177EC, 0x18EC4, 0x191E1, 0x1AFAB,\n 0x1B08E, 0x1CC1A, 0x1D33F, 0x1ED75, 0x1F250,\n 0x209D5, 0x216F0, 0x228BA, 0x2379F, 0x24B0B,\n 0x2542E, 0x26A64, 0x27541, 0x28C69\n ]);\n /**\n * See ISO 18004:2006 6.5.1 Table 9\n */\n Version.VERSIONS = [\n new Version(1, new Int32Array(0), new ECBlocks(7, new ECB(1, 19)), new ECBlocks(10, new ECB(1, 16)), new ECBlocks(13, new ECB(1, 13)), new ECBlocks(17, new ECB(1, 9))),\n new Version(2, Int32Array.from([6, 18]), new ECBlocks(10, new ECB(1, 34)), new ECBlocks(16, new ECB(1, 28)), new ECBlocks(22, new ECB(1, 22)), new ECBlocks(28, new ECB(1, 16))),\n new Version(3, Int32Array.from([6, 22]), new ECBlocks(15, new ECB(1, 55)), new ECBlocks(26, new ECB(1, 44)), new ECBlocks(18, new ECB(2, 17)), new ECBlocks(22, new ECB(2, 13))),\n new Version(4, Int32Array.from([6, 26]), new ECBlocks(20, new ECB(1, 80)), new ECBlocks(18, new ECB(2, 32)), new ECBlocks(26, new ECB(2, 24)), new ECBlocks(16, new ECB(4, 9))),\n new Version(5, Int32Array.from([6, 30]), new ECBlocks(26, new ECB(1, 108)), new ECBlocks(24, new ECB(2, 43)), new ECBlocks(18, new ECB(2, 15), new ECB(2, 16)), new ECBlocks(22, new ECB(2, 11), new ECB(2, 12))),\n new Version(6, Int32Array.from([6, 34]), new ECBlocks(18, new ECB(2, 68)), new ECBlocks(16, new ECB(4, 27)), new ECBlocks(24, new ECB(4, 19)), new ECBlocks(28, new ECB(4, 15))),\n new Version(7, Int32Array.from([6, 22, 38]), new ECBlocks(20, new ECB(2, 78)), new ECBlocks(18, new ECB(4, 31)), new ECBlocks(18, new ECB(2, 14), new ECB(4, 15)), new ECBlocks(26, new ECB(4, 13), new ECB(1, 14))),\n new Version(8, Int32Array.from([6, 24, 42]), new ECBlocks(24, new ECB(2, 97)), new ECBlocks(22, new ECB(2, 38), new ECB(2, 39)), new ECBlocks(22, new ECB(4, 18), new ECB(2, 19)), new ECBlocks(26, new ECB(4, 14), new ECB(2, 15))),\n new Version(9, Int32Array.from([6, 26, 46]), new ECBlocks(30, new ECB(2, 116)), new ECBlocks(22, new ECB(3, 36), new ECB(2, 37)), new ECBlocks(20, new ECB(4, 16), new ECB(4, 17)), new ECBlocks(24, new ECB(4, 12), new ECB(4, 13))),\n new Version(10, Int32Array.from([6, 28, 50]), new ECBlocks(18, new ECB(2, 68), new ECB(2, 69)), new ECBlocks(26, new ECB(4, 43), new ECB(1, 44)), new ECBlocks(24, new ECB(6, 19), new ECB(2, 20)), new ECBlocks(28, new ECB(6, 15), new ECB(2, 16))),\n new Version(11, Int32Array.from([6, 30, 54]), new ECBlocks(20, new ECB(4, 81)), new ECBlocks(30, new ECB(1, 50), new ECB(4, 51)), new ECBlocks(28, new ECB(4, 22), new ECB(4, 23)), new ECBlocks(24, new ECB(3, 12), new ECB(8, 13))),\n new Version(12, Int32Array.from([6, 32, 58]), new ECBlocks(24, new ECB(2, 92), new ECB(2, 93)), new ECBlocks(22, new ECB(6, 36), new ECB(2, 37)), new ECBlocks(26, new ECB(4, 20), new ECB(6, 21)), new ECBlocks(28, new ECB(7, 14), new ECB(4, 15))),\n new Version(13, Int32Array.from([6, 34, 62]), new ECBlocks(26, new ECB(4, 107)), new ECBlocks(22, new ECB(8, 37), new ECB(1, 38)), new ECBlocks(24, new ECB(8, 20), new ECB(4, 21)), new ECBlocks(22, new ECB(12, 11), new ECB(4, 12))),\n new Version(14, Int32Array.from([6, 26, 46, 66]), new ECBlocks(30, new ECB(3, 115), new ECB(1, 116)), new ECBlocks(24, new ECB(4, 40), new ECB(5, 41)), new ECBlocks(20, new ECB(11, 16), new ECB(5, 17)), new ECBlocks(24, new ECB(11, 12), new ECB(5, 13))),\n new Version(15, Int32Array.from([6, 26, 48, 70]), new ECBlocks(22, new ECB(5, 87), new ECB(1, 88)), new ECBlocks(24, new ECB(5, 41), new ECB(5, 42)), new ECBlocks(30, new ECB(5, 24), new ECB(7, 25)), new ECBlocks(24, new ECB(11, 12), new ECB(7, 13))),\n new Version(16, Int32Array.from([6, 26, 50, 74]), new ECBlocks(24, new ECB(5, 98), new ECB(1, 99)), new ECBlocks(28, new ECB(7, 45), new ECB(3, 46)), new ECBlocks(24, new ECB(15, 19), new ECB(2, 20)), new ECBlocks(30, new ECB(3, 15), new ECB(13, 16))),\n new Version(17, Int32Array.from([6, 30, 54, 78]), new ECBlocks(28, new ECB(1, 107), new ECB(5, 108)), new ECBlocks(28, new ECB(10, 46), new ECB(1, 47)), new ECBlocks(28, new ECB(1, 22), new ECB(15, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(17, 15))),\n new Version(18, Int32Array.from([6, 30, 56, 82]), new ECBlocks(30, new ECB(5, 120), new ECB(1, 121)), new ECBlocks(26, new ECB(9, 43), new ECB(4, 44)), new ECBlocks(28, new ECB(17, 22), new ECB(1, 23)), new ECBlocks(28, new ECB(2, 14), new ECB(19, 15))),\n new Version(19, Int32Array.from([6, 30, 58, 86]), new ECBlocks(28, new ECB(3, 113), new ECB(4, 114)), new ECBlocks(26, new ECB(3, 44), new ECB(11, 45)), new ECBlocks(26, new ECB(17, 21), new ECB(4, 22)), new ECBlocks(26, new ECB(9, 13), new ECB(16, 14))),\n new Version(20, Int32Array.from([6, 34, 62, 90]), new ECBlocks(28, new ECB(3, 107), new ECB(5, 108)), new ECBlocks(26, new ECB(3, 41), new ECB(13, 42)), new ECBlocks(30, new ECB(15, 24), new ECB(5, 25)), new ECBlocks(28, new ECB(15, 15), new ECB(10, 16))),\n new Version(21, Int32Array.from([6, 28, 50, 72, 94]), new ECBlocks(28, new ECB(4, 116), new ECB(4, 117)), new ECBlocks(26, new ECB(17, 42)), new ECBlocks(28, new ECB(17, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(19, 16), new ECB(6, 17))),\n new Version(22, Int32Array.from([6, 26, 50, 74, 98]), new ECBlocks(28, new ECB(2, 111), new ECB(7, 112)), new ECBlocks(28, new ECB(17, 46)), new ECBlocks(30, new ECB(7, 24), new ECB(16, 25)), new ECBlocks(24, new ECB(34, 13))),\n new Version(23, Int32Array.from([6, 30, 54, 78, 102]), new ECBlocks(30, new ECB(4, 121), new ECB(5, 122)), new ECBlocks(28, new ECB(4, 47), new ECB(14, 48)), new ECBlocks(30, new ECB(11, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(16, 15), new ECB(14, 16))),\n new Version(24, Int32Array.from([6, 28, 54, 80, 106]), new ECBlocks(30, new ECB(6, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(6, 45), new ECB(14, 46)), new ECBlocks(30, new ECB(11, 24), new ECB(16, 25)), new ECBlocks(30, new ECB(30, 16), new ECB(2, 17))),\n new Version(25, Int32Array.from([6, 32, 58, 84, 110]), new ECBlocks(26, new ECB(8, 106), new ECB(4, 107)), new ECBlocks(28, new ECB(8, 47), new ECB(13, 48)), new ECBlocks(30, new ECB(7, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(13, 16))),\n new Version(26, Int32Array.from([6, 30, 58, 86, 114]), new ECBlocks(28, new ECB(10, 114), new ECB(2, 115)), new ECBlocks(28, new ECB(19, 46), new ECB(4, 47)), new ECBlocks(28, new ECB(28, 22), new ECB(6, 23)), new ECBlocks(30, new ECB(33, 16), new ECB(4, 17))),\n new Version(27, Int32Array.from([6, 34, 62, 90, 118]), new ECBlocks(30, new ECB(8, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(22, 45), new ECB(3, 46)), new ECBlocks(30, new ECB(8, 23), new ECB(26, 24)), new ECBlocks(30, new ECB(12, 15), new ECB(28, 16))),\n new Version(28, Int32Array.from([6, 26, 50, 74, 98, 122]), new ECBlocks(30, new ECB(3, 117), new ECB(10, 118)), new ECBlocks(28, new ECB(3, 45), new ECB(23, 46)), new ECBlocks(30, new ECB(4, 24), new ECB(31, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(31, 16))),\n new Version(29, Int32Array.from([6, 30, 54, 78, 102, 126]), new ECBlocks(30, new ECB(7, 116), new ECB(7, 117)), new ECBlocks(28, new ECB(21, 45), new ECB(7, 46)), new ECBlocks(30, new ECB(1, 23), new ECB(37, 24)), new ECBlocks(30, new ECB(19, 15), new ECB(26, 16))),\n new Version(30, Int32Array.from([6, 26, 52, 78, 104, 130]), new ECBlocks(30, new ECB(5, 115), new ECB(10, 116)), new ECBlocks(28, new ECB(19, 47), new ECB(10, 48)), new ECBlocks(30, new ECB(15, 24), new ECB(25, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(25, 16))),\n new Version(31, Int32Array.from([6, 30, 56, 82, 108, 134]), new ECBlocks(30, new ECB(13, 115), new ECB(3, 116)), new ECBlocks(28, new ECB(2, 46), new ECB(29, 47)), new ECBlocks(30, new ECB(42, 24), new ECB(1, 25)), new ECBlocks(30, new ECB(23, 15), new ECB(28, 16))),\n new Version(32, Int32Array.from([6, 34, 60, 86, 112, 138]), new ECBlocks(30, new ECB(17, 115)), new ECBlocks(28, new ECB(10, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(10, 24), new ECB(35, 25)), new ECBlocks(30, new ECB(19, 15), new ECB(35, 16))),\n new Version(33, Int32Array.from([6, 30, 58, 86, 114, 142]), new ECBlocks(30, new ECB(17, 115), new ECB(1, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(21, 47)), new ECBlocks(30, new ECB(29, 24), new ECB(19, 25)), new ECBlocks(30, new ECB(11, 15), new ECB(46, 16))),\n new Version(34, Int32Array.from([6, 34, 62, 90, 118, 146]), new ECBlocks(30, new ECB(13, 115), new ECB(6, 116)), new ECBlocks(28, new ECB(14, 46), new ECB(23, 47)), new ECBlocks(30, new ECB(44, 24), new ECB(7, 25)), new ECBlocks(30, new ECB(59, 16), new ECB(1, 17))),\n new Version(35, Int32Array.from([6, 30, 54, 78, 102, 126, 150]), new ECBlocks(30, new ECB(12, 121), new ECB(7, 122)), new ECBlocks(28, new ECB(12, 47), new ECB(26, 48)), new ECBlocks(30, new ECB(39, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(22, 15), new ECB(41, 16))),\n new Version(36, Int32Array.from([6, 24, 50, 76, 102, 128, 154]), new ECBlocks(30, new ECB(6, 121), new ECB(14, 122)), new ECBlocks(28, new ECB(6, 47), new ECB(34, 48)), new ECBlocks(30, new ECB(46, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(2, 15), new ECB(64, 16))),\n new Version(37, Int32Array.from([6, 28, 54, 80, 106, 132, 158]), new ECBlocks(30, new ECB(17, 122), new ECB(4, 123)), new ECBlocks(28, new ECB(29, 46), new ECB(14, 47)), new ECBlocks(30, new ECB(49, 24), new ECB(10, 25)), new ECBlocks(30, new ECB(24, 15), new ECB(46, 16))),\n new Version(38, Int32Array.from([6, 32, 58, 84, 110, 136, 162]), new ECBlocks(30, new ECB(4, 122), new ECB(18, 123)), new ECBlocks(28, new ECB(13, 46), new ECB(32, 47)), new ECBlocks(30, new ECB(48, 24), new ECB(14, 25)), new ECBlocks(30, new ECB(42, 15), new ECB(32, 16))),\n new Version(39, Int32Array.from([6, 26, 54, 82, 110, 138, 166]), new ECBlocks(30, new ECB(20, 117), new ECB(4, 118)), new ECBlocks(28, new ECB(40, 47), new ECB(7, 48)), new ECBlocks(30, new ECB(43, 24), new ECB(22, 25)), new ECBlocks(30, new ECB(10, 15), new ECB(67, 16))),\n new Version(40, Int32Array.from([6, 30, 58, 86, 114, 142, 170]), new ECBlocks(30, new ECB(19, 118), new ECB(6, 119)), new ECBlocks(28, new ECB(18, 47), new ECB(31, 48)), new ECBlocks(30, new ECB(34, 24), new ECB(34, 25)), new ECBlocks(30, new ECB(20, 15), new ECB(61, 16)))\n ];\n return Version;\n}());\nexport default Version;\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/*namespace com.google.zxing.qrcode.detector {*/\nimport ResultPoint from '../../ResultPoint';\n/**\n *Encapsulates an alignment pattern, which are the smaller square patterns found in\n * all but the simplest QR Codes.
\n *\n * @author Sean Owen\n */\nvar AlignmentPattern = /** @class */ (function (_super) {\n __extends(AlignmentPattern, _super);\n function AlignmentPattern(posX /*float*/, posY /*float*/, estimatedModuleSize /*float*/) {\n var _this = _super.call(this, posX, posY) || this;\n _this.estimatedModuleSize = estimatedModuleSize;\n return _this;\n }\n /**\n *Determines if this alignment pattern \"about equals\" an alignment pattern at the stated\n * position and size -- meaning, it is at nearly the same center with nearly the same size.
\n */\n AlignmentPattern.prototype.aboutEquals = function (moduleSize /*float*/, i /*float*/, j /*float*/) {\n if (Math.abs(i - this.getY()) <= moduleSize && Math.abs(j - this.getX()) <= moduleSize) {\n var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);\n return moduleSizeDiff <= 1.0 || moduleSizeDiff <= this.estimatedModuleSize;\n }\n return false;\n };\n /**\n * Combines this object's current estimate of a finder pattern position and module size\n * with a new estimate. It returns a new {@code FinderPattern} containing an average of the two.\n */\n AlignmentPattern.prototype.combineEstimate = function (i /*float*/, j /*float*/, newModuleSize /*float*/) {\n var combinedX = (this.getX() + j) / 2.0;\n var combinedY = (this.getY() + i) / 2.0;\n var combinedModuleSize = (this.estimatedModuleSize + newModuleSize) / 2.0;\n return new AlignmentPattern(combinedX, combinedY, combinedModuleSize);\n };\n return AlignmentPattern;\n}(ResultPoint));\nexport default AlignmentPattern;\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\nimport AlignmentPattern from './AlignmentPattern';\nimport NotFoundException from '../../NotFoundException';\n/*import java.util.ArrayList;*/\n/*import java.util.List;*/\n/**\n *This class attempts to find alignment patterns in a QR Code. Alignment patterns look like finder\n * patterns but are smaller and appear at regular intervals throughout the image.
\n *\n *At the moment this only looks for the bottom-right alignment pattern.
\n *\n *This is mostly a simplified copy of {@link FinderPatternFinder}. It is copied,\n * pasted and stripped down here for maximum performance but does unfortunately duplicate\n * some code.
\n *\n *This class is thread-safe but not reentrant. Each thread must allocate its own object.
\n *\n * @author Sean Owen\n */\nvar AlignmentPatternFinder = /** @class */ (function () {\n /**\n *Creates a finder that will look in a portion of the whole image.
\n *\n * @param image image to search\n * @param startX left column from which to start searching\n * @param startY top row from which to start searching\n * @param width width of region to search\n * @param height height of region to search\n * @param moduleSize estimated module size so far\n */\n function AlignmentPatternFinder(image, startX /*int*/, startY /*int*/, width /*int*/, height /*int*/, moduleSize /*float*/, resultPointCallback) {\n this.image = image;\n this.startX = startX;\n this.startY = startY;\n this.width = width;\n this.height = height;\n this.moduleSize = moduleSize;\n this.resultPointCallback = resultPointCallback;\n this.possibleCenters = []; // new ArrayThis method attempts to find the bottom-right alignment pattern in the image. It is a bit messy since\n * it's pretty performance-critical and so is written to be fast foremost.
\n *\n * @return {@link AlignmentPattern} if found\n * @throws NotFoundException if not found\n */\n AlignmentPatternFinder.prototype.find = function () {\n var startX = this.startX;\n var height = this.height;\n var width = this.width;\n var maxJ = startX + width;\n var middleI = this.startY + (height / 2);\n // We are looking for black/white/black modules in 1:1:1 ratio\n // this tracks the number of black/white/black modules seen so far\n var stateCount = new Int32Array(3);\n var image = this.image;\n for (var iGen = 0; iGen < height; iGen++) {\n // Search from middle outwards\n var i = middleI + ((iGen & 0x01) === 0 ? Math.floor((iGen + 1) / 2) : -Math.floor((iGen + 1) / 2));\n stateCount[0] = 0;\n stateCount[1] = 0;\n stateCount[2] = 0;\n var j = startX;\n // Burn off leading white pixels before anything else; if we start in the middle of\n // a white run, it doesn't make sense to count its length, since we don't know if the\n // white run continued to the left of the start point\n while (j < maxJ && !image.get(j, i)) {\n j++;\n }\n var currentState = 0;\n while (j < maxJ) {\n if (image.get(j, i)) {\n // Black pixel\n if (currentState === 1) { // Counting black pixels\n stateCount[1]++;\n }\n else { // Counting white pixels\n if (currentState === 2) { // A winner?\n if (this.foundPatternCross(stateCount)) { // Yes\n var confirmed = this.handlePossibleCenter(stateCount, i, j);\n if (confirmed !== null) {\n return confirmed;\n }\n }\n stateCount[0] = stateCount[2];\n stateCount[1] = 1;\n stateCount[2] = 0;\n currentState = 1;\n }\n else {\n stateCount[++currentState]++;\n }\n }\n }\n else { // White pixel\n if (currentState === 1) { // Counting black pixels\n currentState++;\n }\n stateCount[currentState]++;\n }\n j++;\n }\n if (this.foundPatternCross(stateCount)) {\n var confirmed = this.handlePossibleCenter(stateCount, i, maxJ);\n if (confirmed !== null) {\n return confirmed;\n }\n }\n }\n // Hmm, nothing we saw was observed and confirmed twice. If we had\n // any guess at all, return it.\n if (this.possibleCenters.length !== 0) {\n return this.possibleCenters[0];\n }\n throw new NotFoundException();\n };\n /**\n * Given a count of black/white/black pixels just seen and an end position,\n * figures the location of the center of this black/white/black run.\n */\n AlignmentPatternFinder.centerFromEnd = function (stateCount, end /*int*/) {\n return (end - stateCount[2]) - stateCount[1] / 2.0;\n };\n /**\n * @param stateCount count of black/white/black pixels just read\n * @return true iff the proportions of the counts is close enough to the 1/1/1 ratios\n * used by alignment patterns to be considered a match\n */\n AlignmentPatternFinder.prototype.foundPatternCross = function (stateCount) {\n var moduleSize = this.moduleSize;\n var maxVariance = moduleSize / 2.0;\n for (var i = 0; i < 3; i++) {\n if (Math.abs(moduleSize - stateCount[i]) >= maxVariance) {\n return false;\n }\n }\n return true;\n };\n /**\n *After a horizontal scan finds a potential alignment pattern, this method\n * \"cross-checks\" by scanning down vertically through the center of the possible\n * alignment pattern to see if the same proportion is detected.
\n *\n * @param startI row where an alignment pattern was detected\n * @param centerJ center of the section that appears to cross an alignment pattern\n * @param maxCount maximum reasonable number of modules that should be\n * observed in any reading state, based on the results of the horizontal scan\n * @return vertical center of alignment pattern, or {@link Float#NaN} if not found\n */\n AlignmentPatternFinder.prototype.crossCheckVertical = function (startI /*int*/, centerJ /*int*/, maxCount /*int*/, originalStateCountTotal /*int*/) {\n var image = this.image;\n var maxI = image.getHeight();\n var stateCount = this.crossCheckStateCount;\n stateCount[0] = 0;\n stateCount[1] = 0;\n stateCount[2] = 0;\n // Start counting up from center\n var i = startI;\n while (i >= 0 && image.get(centerJ, i) && stateCount[1] <= maxCount) {\n stateCount[1]++;\n i--;\n }\n // If already too many modules in this state or ran off the edge:\n if (i < 0 || stateCount[1] > maxCount) {\n return NaN;\n }\n while (i >= 0 && !image.get(centerJ, i) && stateCount[0] <= maxCount) {\n stateCount[0]++;\n i--;\n }\n if (stateCount[0] > maxCount) {\n return NaN;\n }\n // Now also count down from center\n i = startI + 1;\n while (i < maxI && image.get(centerJ, i) && stateCount[1] <= maxCount) {\n stateCount[1]++;\n i++;\n }\n if (i === maxI || stateCount[1] > maxCount) {\n return NaN;\n }\n while (i < maxI && !image.get(centerJ, i) && stateCount[2] <= maxCount) {\n stateCount[2]++;\n i++;\n }\n if (stateCount[2] > maxCount) {\n return NaN;\n }\n var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];\n if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {\n return NaN;\n }\n return this.foundPatternCross(stateCount) ? AlignmentPatternFinder.centerFromEnd(stateCount, i) : NaN;\n };\n /**\n *This is called when a horizontal scan finds a possible alignment pattern. It will\n * cross check with a vertical scan, and if successful, will see if this pattern had been\n * found on a previous horizontal scan. If so, we consider it confirmed and conclude we have\n * found the alignment pattern.
\n *\n * @param stateCount reading state module counts from horizontal scan\n * @param i row where alignment pattern may be found\n * @param j end of possible alignment pattern in row\n * @return {@link AlignmentPattern} if we have found the same pattern twice, or null if not\n */\n AlignmentPatternFinder.prototype.handlePossibleCenter = function (stateCount, i /*int*/, j /*int*/) {\n var e_1, _a;\n var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2];\n var centerJ = AlignmentPatternFinder.centerFromEnd(stateCount, j);\n var centerI = this.crossCheckVertical(i, /*(int) */ centerJ, 2 * stateCount[1], stateCountTotal);\n if (!isNaN(centerI)) {\n var estimatedModuleSize = (stateCount[0] + stateCount[1] + stateCount[2]) / 3.0;\n try {\n for (var _b = __values(this.possibleCenters), _c = _b.next(); !_c.done; _c = _b.next()) {\n var center = _c.value;\n // Look for about the same center and module size:\n if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {\n return center.combineEstimate(centerI, centerJ, estimatedModuleSize);\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n // Hadn't found this before; save it\n var point = new AlignmentPattern(centerJ, centerI, estimatedModuleSize);\n this.possibleCenters.push(point);\n if (this.resultPointCallback !== null && this.resultPointCallback !== undefined) {\n this.resultPointCallback.foundPossibleResultPoint(point);\n }\n }\n return null;\n };\n return AlignmentPatternFinder;\n}());\nexport default AlignmentPatternFinder;\n","/*\n * Copyright 2007 ZXing authors\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 */\nimport MathUtils from '../../common/detector/MathUtils';\nimport DetectorResult from '../../common/DetectorResult';\n// import GridSampler from '../../common/GridSampler';\nimport GridSamplerInstance from '../../common/GridSamplerInstance';\nimport PerspectiveTransform from '../../common/PerspectiveTransform';\nimport DecodeHintType from '../../DecodeHintType';\nimport NotFoundException from '../../NotFoundException';\nimport ResultPoint from '../../ResultPoint';\nimport Version from '../decoder/Version';\nimport AlignmentPatternFinder from './AlignmentPatternFinder';\nimport FinderPatternFinder from './FinderPatternFinder';\n/*import java.util.Map;*/\n/**\n *Encapsulates logic that can detect a QR Code in an image, even if the QR Code\n * is rotated or skewed, or partially obscured.
\n *\n * @author Sean Owen\n */\nvar Detector = /** @class */ (function () {\n function Detector(image) {\n this.image = image;\n }\n Detector.prototype.getImage = function () {\n return this.image;\n };\n Detector.prototype.getResultPointCallback = function () {\n return this.resultPointCallback;\n };\n /**\n *Detects a QR Code in an image.
\n *\n * @return {@link DetectorResult} encapsulating results of detecting a QR Code\n * @throws NotFoundException if QR Code cannot be found\n * @throws FormatException if a QR Code cannot be decoded\n */\n // public detect(): DetectorResult /*throws NotFoundException, FormatException*/ {\n // return detect(null)\n // }\n /**\n *Detects a QR Code in an image.
\n *\n * @param hints optional hints to detector\n * @return {@link DetectorResult} encapsulating results of detecting a QR Code\n * @throws NotFoundException if QR Code cannot be found\n * @throws FormatException if a QR Code cannot be decoded\n */\n Detector.prototype.detect = function (hints) {\n this.resultPointCallback = (hints === null || hints === undefined) ? null :\n /*(ResultPointCallback) */ hints.get(DecodeHintType.NEED_RESULT_POINT_CALLBACK);\n var finder = new FinderPatternFinder(this.image, this.resultPointCallback);\n var info = finder.find(hints);\n return this.processFinderPatternInfo(info);\n };\n Detector.prototype.processFinderPatternInfo = function (info) {\n var topLeft = info.getTopLeft();\n var topRight = info.getTopRight();\n var bottomLeft = info.getBottomLeft();\n var moduleSize = this.calculateModuleSize(topLeft, topRight, bottomLeft);\n if (moduleSize < 1.0) {\n throw new NotFoundException('No pattern found in proccess finder.');\n }\n var dimension = Detector.computeDimension(topLeft, topRight, bottomLeft, moduleSize);\n var provisionalVersion = Version.getProvisionalVersionForDimension(dimension);\n var modulesBetweenFPCenters = provisionalVersion.getDimensionForVersion() - 7;\n var alignmentPattern = null;\n // Anything above version 1 has an alignment pattern\n if (provisionalVersion.getAlignmentPatternCenters().length > 0) {\n // Guess where a \"bottom right\" finder pattern would have been\n var bottomRightX = topRight.getX() - topLeft.getX() + bottomLeft.getX();\n var bottomRightY = topRight.getY() - topLeft.getY() + bottomLeft.getY();\n // Estimate that alignment pattern is closer by 3 modules\n // from \"bottom right\" to known top left location\n var correctionToTopLeft = 1.0 - 3.0 / modulesBetweenFPCenters;\n var estAlignmentX = /*(int) */ Math.floor(topLeft.getX() + correctionToTopLeft * (bottomRightX - topLeft.getX()));\n var estAlignmentY = /*(int) */ Math.floor(topLeft.getY() + correctionToTopLeft * (bottomRightY - topLeft.getY()));\n // Kind of arbitrary -- expand search radius before giving up\n for (var i = 4; i <= 16; i <<= 1) {\n try {\n alignmentPattern = this.findAlignmentInRegion(moduleSize, estAlignmentX, estAlignmentY, i);\n break;\n }\n catch (re /*NotFoundException*/) {\n if (!(re instanceof NotFoundException)) {\n throw re;\n }\n // try next round\n }\n }\n // If we didn't find alignment pattern... well try anyway without it\n }\n var transform = Detector.createTransform(topLeft, topRight, bottomLeft, alignmentPattern, dimension);\n var bits = Detector.sampleGrid(this.image, transform, dimension);\n var points;\n if (alignmentPattern === null) {\n points = [bottomLeft, topLeft, topRight];\n }\n else {\n points = [bottomLeft, topLeft, topRight, alignmentPattern];\n }\n return new DetectorResult(bits, points);\n };\n Detector.createTransform = function (topLeft, topRight, bottomLeft, alignmentPattern, dimension /*int*/) {\n var dimMinusThree = dimension - 3.5;\n var bottomRightX; /*float*/\n var bottomRightY; /*float*/\n var sourceBottomRightX; /*float*/\n var sourceBottomRightY; /*float*/\n if (alignmentPattern !== null) {\n bottomRightX = alignmentPattern.getX();\n bottomRightY = alignmentPattern.getY();\n sourceBottomRightX = dimMinusThree - 3.0;\n sourceBottomRightY = sourceBottomRightX;\n }\n else {\n // Don't have an alignment pattern, just make up the bottom-right point\n bottomRightX = (topRight.getX() - topLeft.getX()) + bottomLeft.getX();\n bottomRightY = (topRight.getY() - topLeft.getY()) + bottomLeft.getY();\n sourceBottomRightX = dimMinusThree;\n sourceBottomRightY = dimMinusThree;\n }\n return PerspectiveTransform.quadrilateralToQuadrilateral(3.5, 3.5, dimMinusThree, 3.5, sourceBottomRightX, sourceBottomRightY, 3.5, dimMinusThree, topLeft.getX(), topLeft.getY(), topRight.getX(), topRight.getY(), bottomRightX, bottomRightY, bottomLeft.getX(), bottomLeft.getY());\n };\n Detector.sampleGrid = function (image, transform, dimension /*int*/) {\n var sampler = GridSamplerInstance.getInstance();\n return sampler.sampleGridWithTransform(image, dimension, dimension, transform);\n };\n /**\n *Computes the dimension (number of modules on a size) of the QR Code based on the position\n * of the finder patterns and estimated module size.
\n */\n Detector.computeDimension = function (topLeft, topRight, bottomLeft, moduleSize /*float*/) {\n var tltrCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, topRight) / moduleSize);\n var tlblCentersDimension = MathUtils.round(ResultPoint.distance(topLeft, bottomLeft) / moduleSize);\n var dimension = Math.floor((tltrCentersDimension + tlblCentersDimension) / 2) + 7;\n switch (dimension & 0x03) { // mod 4\n case 0:\n dimension++;\n break;\n // 1? do nothing\n case 2:\n dimension--;\n break;\n case 3:\n throw new NotFoundException('Dimensions could be not found.');\n }\n return dimension;\n };\n /**\n *Computes an average estimated module size based on estimated derived from the positions\n * of the three finder patterns.
\n *\n * @param topLeft detected top-left finder pattern center\n * @param topRight detected top-right finder pattern center\n * @param bottomLeft detected bottom-left finder pattern center\n * @return estimated module size\n */\n Detector.prototype.calculateModuleSize = function (topLeft, topRight, bottomLeft) {\n // Take the average\n return (this.calculateModuleSizeOneWay(topLeft, topRight) +\n this.calculateModuleSizeOneWay(topLeft, bottomLeft)) / 2.0;\n };\n /**\n *Estimates module size based on two finder patterns -- it uses\n * {@link #sizeOfBlackWhiteBlackRunBothWays(int, int, int, int)} to figure the\n * width of each, measuring along the axis between their centers.
\n */\n Detector.prototype.calculateModuleSizeOneWay = function (pattern, otherPattern) {\n var moduleSizeEst1 = this.sizeOfBlackWhiteBlackRunBothWays(/*(int) */ Math.floor(pattern.getX()), \n /*(int) */ Math.floor(pattern.getY()), \n /*(int) */ Math.floor(otherPattern.getX()), \n /*(int) */ Math.floor(otherPattern.getY()));\n var moduleSizeEst2 = this.sizeOfBlackWhiteBlackRunBothWays(/*(int) */ Math.floor(otherPattern.getX()), \n /*(int) */ Math.floor(otherPattern.getY()), \n /*(int) */ Math.floor(pattern.getX()), \n /*(int) */ Math.floor(pattern.getY()));\n if (isNaN(moduleSizeEst1)) {\n return moduleSizeEst2 / 7.0;\n }\n if (isNaN(moduleSizeEst2)) {\n return moduleSizeEst1 / 7.0;\n }\n // Average them, and divide by 7 since we've counted the width of 3 black modules,\n // and 1 white and 1 black module on either side. Ergo, divide sum by 14.\n return (moduleSizeEst1 + moduleSizeEst2) / 14.0;\n };\n /**\n * See {@link #sizeOfBlackWhiteBlackRun(int, int, int, int)}; computes the total width of\n * a finder pattern by looking for a black-white-black run from the center in the direction\n * of another point (another finder pattern center), and in the opposite direction too.\n */\n Detector.prototype.sizeOfBlackWhiteBlackRunBothWays = function (fromX /*int*/, fromY /*int*/, toX /*int*/, toY /*int*/) {\n var result = this.sizeOfBlackWhiteBlackRun(fromX, fromY, toX, toY);\n // Now count other way -- don't run off image though of course\n var scale = 1.0;\n var otherToX = fromX - (toX - fromX);\n if (otherToX < 0) {\n scale = fromX / /*(float) */ (fromX - otherToX);\n otherToX = 0;\n }\n else if (otherToX >= this.image.getWidth()) {\n scale = (this.image.getWidth() - 1 - fromX) / /*(float) */ (otherToX - fromX);\n otherToX = this.image.getWidth() - 1;\n }\n var otherToY = /*(int) */ Math.floor(fromY - (toY - fromY) * scale);\n scale = 1.0;\n if (otherToY < 0) {\n scale = fromY / /*(float) */ (fromY - otherToY);\n otherToY = 0;\n }\n else if (otherToY >= this.image.getHeight()) {\n scale = (this.image.getHeight() - 1 - fromY) / /*(float) */ (otherToY - fromY);\n otherToY = this.image.getHeight() - 1;\n }\n otherToX = /*(int) */ Math.floor(fromX + (otherToX - fromX) * scale);\n result += this.sizeOfBlackWhiteBlackRun(fromX, fromY, otherToX, otherToY);\n // Middle pixel is double-counted this way; subtract 1\n return result - 1.0;\n };\n /**\n *This method traces a line from a point in the image, in the direction towards another point.\n * It begins in a black region, and keeps going until it finds white, then black, then white again.\n * It reports the distance from the start to this point.
\n *\n *This is used when figuring out how wide a finder pattern is, when the finder pattern\n * may be skewed or rotated.
\n */\n Detector.prototype.sizeOfBlackWhiteBlackRun = function (fromX /*int*/, fromY /*int*/, toX /*int*/, toY /*int*/) {\n // Mild variant of Bresenham's algorithm\n // see http://en.wikipedia.org/wiki/Bresenham's_line_algorithm\n var steep = Math.abs(toY - fromY) > Math.abs(toX - fromX);\n if (steep) {\n var temp = fromX;\n fromX = fromY;\n fromY = temp;\n temp = toX;\n toX = toY;\n toY = temp;\n }\n var dx = Math.abs(toX - fromX);\n var dy = Math.abs(toY - fromY);\n var error = -dx / 2;\n var xstep = fromX < toX ? 1 : -1;\n var ystep = fromY < toY ? 1 : -1;\n // In black pixels, looking for white, first or second time.\n var state = 0;\n // Loop up until x == toX, but not beyond\n var xLimit = toX + xstep;\n for (var x = fromX, y = fromY; x !== xLimit; x += xstep) {\n var realX = steep ? y : x;\n var realY = steep ? x : y;\n // Does current pixel mean we have moved white to black or vice versa?\n // Scanning black in state 0,2 and white in state 1, so if we find the wrong\n // color, advance to next state or end if we are in state 2 already\n if ((state === 1) === this.image.get(realX, realY)) {\n if (state === 2) {\n return MathUtils.distance(x, y, fromX, fromY);\n }\n state++;\n }\n error += dy;\n if (error > 0) {\n if (y === toY) {\n break;\n }\n y += ystep;\n error -= dx;\n }\n }\n // Found black-white-black; give the benefit of the doubt that the next pixel outside the image\n // is \"white\" so this last point at (toX+xStep,toY) is the right ending. This is really a\n // small approximation; (toX+xStep,toY+yStep) might be really correct. Ignore this.\n if (state === 2) {\n return MathUtils.distance(toX + xstep, toY, fromX, fromY);\n }\n // else we didn't find even black-white-black; no estimate is really possible\n return NaN;\n };\n /**\n *Attempts to locate an alignment pattern in a limited region of the image, which is\n * guessed to contain it. This method uses {@link AlignmentPattern}.
\n *\n * @param overallEstModuleSize estimated module size so far\n * @param estAlignmentX x coordinate of center of area probably containing alignment pattern\n * @param estAlignmentY y coordinate of above\n * @param allowanceFactor number of pixels in all directions to search from the center\n * @return {@link AlignmentPattern} if found, or null otherwise\n * @throws NotFoundException if an unexpected error occurs during detection\n */\n Detector.prototype.findAlignmentInRegion = function (overallEstModuleSize /*float*/, estAlignmentX /*int*/, estAlignmentY /*int*/, allowanceFactor /*float*/) {\n // Look for an alignment pattern (3 modules in size) around where it\n // should be\n var allowance = /*(int) */ Math.floor(allowanceFactor * overallEstModuleSize);\n var alignmentAreaLeftX = Math.max(0, estAlignmentX - allowance);\n var alignmentAreaRightX = Math.min(this.image.getWidth() - 1, estAlignmentX + allowance);\n if (alignmentAreaRightX - alignmentAreaLeftX < overallEstModuleSize * 3) {\n throw new NotFoundException('Alignment top exceeds estimated module size.');\n }\n var alignmentAreaTopY = Math.max(0, estAlignmentY - allowance);\n var alignmentAreaBottomY = Math.min(this.image.getHeight() - 1, estAlignmentY + allowance);\n if (alignmentAreaBottomY - alignmentAreaTopY < overallEstModuleSize * 3) {\n throw new NotFoundException('Alignment bottom exceeds estimated module size.');\n }\n var alignmentFinder = new AlignmentPatternFinder(this.image, alignmentAreaLeftX, alignmentAreaTopY, alignmentAreaRightX - alignmentAreaLeftX, alignmentAreaBottomY - alignmentAreaTopY, overallEstModuleSize, this.resultPointCallback);\n return alignmentFinder.find();\n };\n return Detector;\n}());\nexport default Detector;\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\n/*namespace com.google.zxing.qrcode.detector {*/\nimport ResultPoint from '../../ResultPoint';\n/**\n *Encapsulates a finder pattern, which are the three square patterns found in\n * the corners of QR Codes. It also encapsulates a count of similar finder patterns,\n * as a convenience to the finder's bookkeeping.
\n *\n * @author Sean Owen\n */\nvar FinderPattern = /** @class */ (function (_super) {\n __extends(FinderPattern, _super);\n // FinderPattern(posX: number/*float*/, posY: number/*float*/, estimatedModuleSize: number/*float*/) {\n // this(posX, posY, estimatedModuleSize, 1)\n // }\n function FinderPattern(posX /*float*/, posY /*float*/, estimatedModuleSize /*float*/, count /*int*/) {\n var _this = _super.call(this, posX, posY) || this;\n _this.estimatedModuleSize = estimatedModuleSize;\n _this.count = count;\n if (undefined === count) {\n _this.count = 1;\n }\n return _this;\n }\n FinderPattern.prototype.getEstimatedModuleSize = function () {\n return this.estimatedModuleSize;\n };\n FinderPattern.prototype.getCount = function () {\n return this.count;\n };\n /*\n void incrementCount() {\n this.count++\n }\n */\n /**\n *Determines if this finder pattern \"about equals\" a finder pattern at the stated\n * position and size -- meaning, it is at nearly the same center with nearly the same size.
\n */\n FinderPattern.prototype.aboutEquals = function (moduleSize /*float*/, i /*float*/, j /*float*/) {\n if (Math.abs(i - this.getY()) <= moduleSize && Math.abs(j - this.getX()) <= moduleSize) {\n var moduleSizeDiff = Math.abs(moduleSize - this.estimatedModuleSize);\n return moduleSizeDiff <= 1.0 || moduleSizeDiff <= this.estimatedModuleSize;\n }\n return false;\n };\n /**\n * Combines this object's current estimate of a finder pattern position and module size\n * with a new estimate. It returns a new {@code FinderPattern} containing a weighted average\n * based on count.\n */\n FinderPattern.prototype.combineEstimate = function (i /*float*/, j /*float*/, newModuleSize /*float*/) {\n var combinedCount = this.count + 1;\n var combinedX = (this.count * this.getX() + j) / combinedCount;\n var combinedY = (this.count * this.getY() + i) / combinedCount;\n var combinedModuleSize = (this.count * this.estimatedModuleSize + newModuleSize) / combinedCount;\n return new FinderPattern(combinedX, combinedY, combinedModuleSize, combinedCount);\n };\n return FinderPattern;\n}(ResultPoint));\nexport default FinderPattern;\n","/*\n * Copyright 2007 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.qrcode.detector {*/\nimport DecodeHintType from '../../DecodeHintType';\nimport ResultPoint from '../../ResultPoint';\nimport FinderPattern from './FinderPattern';\nimport FinderPatternInfo from './FinderPatternInfo';\nimport NotFoundException from '../../NotFoundException';\n/*import java.io.Serializable;*/\n/*import java.util.ArrayList;*/\n/*import java.util.Collections;*/\n/*import java.util.Comparator;*/\n/*import java.util.List;*/\n/*import java.util.Map;*/\n/**\n *This class attempts to find finder patterns in a QR Code. Finder patterns are the square\n * markers at three corners of a QR Code.
\n *\n *This class is thread-safe but not reentrant. Each thread must allocate its own object.\n *\n * @author Sean Owen\n */\nvar FinderPatternFinder = /** @class */ (function () {\n /**\n *
Creates a finder that will search the image for three finder patterns.
\n *\n * @param image image to search\n */\n // public constructor(image: BitMatrix) {\n // this(image, null)\n // }\n function FinderPatternFinder(image, resultPointCallback) {\n this.image = image;\n this.resultPointCallback = resultPointCallback;\n this.possibleCenters = [];\n this.crossCheckStateCount = new Int32Array(5);\n this.resultPointCallback = resultPointCallback;\n }\n FinderPatternFinder.prototype.getImage = function () {\n return this.image;\n };\n FinderPatternFinder.prototype.getPossibleCenters = function () {\n return this.possibleCenters;\n };\n FinderPatternFinder.prototype.find = function (hints) {\n var tryHarder = (hints !== null && hints !== undefined) && undefined !== hints.get(DecodeHintType.TRY_HARDER);\n var pureBarcode = (hints !== null && hints !== undefined) && undefined !== hints.get(DecodeHintType.PURE_BARCODE);\n var image = this.image;\n var maxI = image.getHeight();\n var maxJ = image.getWidth();\n // We are looking for black/white/black/white/black modules in\n // 1:1:3:1:1 ratio; this tracks the number of such modules seen so far\n // Let's assume that the maximum version QR Code we support takes up 1/4 the height of the\n // image, and then account for the center being 3 modules in size. This gives the smallest\n // number of pixels the center could be, so skip this often. When trying harder, look for all\n // QR versions regardless of how dense they are.\n var iSkip = Math.floor((3 * maxI) / (4 * FinderPatternFinder.MAX_MODULES));\n if (iSkip < FinderPatternFinder.MIN_SKIP || tryHarder) {\n iSkip = FinderPatternFinder.MIN_SKIP;\n }\n var done = false;\n var stateCount = new Int32Array(5);\n for (var i = iSkip - 1; i < maxI && !done; i += iSkip) {\n // Get a row of black/white values\n stateCount[0] = 0;\n stateCount[1] = 0;\n stateCount[2] = 0;\n stateCount[3] = 0;\n stateCount[4] = 0;\n var currentState = 0;\n for (var j = 0; j < maxJ; j++) {\n if (image.get(j, i)) {\n // Black pixel\n if ((currentState & 1) === 1) { // Counting white pixels\n currentState++;\n }\n stateCount[currentState]++;\n }\n else { // White pixel\n if ((currentState & 1) === 0) { // Counting black pixels\n if (currentState === 4) { // A winner?\n if (FinderPatternFinder.foundPatternCross(stateCount)) { // Yes\n var confirmed = this.handlePossibleCenter(stateCount, i, j, pureBarcode);\n if (confirmed === true) {\n // Start examining every other line. Checking each line turned out to be too\n // expensive and didn't improve performance.\n iSkip = 2;\n if (this.hasSkipped === true) {\n done = this.haveMultiplyConfirmedCenters();\n }\n else {\n var rowSkip = this.findRowSkip();\n if (rowSkip > stateCount[2]) {\n // Skip rows between row of lower confirmed center\n // and top of presumed third confirmed center\n // but back up a bit to get a full chance of detecting\n // it, entire width of center of finder pattern\n // Skip by rowSkip, but back off by stateCount[2] (size of last center\n // of pattern we saw) to be conservative, and also back off by iSkip which\n // is about to be re-added\n i += rowSkip - stateCount[2] - iSkip;\n j = maxJ - 1;\n }\n }\n }\n else {\n stateCount[0] = stateCount[2];\n stateCount[1] = stateCount[3];\n stateCount[2] = stateCount[4];\n stateCount[3] = 1;\n stateCount[4] = 0;\n currentState = 3;\n continue;\n }\n // Clear state to start looking again\n currentState = 0;\n stateCount[0] = 0;\n stateCount[1] = 0;\n stateCount[2] = 0;\n stateCount[3] = 0;\n stateCount[4] = 0;\n }\n else { // No, shift counts back by two\n stateCount[0] = stateCount[2];\n stateCount[1] = stateCount[3];\n stateCount[2] = stateCount[4];\n stateCount[3] = 1;\n stateCount[4] = 0;\n currentState = 3;\n }\n }\n else {\n stateCount[++currentState]++;\n }\n }\n else { // Counting white pixels\n stateCount[currentState]++;\n }\n }\n }\n if (FinderPatternFinder.foundPatternCross(stateCount)) {\n var confirmed = this.handlePossibleCenter(stateCount, i, maxJ, pureBarcode);\n if (confirmed === true) {\n iSkip = stateCount[0];\n if (this.hasSkipped) {\n // Found a third one\n done = this.haveMultiplyConfirmedCenters();\n }\n }\n }\n }\n var patternInfo = this.selectBestPatterns();\n ResultPoint.orderBestPatterns(patternInfo);\n return new FinderPatternInfo(patternInfo);\n };\n /**\n * Given a count of black/white/black/white/black pixels just seen and an end position,\n * figures the location of the center of this run.\n */\n FinderPatternFinder.centerFromEnd = function (stateCount, end /*int*/) {\n return (end - stateCount[4] - stateCount[3]) - stateCount[2] / 2.0;\n };\n /**\n * @param stateCount count of black/white/black/white/black pixels just read\n * @return true iff the proportions of the counts is close enough to the 1/1/3/1/1 ratios\n * used by finder patterns to be considered a match\n */\n FinderPatternFinder.foundPatternCross = function (stateCount) {\n var totalModuleSize = 0;\n for (var i = 0; i < 5; i++) {\n var count = stateCount[i];\n if (count === 0) {\n return false;\n }\n totalModuleSize += count;\n }\n if (totalModuleSize < 7) {\n return false;\n }\n var moduleSize = totalModuleSize / 7.0;\n var maxVariance = moduleSize / 2.0;\n // Allow less than 50% variance from 1-1-3-1-1 proportions\n return Math.abs(moduleSize - stateCount[0]) < maxVariance &&\n Math.abs(moduleSize - stateCount[1]) < maxVariance &&\n Math.abs(3.0 * moduleSize - stateCount[2]) < 3 * maxVariance &&\n Math.abs(moduleSize - stateCount[3]) < maxVariance &&\n Math.abs(moduleSize - stateCount[4]) < maxVariance;\n };\n FinderPatternFinder.prototype.getCrossCheckStateCount = function () {\n var crossCheckStateCount = this.crossCheckStateCount;\n crossCheckStateCount[0] = 0;\n crossCheckStateCount[1] = 0;\n crossCheckStateCount[2] = 0;\n crossCheckStateCount[3] = 0;\n crossCheckStateCount[4] = 0;\n return crossCheckStateCount;\n };\n /**\n * After a vertical and horizontal scan finds a potential finder pattern, this method\n * \"cross-cross-cross-checks\" by scanning down diagonally through the center of the possible\n * finder pattern to see if the same proportion is detected.\n *\n * @param startI row where a finder pattern was detected\n * @param centerJ center of the section that appears to cross a finder pattern\n * @param maxCount maximum reasonable number of modules that should be\n * observed in any reading state, based on the results of the horizontal scan\n * @param originalStateCountTotal The original state count total.\n * @return true if proportions are withing expected limits\n */\n FinderPatternFinder.prototype.crossCheckDiagonal = function (startI /*int*/, centerJ /*int*/, maxCount /*int*/, originalStateCountTotal /*int*/) {\n var stateCount = this.getCrossCheckStateCount();\n // Start counting up, left from center finding black center mass\n var i = 0;\n var image = this.image;\n while (startI >= i && centerJ >= i && image.get(centerJ - i, startI - i)) {\n stateCount[2]++;\n i++;\n }\n if (startI < i || centerJ < i) {\n return false;\n }\n // Continue up, left finding white space\n while (startI >= i && centerJ >= i && !image.get(centerJ - i, startI - i) &&\n stateCount[1] <= maxCount) {\n stateCount[1]++;\n i++;\n }\n // If already too many modules in this state or ran off the edge:\n if (startI < i || centerJ < i || stateCount[1] > maxCount) {\n return false;\n }\n // Continue up, left finding black border\n while (startI >= i && centerJ >= i && image.get(centerJ - i, startI - i) &&\n stateCount[0] <= maxCount) {\n stateCount[0]++;\n i++;\n }\n if (stateCount[0] > maxCount) {\n return false;\n }\n var maxI = image.getHeight();\n var maxJ = image.getWidth();\n // Now also count down, right from center\n i = 1;\n while (startI + i < maxI && centerJ + i < maxJ && image.get(centerJ + i, startI + i)) {\n stateCount[2]++;\n i++;\n }\n // Ran off the edge?\n if (startI + i >= maxI || centerJ + i >= maxJ) {\n return false;\n }\n while (startI + i < maxI && centerJ + i < maxJ && !image.get(centerJ + i, startI + i) &&\n stateCount[3] < maxCount) {\n stateCount[3]++;\n i++;\n }\n if (startI + i >= maxI || centerJ + i >= maxJ || stateCount[3] >= maxCount) {\n return false;\n }\n while (startI + i < maxI && centerJ + i < maxJ && image.get(centerJ + i, startI + i) &&\n stateCount[4] < maxCount) {\n stateCount[4]++;\n i++;\n }\n if (stateCount[4] >= maxCount) {\n return false;\n }\n // If we found a finder-pattern-like section, but its size is more than 100% different than\n // the original, assume it's a false positive\n var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] + stateCount[4];\n return Math.abs(stateCountTotal - originalStateCountTotal) < 2 * originalStateCountTotal &&\n FinderPatternFinder.foundPatternCross(stateCount);\n };\n /**\n *After a horizontal scan finds a potential finder pattern, this method\n * \"cross-checks\" by scanning down vertically through the center of the possible\n * finder pattern to see if the same proportion is detected.
\n *\n * @param startI row where a finder pattern was detected\n * @param centerJ center of the section that appears to cross a finder pattern\n * @param maxCount maximum reasonable number of modules that should be\n * observed in any reading state, based on the results of the horizontal scan\n * @return vertical center of finder pattern, or {@link Float#NaN} if not found\n */\n FinderPatternFinder.prototype.crossCheckVertical = function (startI /*int*/, centerJ /*int*/, maxCount /*int*/, originalStateCountTotal /*int*/) {\n var image = this.image;\n var maxI = image.getHeight();\n var stateCount = this.getCrossCheckStateCount();\n // Start counting up from center\n var i = startI;\n while (i >= 0 && image.get(centerJ, i)) {\n stateCount[2]++;\n i--;\n }\n if (i < 0) {\n return NaN;\n }\n while (i >= 0 && !image.get(centerJ, i) && stateCount[1] <= maxCount) {\n stateCount[1]++;\n i--;\n }\n // If already too many modules in this state or ran off the edge:\n if (i < 0 || stateCount[1] > maxCount) {\n return NaN;\n }\n while (i >= 0 && image.get(centerJ, i) && stateCount[0] <= maxCount) {\n stateCount[0]++;\n i--;\n }\n if (stateCount[0] > maxCount) {\n return NaN;\n }\n // Now also count down from center\n i = startI + 1;\n while (i < maxI && image.get(centerJ, i)) {\n stateCount[2]++;\n i++;\n }\n if (i === maxI) {\n return NaN;\n }\n while (i < maxI && !image.get(centerJ, i) && stateCount[3] < maxCount) {\n stateCount[3]++;\n i++;\n }\n if (i === maxI || stateCount[3] >= maxCount) {\n return NaN;\n }\n while (i < maxI && image.get(centerJ, i) && stateCount[4] < maxCount) {\n stateCount[4]++;\n i++;\n }\n if (stateCount[4] >= maxCount) {\n return NaN;\n }\n // If we found a finder-pattern-like section, but its size is more than 40% different than\n // the original, assume it's a false positive\n var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\n stateCount[4];\n if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= 2 * originalStateCountTotal) {\n return NaN;\n }\n return FinderPatternFinder.foundPatternCross(stateCount) ? FinderPatternFinder.centerFromEnd(stateCount, i) : NaN;\n };\n /**\n *Like {@link #crossCheckVertical(int, int, int, int)}, and in fact is basically identical,\n * except it reads horizontally instead of vertically. This is used to cross-cross\n * check a vertical cross check and locate the real center of the alignment pattern.
\n */\n FinderPatternFinder.prototype.crossCheckHorizontal = function (startJ /*int*/, centerI /*int*/, maxCount /*int*/, originalStateCountTotal /*int*/) {\n var image = this.image;\n var maxJ = image.getWidth();\n var stateCount = this.getCrossCheckStateCount();\n var j = startJ;\n while (j >= 0 && image.get(j, centerI)) {\n stateCount[2]++;\n j--;\n }\n if (j < 0) {\n return NaN;\n }\n while (j >= 0 && !image.get(j, centerI) && stateCount[1] <= maxCount) {\n stateCount[1]++;\n j--;\n }\n if (j < 0 || stateCount[1] > maxCount) {\n return NaN;\n }\n while (j >= 0 && image.get(j, centerI) && stateCount[0] <= maxCount) {\n stateCount[0]++;\n j--;\n }\n if (stateCount[0] > maxCount) {\n return NaN;\n }\n j = startJ + 1;\n while (j < maxJ && image.get(j, centerI)) {\n stateCount[2]++;\n j++;\n }\n if (j === maxJ) {\n return NaN;\n }\n while (j < maxJ && !image.get(j, centerI) && stateCount[3] < maxCount) {\n stateCount[3]++;\n j++;\n }\n if (j === maxJ || stateCount[3] >= maxCount) {\n return NaN;\n }\n while (j < maxJ && image.get(j, centerI) && stateCount[4] < maxCount) {\n stateCount[4]++;\n j++;\n }\n if (stateCount[4] >= maxCount) {\n return NaN;\n }\n // If we found a finder-pattern-like section, but its size is significantly different than\n // the original, assume it's a false positive\n var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\n stateCount[4];\n if (5 * Math.abs(stateCountTotal - originalStateCountTotal) >= originalStateCountTotal) {\n return NaN;\n }\n return FinderPatternFinder.foundPatternCross(stateCount) ? FinderPatternFinder.centerFromEnd(stateCount, j) : NaN;\n };\n /**\n *This is called when a horizontal scan finds a possible alignment pattern. It will\n * cross check with a vertical scan, and if successful, will, ah, cross-cross-check\n * with another horizontal scan. This is needed primarily to locate the real horizontal\n * center of the pattern in cases of extreme skew.\n * And then we cross-cross-cross check with another diagonal scan.
\n *\n *If that succeeds the finder pattern location is added to a list that tracks\n * the number of times each location has been nearly-matched as a finder pattern.\n * Each additional find is more evidence that the location is in fact a finder\n * pattern center\n *\n * @param stateCount reading state module counts from horizontal scan\n * @param i row where finder pattern may be found\n * @param j end of possible finder pattern in row\n * @param pureBarcode true if in \"pure barcode\" mode\n * @return true if a finder pattern candidate was found this time\n */\n FinderPatternFinder.prototype.handlePossibleCenter = function (stateCount, i /*int*/, j /*int*/, pureBarcode) {\n var stateCountTotal = stateCount[0] + stateCount[1] + stateCount[2] + stateCount[3] +\n stateCount[4];\n var centerJ = FinderPatternFinder.centerFromEnd(stateCount, j);\n var centerI = this.crossCheckVertical(i, /*(int) */ Math.floor(centerJ), stateCount[2], stateCountTotal);\n if (!isNaN(centerI)) {\n // Re-cross check\n centerJ = this.crossCheckHorizontal(/*(int) */ Math.floor(centerJ), /*(int) */ Math.floor(centerI), stateCount[2], stateCountTotal);\n if (!isNaN(centerJ) &&\n (!pureBarcode || this.crossCheckDiagonal(/*(int) */ Math.floor(centerI), /*(int) */ Math.floor(centerJ), stateCount[2], stateCountTotal))) {\n var estimatedModuleSize = stateCountTotal / 7.0;\n var found = false;\n var possibleCenters = this.possibleCenters;\n for (var index = 0, length_1 = possibleCenters.length; index < length_1; index++) {\n var center = possibleCenters[index];\n // Look for about the same center and module size:\n if (center.aboutEquals(estimatedModuleSize, centerI, centerJ)) {\n possibleCenters[index] = center.combineEstimate(centerI, centerJ, estimatedModuleSize);\n found = true;\n break;\n }\n }\n if (!found) {\n var point = new FinderPattern(centerJ, centerI, estimatedModuleSize);\n possibleCenters.push(point);\n if (this.resultPointCallback !== null && this.resultPointCallback !== undefined) {\n this.resultPointCallback.foundPossibleResultPoint(point);\n }\n }\n return true;\n }\n }\n return false;\n };\n /**\n * @return number of rows we could safely skip during scanning, based on the first\n * two finder patterns that have been located. In some cases their position will\n * allow us to infer that the third pattern must lie below a certain point farther\n * down in the image.\n */\n FinderPatternFinder.prototype.findRowSkip = function () {\n var e_1, _a;\n var max = this.possibleCenters.length;\n if (max <= 1) {\n return 0;\n }\n var firstConfirmedCenter = null;\n try {\n for (var _b = __values(this.possibleCenters), _c = _b.next(); !_c.done; _c = _b.next()) {\n var center = _c.value;\n if (center.getCount() >= FinderPatternFinder.CENTER_QUORUM) {\n if (firstConfirmedCenter == null) {\n firstConfirmedCenter = center;\n }\n else {\n // We have two confirmed centers\n // How far down can we skip before resuming looking for the next\n // pattern? In the worst case, only the difference between the\n // difference in the x / y coordinates of the two centers.\n // This is the case where you find top left last.\n this.hasSkipped = true;\n return /*(int) */ Math.floor((Math.abs(firstConfirmedCenter.getX() - center.getX()) -\n Math.abs(firstConfirmedCenter.getY() - center.getY())) / 2);\n }\n }\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n return 0;\n };\n /**\n * @return true iff we have found at least 3 finder patterns that have been detected\n * at least {@link #CENTER_QUORUM} times each, and, the estimated module size of the\n * candidates is \"pretty similar\"\n */\n FinderPatternFinder.prototype.haveMultiplyConfirmedCenters = function () {\n var e_2, _a, e_3, _b;\n var confirmedCount = 0;\n var totalModuleSize = 0.0;\n var max = this.possibleCenters.length;\n try {\n for (var _c = __values(this.possibleCenters), _d = _c.next(); !_d.done; _d = _c.next()) {\n var pattern = _d.value;\n if (pattern.getCount() >= FinderPatternFinder.CENTER_QUORUM) {\n confirmedCount++;\n totalModuleSize += pattern.getEstimatedModuleSize();\n }\n }\n }\n catch (e_2_1) { e_2 = { error: e_2_1 }; }\n finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n }\n finally { if (e_2) throw e_2.error; }\n }\n if (confirmedCount < 3) {\n return false;\n }\n // OK, we have at least 3 confirmed centers, but, it's possible that one is a \"false positive\"\n // and that we need to keep looking. We detect this by asking if the estimated module sizes\n // vary too much. We arbitrarily say that when the total deviation from average exceeds\n // 5% of the total module size estimates, it's too much.\n var average = totalModuleSize / max;\n var totalDeviation = 0.0;\n try {\n for (var _e = __values(this.possibleCenters), _f = _e.next(); !_f.done; _f = _e.next()) {\n var pattern = _f.value;\n totalDeviation += Math.abs(pattern.getEstimatedModuleSize() - average);\n }\n }\n catch (e_3_1) { e_3 = { error: e_3_1 }; }\n finally {\n try {\n if (_f && !_f.done && (_b = _e.return)) _b.call(_e);\n }\n finally { if (e_3) throw e_3.error; }\n }\n return totalDeviation <= 0.05 * totalModuleSize;\n };\n /**\n * @return the 3 best {@link FinderPattern}s from our list of candidates. The \"best\" are\n * those that have been detected at least {@link #CENTER_QUORUM} times, and whose module\n * size differs from the average among those patterns the least\n * @throws NotFoundException if 3 such finder patterns do not exist\n */\n FinderPatternFinder.prototype.selectBestPatterns = function () {\n var e_4, _a, e_5, _b;\n var startSize = this.possibleCenters.length;\n if (startSize < 3) {\n // Couldn't find enough finder patterns\n throw new NotFoundException();\n }\n var possibleCenters = this.possibleCenters;\n var average;\n // Filter outlier possibilities whose module size is too different\n if (startSize > 3) {\n // But we can only afford to do so if we have at least 4 possibilities to choose from\n var totalModuleSize = 0.0;\n var square = 0.0;\n try {\n for (var _c = __values(this.possibleCenters), _d = _c.next(); !_d.done; _d = _c.next()) {\n var center = _d.value;\n var size = center.getEstimatedModuleSize();\n totalModuleSize += size;\n square += size * size;\n }\n }\n catch (e_4_1) { e_4 = { error: e_4_1 }; }\n finally {\n try {\n if (_d && !_d.done && (_a = _c.return)) _a.call(_c);\n }\n finally { if (e_4) throw e_4.error; }\n }\n average = totalModuleSize / startSize;\n var stdDev = Math.sqrt(square / startSize - average * average);\n possibleCenters.sort(\n /**\n *
Orders by furthest from average
\n */\n // FurthestFromAverageComparator implements ComparatorOrders by {@link FinderPattern#getCount()}, descending.
\n */\n // CenterComparator implements ComparatorEncapsulates information about finder patterns in an image, including the location of\n * the three finder patterns, and their estimated module size.
\n *\n * @author Sean Owen\n */\nvar FinderPatternInfo = /** @class */ (function () {\n function FinderPatternInfo(patternCenters) {\n this.bottomLeft = patternCenters[0];\n this.topLeft = patternCenters[1];\n this.topRight = patternCenters[2];\n }\n FinderPatternInfo.prototype.getBottomLeft = function () {\n return this.bottomLeft;\n };\n FinderPatternInfo.prototype.getTopLeft = function () {\n return this.topLeft;\n };\n FinderPatternInfo.prototype.getTopRight = function () {\n return this.topRight;\n };\n return FinderPatternInfo;\n}());\nexport default FinderPatternInfo;\n","/*\n * Copyright 2008 ZXing authors\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/*namespace com.google.zxing.qrcode.encoder {*/\nvar BlockPair = /** @class */ (function () {\n function BlockPair(dataBytes, errorCorrectionBytes) {\n this.dataBytes = dataBytes;\n this.errorCorrectionBytes = errorCorrectionBytes;\n }\n BlockPair.prototype.getDataBytes = function () {\n return this.dataBytes;\n };\n BlockPair.prototype.getErrorCorrectionBytes = function () {\n return this.errorCorrectionBytes;\n };\n return BlockPair;\n}());\nexport default BlockPair;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.qrcode.encoder {*/\n/*import java.util.Arrays;*/\nimport Arrays from '../../util/Arrays';\nimport StringBuilder from '../../util/StringBuilder';\n/**\n * JAVAPORT: The original code was a 2D array of ints, but since it only ever gets assigned\n * -1, 0, and 1, I'm going to use less memory and go with bytes.\n *\n * @author dswitkin@google.com (Daniel Switkin)\n */\nvar ByteMatrix = /** @class */ (function () {\n function ByteMatrix(width /*int*/, height /*int*/) {\n this.width = width;\n this.height = height;\n var bytes = new Array(height); // [height][width]\n for (var i = 0; i !== height; i++) {\n bytes[i] = new Uint8Array(width);\n }\n this.bytes = bytes;\n }\n ByteMatrix.prototype.getHeight = function () {\n return this.height;\n };\n ByteMatrix.prototype.getWidth = function () {\n return this.width;\n };\n ByteMatrix.prototype.get = function (x /*int*/, y /*int*/) {\n return this.bytes[y][x];\n };\n /**\n * @return an internal representation as bytes, in row-major order. array[y][x] represents point (x,y)\n */\n ByteMatrix.prototype.getArray = function () {\n return this.bytes;\n };\n // TYPESCRIPTPORT: preffer to let two methods instead of override to avoid type comparison inside\n ByteMatrix.prototype.setNumber = function (x /*int*/, y /*int*/, value /*byte|int*/) {\n this.bytes[y][x] = value;\n };\n // public set(x: number /*int*/, y: number /*int*/, value: number /*int*/): void {\n // bytes[y][x] = (byte) value\n // }\n ByteMatrix.prototype.setBoolean = function (x /*int*/, y /*int*/, value) {\n this.bytes[y][x] = /*(byte) */ (value ? 1 : 0);\n };\n ByteMatrix.prototype.clear = function (value /*byte*/) {\n var e_1, _a;\n try {\n for (var _b = __values(this.bytes), _c = _b.next(); !_c.done; _c = _b.next()) {\n var aByte = _c.value;\n Arrays.fill(aByte, value);\n }\n }\n catch (e_1_1) { e_1 = { error: e_1_1 }; }\n finally {\n try {\n if (_c && !_c.done && (_a = _b.return)) _a.call(_b);\n }\n finally { if (e_1) throw e_1.error; }\n }\n };\n ByteMatrix.prototype.equals = function (o) {\n if (!(o instanceof ByteMatrix)) {\n return false;\n }\n var other = o;\n if (this.width !== other.width) {\n return false;\n }\n if (this.height !== other.height) {\n return false;\n }\n for (var y = 0, height = this.height; y < height; ++y) {\n var bytesY = this.bytes[y];\n var otherBytesY = other.bytes[y];\n for (var x = 0, width = this.width; x < width; ++x) {\n if (bytesY[x] !== otherBytesY[x]) {\n return false;\n }\n }\n }\n return true;\n };\n /*@Override*/\n ByteMatrix.prototype.toString = function () {\n var result = new StringBuilder(); // (2 * width * height + 2)\n for (var y = 0, height = this.height; y < height; ++y) {\n var bytesY = this.bytes[y];\n for (var x = 0, width = this.width; x < width; ++x) {\n switch (bytesY[x]) {\n case 0:\n result.append(' 0');\n break;\n case 1:\n result.append(' 1');\n break;\n default:\n result.append(' ');\n break;\n }\n }\n result.append('\\n');\n }\n return result.toString();\n };\n return ByteMatrix;\n}());\nexport default ByteMatrix;\n","/*\n * Copyright 2008 ZXing authors\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 */\nvar __values = (this && this.__values) || function(o) {\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\n if (m) return m.call(o);\n if (o && typeof o.length === \"number\") return {\n next: function () {\n if (o && i >= o.length) o = void 0;\n return { value: o && o[i++], done: !o };\n }\n };\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\n};\n/*namespace com.google.zxing.qrcode.encoder {*/\nimport EncodeHintType from '../../EncodeHintType';\nimport BitArray from '../../common/BitArray';\nimport CharacterSetECI from '../../common/CharacterSetECI';\nimport GenericGF from '../../common/reedsolomon/GenericGF';\nimport ReedSolomonEncoder from '../../common/reedsolomon/ReedSolomonEncoder';\nimport Mode from '../decoder/Mode';\nimport Version from '../decoder/Version';\nimport MaskUtil from './MaskUtil';\nimport ByteMatrix from './ByteMatrix';\nimport QRCode from './QRCode';\nimport MatrixUtil from './MatrixUtil';\nimport StringEncoding from '../../util/StringEncoding';\nimport BlockPair from './BlockPair';\nimport WriterException from '../../WriterException';\n/*import java.io.UnsupportedEncodingException;*/\n/*import java.util.ArrayList;*/\n/*import java.util.Collection;*/\n/*import java.util.Map;*/\n/**\n * @author satorux@google.com (Satoru Takabayashi) - creator\n * @author dswitkin@google.com (Daniel Switkin) - ported from C++\n */\nvar Encoder = /** @class */ (function () {\n // TYPESCRIPTPORT: changed to UTF8, the default for js\n function Encoder() {\n }\n // The mask penalty calculation is complicated. See Table 21 of JISX0510:2004 (p.45) for details.\n // Basically it applies four rules and summate all penalties.\n Encoder.calculateMaskPenalty = function (matrix) {\n return MaskUtil.applyMaskPenaltyRule1(matrix)\n + MaskUtil.applyMaskPenaltyRule2(matrix)\n + MaskUtil.applyMaskPenaltyRule3(matrix)\n + MaskUtil.applyMaskPenaltyRule4(matrix);\n };\n /**\n * @param content text to encode\n * @param ecLevel error correction level to use\n * @return {@link QRCode} representing the encoded QR code\n * @throws WriterException if encoding can't succeed, because of for example invalid content\n * or configuration\n */\n // public static encode(content: string, ecLevel: ErrorCorrectionLevel): QRCode /*throws WriterException*/ {\n // return encode(content, ecLevel, null)\n // }\n Encoder.encode = function (content, ecLevel, hints) {\n if (hints === void 0) { hints = null; }\n // Determine what character encoding has been specified by the caller, if any\n var encoding = Encoder.DEFAULT_BYTE_MODE_ENCODING;\n var hasEncodingHint = hints !== null && undefined !== hints.get(EncodeHintType.CHARACTER_SET);\n if (hasEncodingHint) {\n encoding = hints.get(EncodeHintType.CHARACTER_SET).toString();\n }\n // Pick an encoding mode appropriate for the content. Note that this will not attempt to use\n // multiple modes / segments even if that were more efficient. Twould be nice.\n var mode = this.chooseMode(content, encoding);\n // This will store the header information, like mode and\n // length, as well as \"header\" segments like an ECI segment.\n var headerBits = new BitArray();\n // Append ECI segment if applicable\n if (mode === Mode.BYTE && (hasEncodingHint || Encoder.DEFAULT_BYTE_MODE_ENCODING !== encoding)) {\n var eci = CharacterSetECI.getCharacterSetECIByName(encoding);\n if (eci !== undefined) {\n this.appendECI(eci, headerBits);\n }\n }\n // (With ECI in place,) Write the mode marker\n this.appendModeInfo(mode, headerBits);\n // Collect data within the main segment, separately, to count its size if needed. Don't add it to\n // main payload yet.\n var dataBits = new BitArray();\n this.appendBytes(content, mode, dataBits, encoding);\n var version;\n if (hints !== null && undefined !== hints.get(EncodeHintType.QR_VERSION)) {\n var versionNumber = Number.parseInt(hints.get(EncodeHintType.QR_VERSION).toString(), 10);\n version = Version.getVersionForNumber(versionNumber);\n var bitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, version);\n if (!this.willFit(bitsNeeded, version, ecLevel)) {\n throw new WriterException('Data too big for requested version');\n }\n }\n else {\n version = this.recommendVersion(ecLevel, mode, headerBits, dataBits);\n }\n var headerAndDataBits = new BitArray();\n headerAndDataBits.appendBitArray(headerBits);\n // Find \"length\" of main segment and write it\n var numLetters = mode === Mode.BYTE ? dataBits.getSizeInBytes() : content.length;\n this.appendLengthInfo(numLetters, version, mode, headerAndDataBits);\n // Put data together into the overall payload\n headerAndDataBits.appendBitArray(dataBits);\n var ecBlocks = version.getECBlocksForLevel(ecLevel);\n var numDataBytes = version.getTotalCodewords() - ecBlocks.getTotalECCodewords();\n // Terminate the bits properly.\n this.terminateBits(numDataBytes, headerAndDataBits);\n // Interleave data bits with error correction code.\n var finalBits = this.interleaveWithECBytes(headerAndDataBits, version.getTotalCodewords(), numDataBytes, ecBlocks.getNumBlocks());\n var qrCode = new QRCode();\n qrCode.setECLevel(ecLevel);\n qrCode.setMode(mode);\n qrCode.setVersion(version);\n // Choose the mask pattern and set to \"qrCode\".\n var dimension = version.getDimensionForVersion();\n var matrix = new ByteMatrix(dimension, dimension);\n var maskPattern = this.chooseMaskPattern(finalBits, ecLevel, version, matrix);\n qrCode.setMaskPattern(maskPattern);\n // Build the matrix and set it to \"qrCode\".\n MatrixUtil.buildMatrix(finalBits, ecLevel, version, maskPattern, matrix);\n qrCode.setMatrix(matrix);\n return qrCode;\n };\n /**\n * Decides the smallest version of QR code that will contain all of the provided data.\n *\n * @throws WriterException if the data cannot fit in any version\n */\n Encoder.recommendVersion = function (ecLevel, mode, headerBits, dataBits) {\n // Hard part: need to know version to know how many bits length takes. But need to know how many\n // bits it takes to know version. First we take a guess at version by assuming version will be\n // the minimum, 1:\n var provisionalBitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, Version.getVersionForNumber(1));\n var provisionalVersion = this.chooseVersion(provisionalBitsNeeded, ecLevel);\n // Use that guess to calculate the right version. I am still not sure this works in 100% of cases.\n var bitsNeeded = this.calculateBitsNeeded(mode, headerBits, dataBits, provisionalVersion);\n return this.chooseVersion(bitsNeeded, ecLevel);\n };\n Encoder.calculateBitsNeeded = function (mode, headerBits, dataBits, version) {\n return headerBits.getSize() + mode.getCharacterCountBits(version) + dataBits.getSize();\n };\n /**\n * @return the code point of the table used in alphanumeric mode or\n * -1 if there is no corresponding code in the table.\n */\n Encoder.getAlphanumericCode = function (code /*int*/) {\n if (code < Encoder.ALPHANUMERIC_TABLE.length) {\n return Encoder.ALPHANUMERIC_TABLE[code];\n }\n return -1;\n };\n // public static chooseMode(content: string): Mode {\n // return chooseMode(content, null);\n // }\n /**\n * Choose the best mode by examining the content. Note that 'encoding' is used as a hint;\n * if it is Shift_JIS, and the input is only double-byte Kanji, then we return {@link Mode#KANJI}.\n */\n Encoder.chooseMode = function (content, encoding) {\n if (encoding === void 0) { encoding = null; }\n if (CharacterSetECI.SJIS.getName() === encoding && this.isOnlyDoubleByteKanji(content)) {\n // Choose Kanji mode if all input are double-byte characters\n return Mode.KANJI;\n }\n var hasNumeric = false;\n var hasAlphanumeric = false;\n for (var i = 0, length_1 = content.length; i < length_1; ++i) {\n var c = content.charAt(i);\n if (Encoder.isDigit(c)) {\n hasNumeric = true;\n }\n else if (this.getAlphanumericCode(c.charCodeAt(0)) !== -1) {\n hasAlphanumeric = true;\n }\n else {\n return Mode.BYTE;\n }\n }\n if (hasAlphanumeric) {\n return Mode.ALPHANUMERIC;\n }\n if (hasNumeric) {\n return Mode.NUMERIC;\n }\n return Mode.BYTE;\n };\n Encoder.isOnlyDoubleByteKanji = function (content) {\n var bytes;\n try {\n bytes = StringEncoding.encode(content, CharacterSetECI.SJIS); // content.getBytes(\"Shift_JIS\"))\n }\n catch (ignored /*: UnsupportedEncodingException*/) {\n return false;\n }\n var length = bytes.length;\n if (length % 2 !== 0) {\n return false;\n }\n for (var i = 0; i < length; i += 2) {\n var byte1 = bytes[i] & 0xFF;\n if ((byte1 < 0x81 || byte1 > 0x9F) && (byte1 < 0xE0 || byte1 > 0xEB)) {\n return false;\n }\n }\n return true;\n };\n Encoder.chooseMaskPattern = function (bits, ecLevel, version, matrix) {\n var minPenalty = Number.MAX_SAFE_INTEGER; // Lower penalty is better.\n var bestMaskPattern = -1;\n // We try all mask patterns to choose the best one.\n for (var maskPattern = 0; maskPattern < QRCode.NUM_MASK_PATTERNS; maskPattern++) {\n MatrixUtil.buildMatrix(bits, ecLevel, version, maskPattern, matrix);\n var penalty = this.calculateMaskPenalty(matrix);\n if (penalty < minPenalty) {\n minPenalty = penalty;\n bestMaskPattern = maskPattern;\n }\n }\n return bestMaskPattern;\n };\n Encoder.chooseVersion = function (numInputBits /*int*/, ecLevel) {\n for (var versionNum = 1; versionNum <= 40; versionNum++) {\n var version = Version.getVersionForNumber(versionNum);\n if (Encoder.willFit(numInputBits, version, ecLevel)) {\n return version;\n }\n }\n throw new WriterException('Data too big');\n };\n /**\n * @return true if the number of input bits will fit in a code with the specified version and\n * error correction level.\n */\n Encoder.willFit = function (numInputBits /*int*/, version, ecLevel) {\n // In the following comments, we use numbers of Version 7-H.\n // numBytes = 196\n var numBytes = version.getTotalCodewords();\n // getNumECBytes = 130\n var ecBlocks = version.getECBlocksForLevel(ecLevel);\n var numEcBytes = ecBlocks.getTotalECCodewords();\n // getNumDataBytes = 196 - 130 = 66\n var numDataBytes = numBytes - numEcBytes;\n var totalInputBytes = (numInputBits + 7) / 8;\n return numDataBytes >= totalInputBytes;\n };\n /**\n * Terminate bits as described in 8.4.8 and 8.4.9 of JISX0510:2004 (p.24).\n */\n Encoder.terminateBits = function (numDataBytes /*int*/, bits) {\n var capacity = numDataBytes * 8;\n if (bits.getSize() > capacity) {\n throw new WriterException('data bits cannot fit in the QR Code' + bits.getSize() + ' > ' +\n capacity);\n }\n for (var i = 0; i < 4 && bits.getSize() < capacity; ++i) {\n bits.appendBit(false);\n }\n // Append termination bits. See 8.4.8 of JISX0510:2004 (p.24) for details.\n // If the last byte isn't 8-bit aligned, we'll add padding bits.\n var numBitsInLastByte = bits.getSize() & 0x07;\n if (numBitsInLastByte > 0) {\n for (var i = numBitsInLastByte; i < 8; i++) {\n bits.appendBit(false);\n }\n }\n // If we have more space, we'll fill the space with padding patterns defined in 8.4.9 (p.24).\n var numPaddingBytes = numDataBytes - bits.getSizeInBytes();\n for (var i = 0; i < numPaddingBytes; ++i) {\n bits.appendBits((i & 0x01) === 0 ? 0xEC : 0x11, 8);\n }\n if (bits.getSize() !== capacity) {\n throw new WriterException('Bits size does not equal capacity');\n }\n };\n /**\n * Get number of data bytes and number of error correction bytes for block id \"blockID\". Store\n * the result in \"numDataBytesInBlock\", and \"numECBytesInBlock\". See table 12 in 8.5.1 of\n * JISX0510:2004 (p.30)\n */\n Encoder.getNumDataBytesAndNumECBytesForBlockID = function (numTotalBytes /*int*/, numDataBytes /*int*/, numRSBlocks /*int*/, blockID /*int*/, numDataBytesInBlock, numECBytesInBlock) {\n if (blockID >= numRSBlocks) {\n throw new WriterException('Block ID too large');\n }\n // numRsBlocksInGroup2 = 196 % 5 = 1\n var numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;\n // numRsBlocksInGroup1 = 5 - 1 = 4\n var numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;\n // numTotalBytesInGroup1 = 196 / 5 = 39\n var numTotalBytesInGroup1 = Math.floor(numTotalBytes / numRSBlocks);\n // numTotalBytesInGroup2 = 39 + 1 = 40\n var numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;\n // numDataBytesInGroup1 = 66 / 5 = 13\n var numDataBytesInGroup1 = Math.floor(numDataBytes / numRSBlocks);\n // numDataBytesInGroup2 = 13 + 1 = 14\n var numDataBytesInGroup2 = numDataBytesInGroup1 + 1;\n // numEcBytesInGroup1 = 39 - 13 = 26\n var numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;\n // numEcBytesInGroup2 = 40 - 14 = 26\n var numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;\n // Sanity checks.\n // 26 = 26\n if (numEcBytesInGroup1 !== numEcBytesInGroup2) {\n throw new WriterException('EC bytes mismatch');\n }\n // 5 = 4 + 1.\n if (numRSBlocks !== numRsBlocksInGroup1 + numRsBlocksInGroup2) {\n throw new WriterException('RS blocks mismatch');\n }\n // 196 = (13 + 26) * 4 + (14 + 26) * 1\n if (numTotalBytes !==\n ((numDataBytesInGroup1 + numEcBytesInGroup1) *\n numRsBlocksInGroup1) +\n ((numDataBytesInGroup2 + numEcBytesInGroup2) *\n numRsBlocksInGroup2)) {\n throw new WriterException('Total bytes mismatch');\n }\n if (blockID < numRsBlocksInGroup1) {\n numDataBytesInBlock[0] = numDataBytesInGroup1;\n numECBytesInBlock[0] = numEcBytesInGroup1;\n }\n else {\n numDataBytesInBlock[0] = numDataBytesInGroup2;\n numECBytesInBlock[0] = numEcBytesInGroup2;\n }\n };\n /**\n * Interleave \"bits\" with corresponding error correction bytes. On success, store the result in\n * \"result\". The interleave rule is complicated. See 8.6 of JISX0510:2004 (p.37) for details.\n */\n Encoder.interleaveWithECBytes = function (bits, numTotalBytes /*int*/, numDataBytes /*int*/, numRSBlocks /*int*/) {\n var e_1, _a, e_2, _b;\n // \"bits\" must have \"getNumDataBytes\" bytes of data.\n if (bits.getSizeInBytes() !== numDataBytes) {\n throw new WriterException('Number of bits and data bytes does not match');\n }\n // Step 1. Divide data bytes into blocks and generate error correction bytes for them. We'll\n // store the divided data bytes blocks and error correction bytes blocks into \"blocks\".\n var dataBytesOffset = 0;\n var maxNumDataBytes = 0;\n var maxNumEcBytes = 0;\n // Since, we know the number of reedsolmon blocks, we can initialize the vector with the number.\n var blocks = new Array(); // new ArraytoByteArray()
and\n * toString()
.\n * \n * Closing a ByteArrayOutputStream has no effect. The methods in\n * this class can be called after the stream has been closed without\n * generating an IOException.\n *\n * @author Arthur van Hoff\n * @since JDK1.0\n */\nvar ByteArrayOutputStream = /** @class */ (function (_super) {\n __extends(ByteArrayOutputStream, _super);\n /**\n * Creates a new byte array output stream. The buffer capacity is\n * initially 32 bytes, though its size increases if necessary.\n */\n // public constructor() {\n // this(32);\n // }\n /**\n * Creates a new byte array output stream, with a buffer capacity of\n * the specified size, in bytes.\n *\n * @param size the initial size.\n * @exception IllegalArgumentException if size is negative.\n */\n function ByteArrayOutputStream(size) {\n if (size === void 0) { size = 32; }\n var _this = _super.call(this) || this;\n /**\n * The number of valid bytes in the buffer.\n */\n _this.count = 0;\n if (size < 0) {\n throw new IllegalArgumentException('Negative initial size: '\n + size);\n }\n _this.buf = new Uint8Array(size);\n return _this;\n }\n /**\n * Increases the capacity if necessary to ensure that it can hold\n * at least the number of elements specified by the minimum\n * capacity argument.\n *\n * @param minCapacity the desired minimum capacity\n * @throws OutOfMemoryError if {@code minCapacity < 0}. This is\n * interpreted as a request for the unsatisfiably large capacity\n * {@code (long) Integer.MAX_VALUE + (minCapacity - Integer.MAX_VALUE)}.\n */\n ByteArrayOutputStream.prototype.ensureCapacity = function (minCapacity) {\n // overflow-conscious code\n if (minCapacity - this.buf.length > 0)\n this.grow(minCapacity);\n };\n /**\n * Increases the capacity to ensure that it can hold at least the\n * number of elements specified by the minimum capacity argument.\n *\n * @param minCapacity the desired minimum capacity\n */\n ByteArrayOutputStream.prototype.grow = function (minCapacity) {\n // overflow-conscious code\n var oldCapacity = this.buf.length;\n var newCapacity = oldCapacity << 1;\n if (newCapacity - minCapacity < 0)\n newCapacity = minCapacity;\n if (newCapacity < 0) {\n if (minCapacity < 0) // overflow\n throw new OutOfMemoryError();\n newCapacity = Integer.MAX_VALUE;\n }\n this.buf = Arrays.copyOfUint8Array(this.buf, newCapacity);\n };\n /**\n * Writes the specified byte to this byte array output stream.\n *\n * @param b the byte to be written.\n */\n ByteArrayOutputStream.prototype.write = function (b) {\n this.ensureCapacity(this.count + 1);\n this.buf[this.count] = /*(byte)*/ b;\n this.count += 1;\n };\n /**\n * Writes len
bytes from the specified byte array\n * starting at offset off
to this byte array output stream.\n *\n * @param b the data.\n * @param off the start offset in the data.\n * @param len the number of bytes to write.\n */\n ByteArrayOutputStream.prototype.writeBytesOffset = function (b, off, len) {\n if ((off < 0) || (off > b.length) || (len < 0) ||\n ((off + len) - b.length > 0)) {\n throw new IndexOutOfBoundsException();\n }\n this.ensureCapacity(this.count + len);\n System.arraycopy(b, off, this.buf, this.count, len);\n this.count += len;\n };\n /**\n * Writes the complete contents of this byte array output stream to\n * the specified output stream argument, as if by calling the output\n * stream's write method using out.write(buf, 0, count)
.\n *\n * @param out the output stream to which to write the data.\n * @exception IOException if an I/O error occurs.\n */\n ByteArrayOutputStream.prototype.writeTo = function (out) {\n out.writeBytesOffset(this.buf, 0, this.count);\n };\n /**\n * Resets the count
field of this byte array output\n * stream to zero, so that all currently accumulated output in the\n * output stream is discarded. The output stream can be used again,\n * reusing the already allocated buffer space.\n *\n * @see java.io.ByteArrayInputStream#count\n */\n ByteArrayOutputStream.prototype.reset = function () {\n this.count = 0;\n };\n /**\n * Creates a newly allocated byte array. Its size is the current\n * size of this output stream and the valid contents of the buffer\n * have been copied into it.\n *\n * @return the current contents of this output stream, as a byte array.\n * @see java.io.ByteArrayOutputStream#size()\n */\n ByteArrayOutputStream.prototype.toByteArray = function () {\n return Arrays.copyOfUint8Array(this.buf, this.count);\n };\n /**\n * Returns the current size of the buffer.\n *\n * @return the value of the count
field, which is the number\n * of valid bytes in this output stream.\n * @see java.io.ByteArrayOutputStream#count\n */\n ByteArrayOutputStream.prototype.size = function () {\n return this.count;\n };\n ByteArrayOutputStream.prototype.toString = function (param) {\n if (!param) {\n return this.toString_void();\n }\n if (typeof param === 'string') {\n return this.toString_string(param);\n }\n return this.toString_number(param);\n };\n /**\n * Converts the buffer's contents into a string decoding bytes using the\n * platform's default character set. The length of the new String\n * is a function of the character set, and hence may not be equal to the\n * size of the buffer.\n *\n *
This method always replaces malformed-input and unmappable-character\n * sequences with the default replacement string for the platform's\n * default character set. The {@linkplain java.nio.charset.CharsetDecoder}\n * class should be used when more control over the decoding process is\n * required.\n *\n * @return String decoded from the buffer's contents.\n * @since JDK1.1\n */\n ByteArrayOutputStream.prototype.toString_void = function () {\n return new String(this.buf /*, 0, this.count*/).toString();\n };\n /**\n * Converts the buffer's contents into a string by decoding the bytes using\n * the specified {@link java.nio.charset.Charset charsetName}. The length of\n * the new String is a function of the charset, and hence may not be\n * equal to the length of the byte array.\n *\n *
This method always replaces malformed-input and unmappable-character\n * sequences with this charset's default replacement string. The {@link\n * java.nio.charset.CharsetDecoder} class should be used when more control\n * over the decoding process is required.\n *\n * @param charsetName the name of a supported\n * {@linkplain java.nio.charset.Charset charset \n *\n * @throws IOException\n */\n ByteArrayOutputStream.prototype.close = function () {\n };\n return ByteArrayOutputStream;\n}(OutputStream));\nexport default ByteArrayOutputStream;\n","var __extends = (this && this.__extends) || (function () {\n var extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf ||\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\n return extendStatics(d, b);\n };\n return function (d, b) {\n extendStatics(d, b);\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n };\n})();\nimport CharacterSetECI from '../common/CharacterSetECI';\n/**\n * Just to make a shortcut between Java code and TS code.\n */\nvar Charset = /** @class */ (function (_super) {\n __extends(Charset, _super);\n function Charset() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n Charset.forName = function (name) {\n return this.getCharacterSetECIByName(name);\n };\n return Charset;\n}(CharacterSetECI));\nexport default Charset;\n","var Collections = /** @class */ (function () {\n function Collections() {\n }\n /**\n * The singletonList(T) method is used to return an immutable list containing only the specified object.\n */\n Collections.singletonList = function (item) {\n return [item];\n };\n /**\n * The min(Collection extends T>, Comparator super T>) method is used to return the minimum element of the given collection, according to the order induced by the specified comparator.\n */\n Collections.min = function (collection, comparator) {\n return collection.sort(comparator)[0];\n };\n return Collections;\n}());\nexport default Collections;\n","/**\n * Ponyfill for Java's Float class.\n */\nvar Float = /** @class */ (function () {\n function Float() {\n }\n /**\n * SincTS has no difference between int and float, there's all numbers,\n * this is used only to polyfill Java code.\n */\n Float.floatToIntBits = function (f) {\n return f;\n };\n /**\n * The float max value in JS is the number max value.\n */\n Float.MAX_VALUE = Number.MAX_SAFE_INTEGER;\n return Float;\n}());\nexport default Float;\n","/**\n * Java Formatter class polyfill that works in the JS way.\n */\nvar Formatter = /** @class */ (function () {\n function Formatter() {\n this.buffer = '';\n }\n /**\n *\n * @see https://stackoverflow.com/a/13439711/4367683\n *\n * @param str\n * @param arr\n */\n Formatter.form = function (str, arr) {\n var i = -1;\n function callback(exp, p0, p1, p2, p3, p4) {\n if (exp === '%%')\n return '%';\n if (arr[++i] === undefined)\n return undefined;\n exp = p2 ? parseInt(p2.substr(1)) : undefined;\n var base = p3 ? parseInt(p3.substr(1)) : undefined;\n var val;\n switch (p4) {\n case 's':\n val = arr[i];\n break;\n case 'c':\n val = arr[i][0];\n break;\n case 'f':\n val = parseFloat(arr[i]).toFixed(exp);\n break;\n case 'p':\n val = parseFloat(arr[i]).toPrecision(exp);\n break;\n case 'e':\n val = parseFloat(arr[i]).toExponential(exp);\n break;\n case 'x':\n val = parseInt(arr[i]).toString(base ? base : 16);\n break;\n case 'd':\n val = parseFloat(parseInt(arr[i], base ? base : 10).toPrecision(exp)).toFixed(0);\n break;\n }\n val = typeof val === 'object' ? JSON.stringify(val) : (+val).toString(base);\n var size = parseInt(p1); /* padding size */\n var ch = p1 && (p1[0] + '') === '0' ? '0' : ' '; /* isnull? */\n while (val.length < size)\n val = p0 !== undefined ? val + ch : ch + val; /* isminus? */\n return val;\n }\n var regex = /%(-)?(0?[0-9]+)?([.][0-9]+)?([#][0-9]+)?([scfpexd%])/g;\n return str.replace(regex, callback);\n };\n /**\n *\n * @param append The new string to append.\n * @param args Argumets values to be formated.\n */\n Formatter.prototype.format = function (append) {\n var args = [];\n for (var _i = 1; _i < arguments.length; _i++) {\n args[_i - 1] = arguments[_i];\n }\n this.buffer += Formatter.form(append, args);\n };\n /**\n * Returns the Formatter string value.\n */\n Formatter.prototype.toString = function () {\n return this.buffer;\n };\n return Formatter;\n}());\nexport default Formatter;\n","/**\n * Ponyfill for Java's Integer class.\n */\nvar Integer = /** @class */ (function () {\n function Integer() {\n }\n Integer.numberOfTrailingZeros = function (i) {\n var y;\n if (i === 0)\n return 32;\n var n = 31;\n y = i << 16;\n if (y !== 0) {\n n -= 16;\n i = y;\n }\n y = i << 8;\n if (y !== 0) {\n n -= 8;\n i = y;\n }\n y = i << 4;\n if (y !== 0) {\n n -= 4;\n i = y;\n }\n y = i << 2;\n if (y !== 0) {\n n -= 2;\n i = y;\n }\n return n - ((i << 1) >>> 31);\n };\n Integer.numberOfLeadingZeros = function (i) {\n // HD, Figure 5-6\n if (i === 0) {\n return 32;\n }\n var n = 1;\n if (i >>> 16 === 0) {\n n += 16;\n i <<= 16;\n }\n if (i >>> 24 === 0) {\n n += 8;\n i <<= 8;\n }\n if (i >>> 28 === 0) {\n n += 4;\n i <<= 4;\n }\n if (i >>> 30 === 0) {\n n += 2;\n i <<= 2;\n }\n n -= i >>> 31;\n return n;\n };\n Integer.toHexString = function (i) {\n return i.toString(16);\n };\n Integer.toBinaryString = function (intNumber) {\n return String(parseInt(String(intNumber), 2));\n };\n // Returns the number of one-bits in the two's complement binary representation of the specified int value. This function is sometimes referred to as the population count.\n // Returns:\n // the number of one-bits in the two's complement binary representation of the specified int value.\n Integer.bitCount = function (i) {\n // HD, Figure 5-2\n i = i - ((i >>> 1) & 0x55555555);\n i = (i & 0x33333333) + ((i >>> 2) & 0x33333333);\n i = (i + (i >>> 4)) & 0x0f0f0f0f;\n i = i + (i >>> 8);\n i = i + (i >>> 16);\n return i & 0x3f;\n };\n Integer.truncDivision = function (dividend, divisor) {\n return Math.trunc(dividend / divisor);\n };\n /**\n * Converts A string to an integer.\n * @param s A string to convert into a number.\n * @param radix A value between 2 and 36 that specifies the base of the number in numString. If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. All other strings are considered decimal.\n */\n Integer.parseInt = function (num, radix) {\n if (radix === void 0) { radix = undefined; }\n return parseInt(num, radix);\n };\n Integer.MIN_VALUE_32_BITS = -2147483648;\n Integer.MAX_VALUE = Number.MAX_SAFE_INTEGER;\n return Integer;\n}());\nexport default Integer;\n","/**\n * Ponyfill for Java's Long class.\n */\nvar Long = /** @class */ (function () {\n function Long() {\n }\n /**\n * Parses a string to a number, since JS has no really Int64.\n *\n * @param num Numeric string.\n * @param radix Destination radix.\n */\n Long.parseLong = function (num, radix) {\n if (radix === void 0) { radix = undefined; }\n return parseInt(num, radix);\n };\n return Long;\n}());\nexport default Long;\n","import IndexOutOfBoundsException from '../IndexOutOfBoundsException';\nimport NullPointerException from '../NullPointerException';\n/*\n * Copyright (c) 1994, 2004, Oracle and/or its affiliates. All rights reserved.\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * This code is free software; you can redistribute it and/or modify it\n * under the terms of the GNU General Public License version 2 only, as\n * published by the Free Software Foundation. Oracle designates this\n * particular file as subject to the \"Classpath\" exception as provided\n * by Oracle in the LICENSE file that accompanied this code.\n *\n * This code is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License\n * version 2 for more details (a copy is included in the LICENSE file that\n * accompanied this code).\n *\n * You should have received a copy of the GNU General Public License version\n * 2 along with this work; if not, write to the Free Software Foundation,\n * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.\n *\n * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA\n * or visit www.oracle.com if you need additional information or have any\n * questions.\n */\n// package java.io;\n/**\n * This abstract class is the superclass of all classes representing\n * an output stream of bytes. An output stream accepts output bytes\n * and sends them to some sink.\n * \n * Applications that need to define a subclass of\n * \n * The \n * If \n * If \n * If the intended destination of this stream is an abstraction provided by\n * the underlying operating system, for example a file, then flushing the\n * stream guarantees only that bytes previously written to the stream are\n * passed to the operating system for writing; it does not guarantee that\n * they are actually written to a physical device such as a disk drive.\n * \n * The \n * The Today is {{today | date}} Or if you prefer, {{today | date:'fullDate'}} The time is {{today | date:'h:mm a z'}}}\n * @return String decoded from the buffer's contents.\n * @exception UnsupportedEncodingException\n * If the named charset is not supported\n * @since JDK1.1\n */\n ByteArrayOutputStream.prototype.toString_string = function (charsetName) {\n return new String(this.buf /*, 0, this.count, charsetName*/).toString();\n };\n /**\n * Creates a newly allocated string. Its size is the current size of\n * the output stream and the valid contents of the buffer have been\n * copied into it. Each character c in the resulting string is\n * constructed from the corresponding element b in the byte\n * array such that:\n *
\n *\n * @deprecated This method does not properly convert bytes into characters.\n * As of JDK 1.1, the preferred way to do this is via the\n * \n * c == (char)(((hibyte & 0xff) << 8) | (b & 0xff))\n *
toString(String enc)
method, which takes an encoding-name\n * argument, or the toString()
method, which uses the\n * platform's default character encoding.\n *\n * @param hibyte the high byte of each resulting Unicode character.\n * @return the current contents of the output stream, as a string.\n * @see java.io.ByteArrayOutputStream#size()\n * @see java.io.ByteArrayOutputStream#toString(String)\n * @see java.io.ByteArrayOutputStream#toString()\n */\n // @Deprecated\n ByteArrayOutputStream.prototype.toString_number = function (hibyte) {\n return new String(this.buf /*, hibyte, 0, this.count*/).toString();\n };\n /**\n * Closing a ByteArrayOutputStream has no effect. The methods in\n * this class can be called after the stream has been closed without\n * generating an IOException.\n * OutputStream
must always provide at least a method\n * that writes one byte of output.\n *\n * @author Arthur van Hoff\n * @see java.io.BufferedOutputStream\n * @see java.io.ByteArrayOutputStream\n * @see java.io.DataOutputStream\n * @see java.io.FilterOutputStream\n * @see java.io.InputStream\n * @see java.io.OutputStream#write(int)\n * @since JDK1.0\n */\nvar OutputStream /*implements Closeable, Flushable*/ = /** @class */ (function () {\n function OutputStream() {\n }\n /**\n * Writes b.length
bytes from the specified byte array\n * to this output stream. The general contract for write(b)
\n * is that it should have exactly the same effect as the call\n * write(b, 0, b.length)
.\n *\n * @param b the data.\n * @exception IOException if an I/O error occurs.\n * @see java.io.OutputStream#write(byte[], int, int)\n */\n OutputStream.prototype.writeBytes = function (b) {\n this.writeBytesOffset(b, 0, b.length);\n };\n /**\n * Writes len
bytes from the specified byte array\n * starting at offset off
to this output stream.\n * The general contract for write(b, off, len)
is that\n * some of the bytes in the array b
are written to the\n * output stream in order; element b[off]
is the first\n * byte written and b[off+len-1]
is the last byte written\n * by this operation.\n * write
method of OutputStream
calls\n * the write method of one argument on each of the bytes to be\n * written out. Subclasses are encouraged to override this method and\n * provide a more efficient implementation.\n * b
is null
, a\n * NullPointerException
is thrown.\n * off
is negative, or len
is negative, or\n * off+len
is greater than the length of the array\n * b
, then an IndexOutOfBoundsException is thrown.\n *\n * @param b the data.\n * @param off the start offset in the data.\n * @param len the number of bytes to write.\n * @exception IOException if an I/O error occurs. In particular,\n * an IOException
is thrown if the output\n * stream is closed.\n */\n OutputStream.prototype.writeBytesOffset = function (b, off, len) {\n if (b == null) {\n throw new NullPointerException();\n }\n else if ((off < 0) || (off > b.length) || (len < 0) ||\n ((off + len) > b.length) || ((off + len) < 0)) {\n throw new IndexOutOfBoundsException();\n }\n else if (len === 0) {\n return;\n }\n for (var i = 0; i < len; i++) {\n this.write(b[off + i]);\n }\n };\n /**\n * Flushes this output stream and forces any buffered output bytes\n * to be written out. The general contract of flush
is\n * that calling it is an indication that, if any bytes previously\n * written have been buffered by the implementation of the output\n * stream, such bytes should immediately be written to their\n * intended destination.\n * flush
method of OutputStream
does nothing.\n *\n * @exception IOException if an I/O error occurs.\n */\n OutputStream.prototype.flush = function () {\n };\n /**\n * Closes this output stream and releases any system resources\n * associated with this stream. The general contract of close
\n * is that it closes the output stream. A closed stream cannot perform\n * output operations and cannot be reopened.\n * close
method of OutputStream
does nothing.\n *\n * @exception IOException if an I/O error occurs.\n */\n OutputStream.prototype.close = function () {\n };\n return OutputStream;\n}());\nexport default OutputStream;\n","import CharacterSetECI from '../common/CharacterSetECI';\n/**\n * Just to make a shortcut between Java code and TS code.\n */\nvar StandardCharsets = /** @class */ (function () {\n function StandardCharsets() {\n }\n StandardCharsets.ISO_8859_1 = CharacterSetECI.ISO8859_1;\n return StandardCharsets;\n}());\nexport default StandardCharsets;\n","import StringUtils from '../common/StringUtils';\nvar StringBuilder = /** @class */ (function () {\n function StringBuilder(value) {\n if (value === void 0) { value = ''; }\n this.value = value;\n }\n StringBuilder.prototype.enableDecoding = function (encoding) {\n this.encoding = encoding;\n return this;\n };\n StringBuilder.prototype.append = function (s) {\n if (typeof s === 'string') {\n this.value += s.toString();\n }\n else if (this.encoding) {\n // use passed format (fromCharCode will return UTF8 encoding)\n this.value += StringUtils.castAsNonUtf8Char(s, this.encoding);\n }\n else {\n // correctly converts from UTF-8, but not other encodings\n this.value += String.fromCharCode(s);\n }\n return this;\n };\n StringBuilder.prototype.appendChars = function (str, offset, len) {\n for (var i = offset; offset < offset + len; i++) {\n this.append(str[i]);\n }\n return this;\n };\n StringBuilder.prototype.length = function () {\n return this.value.length;\n };\n StringBuilder.prototype.charAt = function (n) {\n return this.value.charAt(n);\n };\n StringBuilder.prototype.deleteCharAt = function (n) {\n this.value = this.value.substr(0, n) + this.value.substring(n + 1);\n };\n StringBuilder.prototype.setCharAt = function (n, c) {\n this.value = this.value.substr(0, n) + c + this.value.substr(n + 1);\n };\n StringBuilder.prototype.substring = function (start, end) {\n return this.value.substring(start, end);\n };\n /**\n * @note helper method for RSS Expanded\n */\n StringBuilder.prototype.setLengthToZero = function () {\n this.value = '';\n };\n StringBuilder.prototype.toString = function () {\n return this.value;\n };\n StringBuilder.prototype.insert = function (n, c) {\n this.value = this.value.substring(0, n) + c + this.value.substring(n);\n };\n return StringBuilder;\n}());\nexport default StringBuilder;\n","import UnsupportedOperationException from '../UnsupportedOperationException';\nimport CharacterSetECI from '../common/CharacterSetECI';\n/**\n * Responsible for en/decoding strings.\n */\nvar StringEncoding = /** @class */ (function () {\n function StringEncoding() {\n }\n /**\n * Decodes some Uint8Array to a string format.\n */\n StringEncoding.decode = function (bytes, encoding) {\n var encodingName = this.encodingName(encoding);\n if (this.customDecoder) {\n return this.customDecoder(bytes, encodingName);\n }\n // Increases browser support.\n if (typeof TextDecoder === 'undefined' || this.shouldDecodeOnFallback(encodingName)) {\n return this.decodeFallback(bytes, encodingName);\n }\n return new TextDecoder(encodingName).decode(bytes);\n };\n /**\n * Checks if the decoding method should use the fallback for decoding\n * once Node TextDecoder doesn't support all encoding formats.\n *\n * @param encodingName\n */\n StringEncoding.shouldDecodeOnFallback = function (encodingName) {\n return !StringEncoding.isBrowser() && encodingName === 'ISO-8859-1';\n };\n /**\n * Encodes some string into a Uint8Array.\n */\n StringEncoding.encode = function (s, encoding) {\n var encodingName = this.encodingName(encoding);\n if (this.customEncoder) {\n return this.customEncoder(s, encodingName);\n }\n // Increases browser support.\n if (typeof TextEncoder === 'undefined') {\n return this.encodeFallback(s);\n }\n // TextEncoder only encodes to UTF8 by default as specified by encoding.spec.whatwg.org\n return new TextEncoder().encode(s);\n };\n StringEncoding.isBrowser = function () {\n return (typeof window !== 'undefined' && {}.toString.call(window) === '[object Window]');\n };\n /**\n * Returns the string value from some encoding character set.\n */\n StringEncoding.encodingName = function (encoding) {\n return typeof encoding === 'string'\n ? encoding\n : encoding.getName();\n };\n /**\n * Returns character set from some encoding character set.\n */\n StringEncoding.encodingCharacterSet = function (encoding) {\n if (encoding instanceof CharacterSetECI) {\n return encoding;\n }\n return CharacterSetECI.getCharacterSetECIByName(encoding);\n };\n /**\n * Runs a fallback for the native decoding funcion.\n */\n StringEncoding.decodeFallback = function (bytes, encoding) {\n var characterSet = this.encodingCharacterSet(encoding);\n if (StringEncoding.isDecodeFallbackSupported(characterSet)) {\n var s = '';\n for (var i = 0, length_1 = bytes.length; i < length_1; i++) {\n var h = bytes[i].toString(16);\n if (h.length < 2) {\n h = '0' + h;\n }\n s += '%' + h;\n }\n return decodeURIComponent(s);\n }\n if (characterSet.equals(CharacterSetECI.UnicodeBigUnmarked)) {\n return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer));\n }\n throw new UnsupportedOperationException(\"Encoding \" + this.encodingName(encoding) + \" not supported by fallback.\");\n };\n StringEncoding.isDecodeFallbackSupported = function (characterSet) {\n return characterSet.equals(CharacterSetECI.UTF8) ||\n characterSet.equals(CharacterSetECI.ISO8859_1) ||\n characterSet.equals(CharacterSetECI.ASCII);\n };\n /**\n * Runs a fallback for the native encoding funcion.\n *\n * @see https://stackoverflow.com/a/17192845/4367683\n */\n StringEncoding.encodeFallback = function (s) {\n var encodedURIstring = btoa(unescape(encodeURIComponent(s)));\n var charList = encodedURIstring.split('');\n var uintArray = [];\n for (var i = 0; i < charList.length; i++) {\n uintArray.push(charList[i].charCodeAt(0));\n }\n return new Uint8Array(uintArray);\n };\n return StringEncoding;\n}());\nexport default StringEncoding;\n","var System = /** @class */ (function () {\n function System() {\n }\n // public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)\n /**\n * Makes a copy of a array.\n */\n System.arraycopy = function (src, srcPos, dest, destPos, length) {\n // TODO: better use split or set?\n while (length--) {\n dest[destPos++] = src[srcPos++];\n }\n };\n /**\n * Returns the current time in milliseconds.\n */\n System.currentTimeMillis = function () {\n return Date.now();\n };\n return System;\n}());\nexport default System;\n","export * from './browser';\n// Exceptions\nexport { default as ArgumentException } from './core/ArgumentException';\nexport { default as ArithmeticException } from './core/ArithmeticException';\nexport { default as ChecksumException } from './core/ChecksumException';\nexport { default as Exception } from './core/Exception';\nexport { default as FormatException } from './core/FormatException';\nexport { default as IllegalArgumentException } from './core/IllegalArgumentException';\nexport { default as IllegalStateException } from './core/IllegalStateException';\nexport { default as NotFoundException } from './core/NotFoundException';\nexport { default as ReaderException } from './core/ReaderException';\nexport { default as ReedSolomonException } from './core/ReedSolomonException';\nexport { default as UnsupportedOperationException } from './core/UnsupportedOperationException';\nexport { default as WriterException } from './core/WriterException';\n// core\nexport { default as BarcodeFormat } from './core/BarcodeFormat';\nexport { default as Binarizer } from './core/Binarizer';\nexport { default as BinaryBitmap } from './core/BinaryBitmap';\nexport { default as DecodeHintType } from './core/DecodeHintType';\nexport { default as InvertedLuminanceSource } from './core/InvertedLuminanceSource';\nexport { default as LuminanceSource } from './core/LuminanceSource';\nexport { default as MultiFormatReader } from './core/MultiFormatReader';\nexport { default as MultiFormatWriter } from './core/MultiFormatWriter';\nexport { default as PlanarYUVLuminanceSource } from './core/PlanarYUVLuminanceSource';\nexport { default as Result } from './core/Result';\nexport { default as ResultMetadataType } from './core/ResultMetadataType';\nexport { default as RGBLuminanceSource } from './core/RGBLuminanceSource';\nexport { default as ResultPoint } from './core/ResultPoint';\n// core/util\nexport { default as ZXingSystem } from './core/util/System';\nexport { default as ZXingStringBuilder } from './core/util/StringBuilder';\nexport { default as ZXingStringEncoding } from './core/util/StringEncoding';\nexport { default as ZXingCharset } from './core/util/Charset';\nexport { default as ZXingArrays } from './core/util/Arrays';\nexport { default as ZXingStandardCharsets } from './core/util/StandardCharsets';\nexport { default as ZXingInteger } from './core/util/Integer';\n// core/common\nexport { default as BitArray } from './core/common/BitArray';\nexport { default as BitMatrix } from './core/common/BitMatrix';\nexport { default as BitSource } from './core/common/BitSource';\nexport { default as CharacterSetECI } from './core/common/CharacterSetECI';\nexport { default as DecoderResult } from './core/common/DecoderResult';\nexport { default as DefaultGridSampler } from './core/common/DefaultGridSampler';\nexport { default as DetectorResult } from './core/common/DetectorResult';\nexport { default as EncodeHintType } from './core/EncodeHintType';\nexport { default as GlobalHistogramBinarizer } from './core/common/GlobalHistogramBinarizer';\nexport { default as GridSampler } from './core/common/GridSampler';\nexport { default as GridSamplerInstance } from './core/common/GridSamplerInstance';\nexport { default as HybridBinarizer } from './core/common/HybridBinarizer';\nexport { default as PerspectiveTransform } from './core/common/PerspectiveTransform';\nexport { default as StringUtils } from './core/common/StringUtils';\n// core/common/detector\nexport { default as MathUtils } from './core/common/detector/MathUtils';\n// export { default as MonochromeRectangleDetector } from './core/common/detector/MonochromeRectangleDetector';\nexport { default as WhiteRectangleDetector } from './core/common/detector/WhiteRectangleDetector';\n// core/common/reedsolomon\nexport { default as GenericGF } from './core/common/reedsolomon/GenericGF';\nexport { default as GenericGFPoly } from './core/common/reedsolomon/GenericGFPoly';\nexport { default as ReedSolomonDecoder } from './core/common/reedsolomon/ReedSolomonDecoder';\nexport { default as ReedSolomonEncoder } from './core/common/reedsolomon/ReedSolomonEncoder';\n// core/datamatrix\nexport { default as DataMatrixReader } from './core/datamatrix/DataMatrixReader';\nexport { default as DataMatrixDecodedBitStreamParser } from './core/datamatrix/decoder/DecodedBitStreamParser';\nexport { default as DataMatrixDefaultPlacement } from './core/datamatrix/encoder/DefaultPlacement';\nexport { default as DataMatrixErrorCorrection } from './core/datamatrix/encoder/ErrorCorrection';\nexport { default as DataMatrixHighLevelEncoder } from './core/datamatrix/encoder/HighLevelEncoder';\nexport { default as DataMatrixSymbolInfo } from './core/datamatrix/encoder/SymbolInfo';\nexport { SymbolShapeHint as DataMatrixSymbolShapeHint } from './core/datamatrix/encoder/constants';\nexport { default as DataMatrixWriter } from './core/datamatrix/DataMatrixWriter';\n// core/pdf417\nexport { default as PDF417Reader } from './core/pdf417/PDF417Reader';\nexport { default as PDF417ResultMetadata } from './core/pdf417/PDF417ResultMetadata';\nexport { default as PDF417DecodedBitStreamParser } from './core/pdf417/decoder/DecodedBitStreamParser';\nexport { default as PDF417DecoderErrorCorrection } from './core/pdf417/decoder/ec/ErrorCorrection';\n// core/twod/qrcode\nexport { default as QRCodeReader } from './core/qrcode/QRCodeReader';\nexport { default as QRCodeWriter } from './core/qrcode/QRCodeWriter';\nexport { default as QRCodeDecoderErrorCorrectionLevel } from './core/qrcode/decoder/ErrorCorrectionLevel';\nexport { default as QRCodeDecoderFormatInformation } from './core/qrcode/decoder/FormatInformation';\nexport { default as QRCodeVersion } from './core/qrcode/decoder/Version';\nexport { default as QRCodeMode } from './core/qrcode/decoder/Mode';\nexport { default as QRCodeDecodedBitStreamParser } from './core/qrcode/decoder/DecodedBitStreamParser';\nexport { default as QRCodeDataMask } from './core/qrcode/decoder/DataMask';\nexport { default as QRCodeEncoder } from './core/qrcode/encoder/Encoder';\nexport { default as QRCodeEncoderQRCode } from './core/qrcode/encoder/QRCode';\nexport { default as QRCodeMatrixUtil } from './core/qrcode/encoder/MatrixUtil';\nexport { default as QRCodeByteMatrix } from './core/qrcode/encoder/ByteMatrix';\nexport { default as QRCodeMaskUtil } from './core/qrcode/encoder/MaskUtil';\n// core/twod/aztec\nexport { default as AztecCodeReader } from './core/aztec/AztecReader';\nexport { default as AztecCodeWriter } from './core/aztec/AztecWriter';\nexport { default as AztecDetectorResult } from './core/aztec/AztecDetectorResult';\nexport { default as AztecEncoder } from './core/aztec/encoder/Encoder';\nexport { default as AztecHighLevelEncoder } from './core/aztec/encoder/HighLevelEncoder';\nexport { default as AztecCode } from './core/aztec/encoder/AztecCode';\nexport { default as AztecDecoder } from './core/aztec/decoder/Decoder';\nexport { default as AztecDetector } from './core/aztec/detector/Detector';\nexport { Point as AztecPoint } from './core/aztec/detector/Detector';\n// core/oned\nexport { default as OneDReader } from './core/oned/OneDReader';\nexport { default as EAN13Reader } from './core/oned/EAN13Reader';\nexport { default as Code128Reader } from './core/oned/Code128Reader';\nexport { default as ITFReader } from './core/oned/ITFReader';\nexport { default as Code39Reader } from './core/oned/Code39Reader';\nexport { default as Code93Reader } from './core/oned/Code93Reader';\nexport { default as RSS14Reader } from './core/oned/rss/RSS14Reader';\nexport { default as RSSExpandedReader } from './core/oned/rss/expanded/RSSExpandedReader';\nexport { default as AbstractExpandedDecoder } from './core/oned/rss/expanded/decoders/AbstractExpandedDecoder';\nexport { createDecoder as createAbstractExpandedDecoder } from './core/oned/rss/expanded/decoders/AbstractExpandedDecoderComplement';\nexport { default as MultiFormatOneDReader } from './core/oned/MultiFormatOneDReader';\nexport { default as CodaBarReader } from './core/oned/CodaBarReader';\n","exports.remove = removeDiacritics;\n\nvar replacementList = [\n {\n base: ' ',\n chars: \"\\u00A0\",\n }, {\n base: '0',\n chars: \"\\u07C0\",\n }, {\n base: 'A',\n chars: \"\\u24B6\\uFF21\\u00C0\\u00C1\\u00C2\\u1EA6\\u1EA4\\u1EAA\\u1EA8\\u00C3\\u0100\\u0102\\u1EB0\\u1EAE\\u1EB4\\u1EB2\\u0226\\u01E0\\u00C4\\u01DE\\u1EA2\\u00C5\\u01FA\\u01CD\\u0200\\u0202\\u1EA0\\u1EAC\\u1EB6\\u1E00\\u0104\\u023A\\u2C6F\",\n }, {\n base: 'AA',\n chars: \"\\uA732\",\n }, {\n base: 'AE',\n chars: \"\\u00C6\\u01FC\\u01E2\",\n }, {\n base: 'AO',\n chars: \"\\uA734\",\n }, {\n base: 'AU',\n chars: \"\\uA736\",\n }, {\n base: 'AV',\n chars: \"\\uA738\\uA73A\",\n }, {\n base: 'AY',\n chars: \"\\uA73C\",\n }, {\n base: 'B',\n chars: \"\\u24B7\\uFF22\\u1E02\\u1E04\\u1E06\\u0243\\u0181\",\n }, {\n base: 'C',\n chars: \"\\u24b8\\uff23\\uA73E\\u1E08\\u0106\\u0043\\u0108\\u010A\\u010C\\u00C7\\u0187\\u023B\",\n }, {\n base: 'D',\n chars: \"\\u24B9\\uFF24\\u1E0A\\u010E\\u1E0C\\u1E10\\u1E12\\u1E0E\\u0110\\u018A\\u0189\\u1D05\\uA779\",\n }, {\n base: 'Dh',\n chars: \"\\u00D0\",\n }, {\n base: 'DZ',\n chars: \"\\u01F1\\u01C4\",\n }, {\n base: 'Dz',\n chars: \"\\u01F2\\u01C5\",\n }, {\n base: 'E',\n chars: \"\\u025B\\u24BA\\uFF25\\u00C8\\u00C9\\u00CA\\u1EC0\\u1EBE\\u1EC4\\u1EC2\\u1EBC\\u0112\\u1E14\\u1E16\\u0114\\u0116\\u00CB\\u1EBA\\u011A\\u0204\\u0206\\u1EB8\\u1EC6\\u0228\\u1E1C\\u0118\\u1E18\\u1E1A\\u0190\\u018E\\u1D07\",\n }, {\n base: 'F',\n chars: \"\\uA77C\\u24BB\\uFF26\\u1E1E\\u0191\\uA77B\",\n }, {\n base: 'G',\n chars: \"\\u24BC\\uFF27\\u01F4\\u011C\\u1E20\\u011E\\u0120\\u01E6\\u0122\\u01E4\\u0193\\uA7A0\\uA77D\\uA77E\\u0262\",\n }, {\n base: 'H',\n chars: \"\\u24BD\\uFF28\\u0124\\u1E22\\u1E26\\u021E\\u1E24\\u1E28\\u1E2A\\u0126\\u2C67\\u2C75\\uA78D\",\n }, {\n base: 'I',\n chars: \"\\u24BE\\uFF29\\xCC\\xCD\\xCE\\u0128\\u012A\\u012C\\u0130\\xCF\\u1E2E\\u1EC8\\u01CF\\u0208\\u020A\\u1ECA\\u012E\\u1E2C\\u0197\",\n }, {\n base: 'J',\n chars: \"\\u24BF\\uFF2A\\u0134\\u0248\\u0237\",\n }, {\n base: 'K',\n chars: \"\\u24C0\\uFF2B\\u1E30\\u01E8\\u1E32\\u0136\\u1E34\\u0198\\u2C69\\uA740\\uA742\\uA744\\uA7A2\",\n }, {\n base: 'L',\n chars: \"\\u24C1\\uFF2C\\u013F\\u0139\\u013D\\u1E36\\u1E38\\u013B\\u1E3C\\u1E3A\\u0141\\u023D\\u2C62\\u2C60\\uA748\\uA746\\uA780\",\n }, {\n base: 'LJ',\n chars: \"\\u01C7\",\n }, {\n base: 'Lj',\n chars: \"\\u01C8\",\n }, {\n base: 'M',\n chars: \"\\u24C2\\uFF2D\\u1E3E\\u1E40\\u1E42\\u2C6E\\u019C\\u03FB\",\n }, {\n base: 'N',\n chars: \"\\uA7A4\\u0220\\u24C3\\uFF2E\\u01F8\\u0143\\xD1\\u1E44\\u0147\\u1E46\\u0145\\u1E4A\\u1E48\\u019D\\uA790\\u1D0E\",\n }, {\n base: 'NJ',\n chars: \"\\u01CA\",\n }, {\n base: 'Nj',\n chars: \"\\u01CB\",\n }, {\n base: 'O',\n chars: \"\\u24C4\\uFF2F\\xD2\\xD3\\xD4\\u1ED2\\u1ED0\\u1ED6\\u1ED4\\xD5\\u1E4C\\u022C\\u1E4E\\u014C\\u1E50\\u1E52\\u014E\\u022E\\u0230\\xD6\\u022A\\u1ECE\\u0150\\u01D1\\u020C\\u020E\\u01A0\\u1EDC\\u1EDA\\u1EE0\\u1EDE\\u1EE2\\u1ECC\\u1ED8\\u01EA\\u01EC\\xD8\\u01FE\\u0186\\u019F\\uA74A\\uA74C\",\n }, {\n base: 'OE',\n chars: \"\\u0152\",\n }, {\n base: 'OI',\n chars: \"\\u01A2\",\n }, {\n base: 'OO',\n chars: \"\\uA74E\",\n }, {\n base: 'OU',\n chars: \"\\u0222\",\n }, {\n base: 'P',\n chars: \"\\u24C5\\uFF30\\u1E54\\u1E56\\u01A4\\u2C63\\uA750\\uA752\\uA754\",\n }, {\n base: 'Q',\n chars: \"\\u24C6\\uFF31\\uA756\\uA758\\u024A\",\n }, {\n base: 'R',\n chars: \"\\u24C7\\uFF32\\u0154\\u1E58\\u0158\\u0210\\u0212\\u1E5A\\u1E5C\\u0156\\u1E5E\\u024C\\u2C64\\uA75A\\uA7A6\\uA782\",\n }, {\n base: 'S',\n chars: \"\\u24C8\\uFF33\\u1E9E\\u015A\\u1E64\\u015C\\u1E60\\u0160\\u1E66\\u1E62\\u1E68\\u0218\\u015E\\u2C7E\\uA7A8\\uA784\",\n }, {\n base: 'T',\n chars: \"\\u24C9\\uFF34\\u1E6A\\u0164\\u1E6C\\u021A\\u0162\\u1E70\\u1E6E\\u0166\\u01AC\\u01AE\\u023E\\uA786\",\n }, {\n base: 'Th',\n chars: \"\\u00DE\",\n }, {\n base: 'TZ',\n chars: \"\\uA728\",\n }, {\n base: 'U',\n chars: \"\\u24CA\\uFF35\\xD9\\xDA\\xDB\\u0168\\u1E78\\u016A\\u1E7A\\u016C\\xDC\\u01DB\\u01D7\\u01D5\\u01D9\\u1EE6\\u016E\\u0170\\u01D3\\u0214\\u0216\\u01AF\\u1EEA\\u1EE8\\u1EEE\\u1EEC\\u1EF0\\u1EE4\\u1E72\\u0172\\u1E76\\u1E74\\u0244\",\n }, {\n base: 'V',\n chars: \"\\u24CB\\uFF36\\u1E7C\\u1E7E\\u01B2\\uA75E\\u0245\",\n }, {\n base: 'VY',\n chars: \"\\uA760\",\n }, {\n base: 'W',\n chars: \"\\u24CC\\uFF37\\u1E80\\u1E82\\u0174\\u1E86\\u1E84\\u1E88\\u2C72\",\n }, {\n base: 'X',\n chars: \"\\u24CD\\uFF38\\u1E8A\\u1E8C\",\n }, {\n base: 'Y',\n chars: \"\\u24CE\\uFF39\\u1EF2\\xDD\\u0176\\u1EF8\\u0232\\u1E8E\\u0178\\u1EF6\\u1EF4\\u01B3\\u024E\\u1EFE\",\n }, {\n base: 'Z',\n chars: \"\\u24CF\\uFF3A\\u0179\\u1E90\\u017B\\u017D\\u1E92\\u1E94\\u01B5\\u0224\\u2C7F\\u2C6B\\uA762\",\n }, {\n base: 'a',\n chars: \"\\u24D0\\uFF41\\u1E9A\\u00E0\\u00E1\\u00E2\\u1EA7\\u1EA5\\u1EAB\\u1EA9\\u00E3\\u0101\\u0103\\u1EB1\\u1EAF\\u1EB5\\u1EB3\\u0227\\u01E1\\u00E4\\u01DF\\u1EA3\\u00E5\\u01FB\\u01CE\\u0201\\u0203\\u1EA1\\u1EAD\\u1EB7\\u1E01\\u0105\\u2C65\\u0250\\u0251\",\n }, {\n base: 'aa',\n chars: \"\\uA733\",\n }, {\n base: 'ae',\n chars: \"\\u00E6\\u01FD\\u01E3\",\n }, {\n base: 'ao',\n chars: \"\\uA735\",\n }, {\n base: 'au',\n chars: \"\\uA737\",\n }, {\n base: 'av',\n chars: \"\\uA739\\uA73B\",\n }, {\n base: 'ay',\n chars: \"\\uA73D\",\n }, {\n base: 'b',\n chars: \"\\u24D1\\uFF42\\u1E03\\u1E05\\u1E07\\u0180\\u0183\\u0253\\u0182\",\n }, {\n base: 'c',\n chars: \"\\uFF43\\u24D2\\u0107\\u0109\\u010B\\u010D\\u00E7\\u1E09\\u0188\\u023C\\uA73F\\u2184\",\n }, {\n base: 'd',\n chars: \"\\u24D3\\uFF44\\u1E0B\\u010F\\u1E0D\\u1E11\\u1E13\\u1E0F\\u0111\\u018C\\u0256\\u0257\\u018B\\u13E7\\u0501\\uA7AA\",\n }, {\n base: 'dh',\n chars: \"\\u00F0\",\n }, {\n base: 'dz',\n chars: \"\\u01F3\\u01C6\",\n }, {\n base: 'e',\n chars: \"\\u24D4\\uFF45\\u00E8\\u00E9\\u00EA\\u1EC1\\u1EBF\\u1EC5\\u1EC3\\u1EBD\\u0113\\u1E15\\u1E17\\u0115\\u0117\\u00EB\\u1EBB\\u011B\\u0205\\u0207\\u1EB9\\u1EC7\\u0229\\u1E1D\\u0119\\u1E19\\u1E1B\\u0247\\u01DD\",\n }, {\n base: 'f',\n chars: \"\\u24D5\\uFF46\\u1E1F\\u0192\",\n }, {\n base: 'ff',\n chars: \"\\uFB00\",\n }, {\n base: 'fi',\n chars: \"\\uFB01\",\n }, {\n base: 'fl',\n chars: \"\\uFB02\",\n }, {\n base: 'ffi',\n chars: \"\\uFB03\",\n }, {\n base: 'ffl',\n chars: \"\\uFB04\",\n }, {\n base: 'g',\n chars: \"\\u24D6\\uFF47\\u01F5\\u011D\\u1E21\\u011F\\u0121\\u01E7\\u0123\\u01E5\\u0260\\uA7A1\\uA77F\\u1D79\",\n }, {\n base: 'h',\n chars: \"\\u24D7\\uFF48\\u0125\\u1E23\\u1E27\\u021F\\u1E25\\u1E29\\u1E2B\\u1E96\\u0127\\u2C68\\u2C76\\u0265\",\n }, {\n base: 'hv',\n chars: \"\\u0195\",\n }, {\n base: 'i',\n chars: \"\\u24D8\\uFF49\\xEC\\xED\\xEE\\u0129\\u012B\\u012D\\xEF\\u1E2F\\u1EC9\\u01D0\\u0209\\u020B\\u1ECB\\u012F\\u1E2D\\u0268\\u0131\",\n }, {\n base: 'j',\n chars: \"\\u24D9\\uFF4A\\u0135\\u01F0\\u0249\",\n }, {\n base: 'k',\n chars: \"\\u24DA\\uFF4B\\u1E31\\u01E9\\u1E33\\u0137\\u1E35\\u0199\\u2C6A\\uA741\\uA743\\uA745\\uA7A3\",\n }, {\n base: 'l',\n chars: \"\\u24DB\\uFF4C\\u0140\\u013A\\u013E\\u1E37\\u1E39\\u013C\\u1E3D\\u1E3B\\u017F\\u0142\\u019A\\u026B\\u2C61\\uA749\\uA781\\uA747\\u026D\",\n }, {\n base: 'lj',\n chars: \"\\u01C9\",\n }, {\n base: 'm',\n chars: \"\\u24DC\\uFF4D\\u1E3F\\u1E41\\u1E43\\u0271\\u026F\",\n }, {\n base: 'n',\n chars: \"\\u24DD\\uFF4E\\u01F9\\u0144\\xF1\\u1E45\\u0148\\u1E47\\u0146\\u1E4B\\u1E49\\u019E\\u0272\\u0149\\uA791\\uA7A5\\u043B\\u0509\",\n }, {\n base: 'nj',\n chars: \"\\u01CC\",\n }, {\n base: 'o',\n chars: \"\\u24DE\\uFF4F\\xF2\\xF3\\xF4\\u1ED3\\u1ED1\\u1ED7\\u1ED5\\xF5\\u1E4D\\u022D\\u1E4F\\u014D\\u1E51\\u1E53\\u014F\\u022F\\u0231\\xF6\\u022B\\u1ECF\\u0151\\u01D2\\u020D\\u020F\\u01A1\\u1EDD\\u1EDB\\u1EE1\\u1EDF\\u1EE3\\u1ECD\\u1ED9\\u01EB\\u01ED\\xF8\\u01FF\\uA74B\\uA74D\\u0275\\u0254\\u1D11\",\n }, {\n base: 'oe',\n chars: \"\\u0153\",\n }, {\n base: 'oi',\n chars: \"\\u01A3\",\n }, {\n base: 'oo',\n chars: \"\\uA74F\",\n }, {\n base: 'ou',\n chars: \"\\u0223\",\n }, {\n base: 'p',\n chars: \"\\u24DF\\uFF50\\u1E55\\u1E57\\u01A5\\u1D7D\\uA751\\uA753\\uA755\\u03C1\",\n }, {\n base: 'q',\n chars: \"\\u24E0\\uFF51\\u024B\\uA757\\uA759\",\n }, {\n base: 'r',\n chars: \"\\u24E1\\uFF52\\u0155\\u1E59\\u0159\\u0211\\u0213\\u1E5B\\u1E5D\\u0157\\u1E5F\\u024D\\u027D\\uA75B\\uA7A7\\uA783\",\n }, {\n base: 's',\n chars: \"\\u24E2\\uFF53\\u015B\\u1E65\\u015D\\u1E61\\u0161\\u1E67\\u1E63\\u1E69\\u0219\\u015F\\u023F\\uA7A9\\uA785\\u1E9B\\u0282\",\n }, {\n base: 'ss',\n chars: \"\\xDF\",\n }, {\n base: 't',\n chars: \"\\u24E3\\uFF54\\u1E6B\\u1E97\\u0165\\u1E6D\\u021B\\u0163\\u1E71\\u1E6F\\u0167\\u01AD\\u0288\\u2C66\\uA787\",\n }, {\n base: 'th',\n chars: \"\\u00FE\",\n }, {\n base: 'tz',\n chars: \"\\uA729\",\n }, {\n base: 'u',\n chars: \"\\u24E4\\uFF55\\xF9\\xFA\\xFB\\u0169\\u1E79\\u016B\\u1E7B\\u016D\\xFC\\u01DC\\u01D8\\u01D6\\u01DA\\u1EE7\\u016F\\u0171\\u01D4\\u0215\\u0217\\u01B0\\u1EEB\\u1EE9\\u1EEF\\u1EED\\u1EF1\\u1EE5\\u1E73\\u0173\\u1E77\\u1E75\\u0289\",\n }, {\n base: 'v',\n chars: \"\\u24E5\\uFF56\\u1E7D\\u1E7F\\u028B\\uA75F\\u028C\",\n }, {\n base: 'vy',\n chars: \"\\uA761\",\n }, {\n base: 'w',\n chars: \"\\u24E6\\uFF57\\u1E81\\u1E83\\u0175\\u1E87\\u1E85\\u1E98\\u1E89\\u2C73\",\n }, {\n base: 'x',\n chars: \"\\u24E7\\uFF58\\u1E8B\\u1E8D\",\n }, {\n base: 'y',\n chars: \"\\u24E8\\uFF59\\u1EF3\\xFD\\u0177\\u1EF9\\u0233\\u1E8F\\xFF\\u1EF7\\u1E99\\u1EF5\\u01B4\\u024F\\u1EFF\",\n }, {\n base: 'z',\n chars: \"\\u24E9\\uFF5A\\u017A\\u1E91\\u017C\\u017E\\u1E93\\u1E95\\u01B6\\u0225\\u0240\\u2C6C\\uA763\",\n }\n];\n\nvar diacriticsMap = {};\nfor (var i = 0; i < replacementList.length; i += 1) {\n var chars = replacementList[i].chars;\n for (var j = 0; j < chars.length; j += 1) {\n diacriticsMap[chars[j]] = replacementList[i].base;\n }\n}\n\nfunction removeDiacritics(str) {\n return str.replace(/[^\\u0000-\\u007e]/g, function(c) {\n return diacriticsMap[c] || c;\n });\n}\n\nexports.replacementList = replacementList;\nexports.diacriticsMap = diacriticsMap;\n","var moment = module.exports = require(\"./moment-timezone\");\nmoment.tz.load(require('./data/packed/latest.json'));\n","//! moment-timezone.js\n//! version : 0.5.46\n//! Copyright (c) JS Foundation and other contributors\n//! license : MIT\n//! github.com/moment/moment-timezone\n\n(function (root, factory) {\n\t\"use strict\";\n\n\t/*global define*/\n\tif (typeof module === 'object' && module.exports) {\n\t\tmodule.exports = factory(require('moment')); // Node\n\t} else if (typeof define === 'function' && define.amd) {\n\t\tdefine(['moment'], factory); // AMD\n\t} else {\n\t\tfactory(root.moment); // Browser\n\t}\n}(this, function (moment) {\n\t\"use strict\";\n\n\t// Resolves es6 module loading issue\n\tif (moment.version === undefined && moment.default) {\n\t\tmoment = moment.default;\n\t}\n\n\t// Do not load moment-timezone a second time.\n\t// if (moment.tz !== undefined) {\n\t// \tlogError('Moment Timezone ' + moment.tz.version + ' was already loaded ' + (moment.tz.dataVersion ? 'with data from ' : 'without any data') + moment.tz.dataVersion);\n\t// \treturn moment;\n\t// }\n\n\tvar VERSION = \"0.5.46\",\n\t\tzones = {},\n\t\tlinks = {},\n\t\tcountries = {},\n\t\tnames = {},\n\t\tguesses = {},\n\t\tcachedGuess;\n\n\tif (!moment || typeof moment.version !== 'string') {\n\t\tlogError('Moment Timezone requires Moment.js. See https://momentjs.com/timezone/docs/#/use-it/browser/');\n\t}\n\n\tvar momentVersion = moment.version.split('.'),\n\t\tmajor = +momentVersion[0],\n\t\tminor = +momentVersion[1];\n\n\t// Moment.js version check\n\tif (major < 2 || (major === 2 && minor < 6)) {\n\t\tlogError('Moment Timezone requires Moment.js >= 2.6.0. You are using Moment.js ' + moment.version + '. See momentjs.com');\n\t}\n\n\t/************************************\n\t\tUnpacking\n\t************************************/\n\n\tfunction charCodeToInt(charCode) {\n\t\tif (charCode > 96) {\n\t\t\treturn charCode - 87;\n\t\t} else if (charCode > 64) {\n\t\t\treturn charCode - 29;\n\t\t}\n\t\treturn charCode - 48;\n\t}\n\n\tfunction unpackBase60(string) {\n\t\tvar i = 0,\n\t\t\tparts = string.split('.'),\n\t\t\twhole = parts[0],\n\t\t\tfractional = parts[1] || '',\n\t\t\tmultiplier = 1,\n\t\t\tnum,\n\t\t\tout = 0,\n\t\t\tsign = 1;\n\n\t\t// handle negative numbers\n\t\tif (string.charCodeAt(0) === 45) {\n\t\t\ti = 1;\n\t\t\tsign = -1;\n\t\t}\n\n\t\t// handle digits before the decimal\n\t\tfor (i; i < whole.length; i++) {\n\t\t\tnum = charCodeToInt(whole.charCodeAt(i));\n\t\t\tout = 60 * out + num;\n\t\t}\n\n\t\t// handle digits after the decimal\n\t\tfor (i = 0; i < fractional.length; i++) {\n\t\t\tmultiplier = multiplier / 60;\n\t\t\tnum = charCodeToInt(fractional.charCodeAt(i));\n\t\t\tout += num * multiplier;\n\t\t}\n\n\t\treturn out * sign;\n\t}\n\n\tfunction arrayToInt (array) {\n\t\tfor (var i = 0; i < array.length; i++) {\n\t\t\tarray[i] = unpackBase60(array[i]);\n\t\t}\n\t}\n\n\tfunction intToUntil (array, length) {\n\t\tfor (var i = 0; i < length; i++) {\n\t\t\tarray[i] = Math.round((array[i - 1] || 0) + (array[i] * 60000)); // minutes to milliseconds\n\t\t}\n\n\t\tarray[length - 1] = Infinity;\n\t}\n\n\tfunction mapIndices (source, indices) {\n\t\tvar out = [], i;\n\n\t\tfor (i = 0; i < indices.length; i++) {\n\t\t\tout[i] = source[indices[i]];\n\t\t}\n\n\t\treturn out;\n\t}\n\n\tfunction unpack (string) {\n\t\tvar data = string.split('|'),\n\t\t\toffsets = data[2].split(' '),\n\t\t\tindices = data[3].split(''),\n\t\t\tuntils = data[4].split(' ');\n\n\t\tarrayToInt(offsets);\n\t\tarrayToInt(indices);\n\t\tarrayToInt(untils);\n\n\t\tintToUntil(untils, indices.length);\n\n\t\treturn {\n\t\t\tname : data[0],\n\t\t\tabbrs : mapIndices(data[1].split(' '), indices),\n\t\t\toffsets : mapIndices(offsets, indices),\n\t\t\tuntils : untils,\n\t\t\tpopulation : data[5] | 0\n\t\t};\n\t}\n\n\t/************************************\n\t\tZone object\n\t************************************/\n\n\tfunction Zone (packedString) {\n\t\tif (packedString) {\n\t\t\tthis._set(unpack(packedString));\n\t\t}\n\t}\n\n\tfunction closest (num, arr) {\n\t\tvar len = arr.length;\n\t\tif (num < arr[0]) {\n\t\t\treturn 0;\n\t\t} else if (len > 1 && arr[len - 1] === Infinity && num >= arr[len - 2]) {\n\t\t\treturn len - 1;\n\t\t} else if (num >= arr[len - 1]) {\n\t\t\treturn -1;\n\t\t}\n\n\t\tvar mid;\n\t\tvar lo = 0;\n\t\tvar hi = len - 1;\n\t\twhile (hi - lo > 1) {\n\t\t\tmid = Math.floor((lo + hi) / 2);\n\t\t\tif (arr[mid] <= num) {\n\t\t\t\tlo = mid;\n\t\t\t} else {\n\t\t\t\thi = mid;\n\t\t\t}\n\t\t}\n\t\treturn hi;\n\t}\n\n\tZone.prototype = {\n\t\t_set : function (unpacked) {\n\t\t\tthis.name = unpacked.name;\n\t\t\tthis.abbrs = unpacked.abbrs;\n\t\t\tthis.untils = unpacked.untils;\n\t\t\tthis.offsets = unpacked.offsets;\n\t\t\tthis.population = unpacked.population;\n\t\t},\n\n\t\t_index : function (timestamp) {\n\t\t\tvar target = +timestamp,\n\t\t\t\tuntils = this.untils,\n\t\t\t\ti;\n\n\t\t\ti = closest(target, untils);\n\t\t\tif (i >= 0) {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t},\n\n\t\tcountries : function () {\n\t\t\tvar zone_name = this.name;\n\t\t\treturn Object.keys(countries).filter(function (country_code) {\n\t\t\t\treturn countries[country_code].zones.indexOf(zone_name) !== -1;\n\t\t\t});\n\t\t},\n\n\t\tparse : function (timestamp) {\n\t\t\tvar target = +timestamp,\n\t\t\t\toffsets = this.offsets,\n\t\t\t\tuntils = this.untils,\n\t\t\t\tmax = untils.length - 1,\n\t\t\t\toffset, offsetNext, offsetPrev, i;\n\n\t\t\tfor (i = 0; i < max; i++) {\n\t\t\t\toffset = offsets[i];\n\t\t\t\toffsetNext = offsets[i + 1];\n\t\t\t\toffsetPrev = offsets[i ? i - 1 : i];\n\n\t\t\t\tif (offset < offsetNext && tz.moveAmbiguousForward) {\n\t\t\t\t\toffset = offsetNext;\n\t\t\t\t} else if (offset > offsetPrev && tz.moveInvalidForward) {\n\t\t\t\t\toffset = offsetPrev;\n\t\t\t\t}\n\n\t\t\t\tif (target < untils[i] - (offset * 60000)) {\n\t\t\t\t\treturn offsets[i];\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn offsets[max];\n\t\t},\n\n\t\tabbr : function (mom) {\n\t\t\treturn this.abbrs[this._index(mom)];\n\t\t},\n\n\t\toffset : function (mom) {\n\t\t\tlogError(\"zone.offset has been deprecated in favor of zone.utcOffset\");\n\t\t\treturn this.offsets[this._index(mom)];\n\t\t},\n\n\t\tutcOffset : function (mom) {\n\t\t\treturn this.offsets[this._index(mom)];\n\t\t}\n\t};\n\n\t/************************************\n\t\tCountry object\n\t************************************/\n\n\tfunction Country (country_name, zone_names) {\n\t\tthis.name = country_name;\n\t\tthis.zones = zone_names;\n\t}\n\n\t/************************************\n\t\tCurrent Timezone\n\t************************************/\n\n\tfunction OffsetAt(at) {\n\t\tvar timeString = at.toTimeString();\n\t\tvar abbr = timeString.match(/\\([a-z ]+\\)/i);\n\t\tif (abbr && abbr[0]) {\n\t\t\t// 17:56:31 GMT-0600 (CST)\n\t\t\t// 17:56:31 GMT-0600 (Central Standard Time)\n\t\t\tabbr = abbr[0].match(/[A-Z]/g);\n\t\t\tabbr = abbr ? abbr.join('') : undefined;\n\t\t} else {\n\t\t\t// 17:56:31 CST\n\t\t\t// 17:56:31 GMT+0800 (台北標準時間)\n\t\t\tabbr = timeString.match(/[A-Z]{3,5}/g);\n\t\t\tabbr = abbr ? abbr[0] : undefined;\n\t\t}\n\n\t\tif (abbr === 'GMT') {\n\t\t\tabbr = undefined;\n\t\t}\n\n\t\tthis.at = +at;\n\t\tthis.abbr = abbr;\n\t\tthis.offset = at.getTimezoneOffset();\n\t}\n\n\tfunction ZoneScore(zone) {\n\t\tthis.zone = zone;\n\t\tthis.offsetScore = 0;\n\t\tthis.abbrScore = 0;\n\t}\n\n\tZoneScore.prototype.scoreOffsetAt = function (offsetAt) {\n\t\tthis.offsetScore += Math.abs(this.zone.utcOffset(offsetAt.at) - offsetAt.offset);\n\t\tif (this.zone.abbr(offsetAt.at).replace(/[^A-Z]/g, '') !== offsetAt.abbr) {\n\t\t\tthis.abbrScore++;\n\t\t}\n\t};\n\n\tfunction findChange(low, high) {\n\t\tvar mid, diff;\n\n\t\twhile ((diff = ((high.at - low.at) / 12e4 | 0) * 6e4)) {\n\t\t\tmid = new OffsetAt(new Date(low.at + diff));\n\t\t\tif (mid.offset === low.offset) {\n\t\t\t\tlow = mid;\n\t\t\t} else {\n\t\t\t\thigh = mid;\n\t\t\t}\n\t\t}\n\n\t\treturn low;\n\t}\n\n\tfunction userOffsets() {\n\t\tvar startYear = new Date().getFullYear() - 2,\n\t\t\tlast = new OffsetAt(new Date(startYear, 0, 1)),\n\t\t\tlastOffset = last.offset,\n\t\t\toffsets = [last],\n\t\t\tchange, next, nextOffset, i;\n\n\t\tfor (i = 1; i < 48; i++) {\n\t\t\tnextOffset = new Date(startYear, i, 1).getTimezoneOffset();\n\t\t\tif (nextOffset !== lastOffset) {\n\t\t\t\t// Create OffsetAt here to avoid unnecessary abbr parsing before checking offsets\n\t\t\t\tnext = new OffsetAt(new Date(startYear, i, 1));\n\t\t\t\tchange = findChange(last, next);\n\t\t\t\toffsets.push(change);\n\t\t\t\toffsets.push(new OffsetAt(new Date(change.at + 6e4)));\n\t\t\t\tlast = next;\n\t\t\t\tlastOffset = nextOffset;\n\t\t\t}\n\t\t}\n\n\t\tfor (i = 0; i < 4; i++) {\n\t\t\toffsets.push(new OffsetAt(new Date(startYear + i, 0, 1)));\n\t\t\toffsets.push(new OffsetAt(new Date(startYear + i, 6, 1)));\n\t\t}\n\n\t\treturn offsets;\n\t}\n\n\tfunction sortZoneScores (a, b) {\n\t\tif (a.offsetScore !== b.offsetScore) {\n\t\t\treturn a.offsetScore - b.offsetScore;\n\t\t}\n\t\tif (a.abbrScore !== b.abbrScore) {\n\t\t\treturn a.abbrScore - b.abbrScore;\n\t\t}\n\t\tif (a.zone.population !== b.zone.population) {\n\t\t\treturn b.zone.population - a.zone.population;\n\t\t}\n\t\treturn b.zone.name.localeCompare(a.zone.name);\n\t}\n\n\tfunction addToGuesses (name, offsets) {\n\t\tvar i, offset;\n\t\tarrayToInt(offsets);\n\t\tfor (i = 0; i < offsets.length; i++) {\n\t\t\toffset = offsets[i];\n\t\t\tguesses[offset] = guesses[offset] || {};\n\t\t\tguesses[offset][name] = true;\n\t\t}\n\t}\n\n\tfunction guessesForUserOffsets (offsets) {\n\t\tvar offsetsLength = offsets.length,\n\t\t\tfilteredGuesses = {},\n\t\t\tout = [],\n\t\t\tcheckedOffsets = {},\n\t\t\ti, j, offset, guessesOffset;\n\n\t\tfor (i = 0; i < offsetsLength; i++) {\n\t\t\toffset = offsets[i].offset;\n\t\t\tif (checkedOffsets.hasOwnProperty(offset)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tguessesOffset = guesses[offset] || {};\n\t\t\tfor (j in guessesOffset) {\n\t\t\t\tif (guessesOffset.hasOwnProperty(j)) {\n\t\t\t\t\tfilteredGuesses[j] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcheckedOffsets[offset] = true;\n\t\t}\n\n\t\tfor (i in filteredGuesses) {\n\t\t\tif (filteredGuesses.hasOwnProperty(i)) {\n\t\t\t\tout.push(names[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn out;\n\t}\n\n\tfunction rebuildGuess () {\n\n\t\t// use Intl API when available and returning valid time zone\n\t\ttry {\n\t\t\tvar intlName = Intl.DateTimeFormat().resolvedOptions().timeZone;\n\t\t\tif (intlName && intlName.length > 3) {\n\t\t\t\tvar name = names[normalizeName(intlName)];\n\t\t\t\tif (name) {\n\t\t\t\t\treturn name;\n\t\t\t\t}\n\t\t\t\tlogError(\"Moment Timezone found \" + intlName + \" from the Intl api, but did not have that data loaded.\");\n\t\t\t}\n\t\t} catch (e) {\n\t\t\t// Intl unavailable, fall back to manual guessing.\n\t\t}\n\n\t\tvar offsets = userOffsets(),\n\t\t\toffsetsLength = offsets.length,\n\t\t\tguesses = guessesForUserOffsets(offsets),\n\t\t\tzoneScores = [],\n\t\t\tzoneScore, i, j;\n\n\t\tfor (i = 0; i < guesses.length; i++) {\n\t\t\tzoneScore = new ZoneScore(getZone(guesses[i]), offsetsLength);\n\t\t\tfor (j = 0; j < offsetsLength; j++) {\n\t\t\t\tzoneScore.scoreOffsetAt(offsets[j]);\n\t\t\t}\n\t\t\tzoneScores.push(zoneScore);\n\t\t}\n\n\t\tzoneScores.sort(sortZoneScores);\n\n\t\treturn zoneScores.length > 0 ? zoneScores[0].zone.name : undefined;\n\t}\n\n\tfunction guess (ignoreCache) {\n\t\tif (!cachedGuess || ignoreCache) {\n\t\t\tcachedGuess = rebuildGuess();\n\t\t}\n\t\treturn cachedGuess;\n\t}\n\n\t/************************************\n\t\tGlobal Methods\n\t************************************/\n\n\tfunction normalizeName (name) {\n\t\treturn (name || '').toLowerCase().replace(/\\//g, '_');\n\t}\n\n\tfunction addZone (packed) {\n\t\tvar i, name, split, normalized;\n\n\t\tif (typeof packed === \"string\") {\n\t\t\tpacked = [packed];\n\t\t}\n\n\t\tfor (i = 0; i < packed.length; i++) {\n\t\t\tsplit = packed[i].split('|');\n\t\t\tname = split[0];\n\t\t\tnormalized = normalizeName(name);\n\t\t\tzones[normalized] = packed[i];\n\t\t\tnames[normalized] = name;\n\t\t\taddToGuesses(normalized, split[2].split(' '));\n\t\t}\n\t}\n\n\tfunction getZone (name, caller) {\n\n\t\tname = normalizeName(name);\n\n\t\tvar zone = zones[name];\n\t\tvar link;\n\n\t\tif (zone instanceof Zone) {\n\t\t\treturn zone;\n\t\t}\n\n\t\tif (typeof zone === 'string') {\n\t\t\tzone = new Zone(zone);\n\t\t\tzones[name] = zone;\n\t\t\treturn zone;\n\t\t}\n\n\t\t// Pass getZone to prevent recursion more than 1 level deep\n\t\tif (links[name] && caller !== getZone && (link = getZone(links[name], getZone))) {\n\t\t\tzone = zones[name] = new Zone();\n\t\t\tzone._set(link);\n\t\t\tzone.name = names[name];\n\t\t\treturn zone;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\tfunction getNames () {\n\t\tvar i, out = [];\n\n\t\tfor (i in names) {\n\t\t\tif (names.hasOwnProperty(i) && (zones[i] || zones[links[i]]) && names[i]) {\n\t\t\t\tout.push(names[i]);\n\t\t\t}\n\t\t}\n\n\t\treturn out.sort();\n\t}\n\n\tfunction getCountryNames () {\n\t\treturn Object.keys(countries);\n\t}\n\n\tfunction addLink (aliases) {\n\t\tvar i, alias, normal0, normal1;\n\n\t\tif (typeof aliases === \"string\") {\n\t\t\taliases = [aliases];\n\t\t}\n\n\t\tfor (i = 0; i < aliases.length; i++) {\n\t\t\talias = aliases[i].split('|');\n\n\t\t\tnormal0 = normalizeName(alias[0]);\n\t\t\tnormal1 = normalizeName(alias[1]);\n\n\t\t\tlinks[normal0] = normal1;\n\t\t\tnames[normal0] = alias[0];\n\n\t\t\tlinks[normal1] = normal0;\n\t\t\tnames[normal1] = alias[1];\n\t\t}\n\t}\n\n\tfunction addCountries (data) {\n\t\tvar i, country_code, country_zones, split;\n\t\tif (!data || !data.length) return;\n\t\tfor (i = 0; i < data.length; i++) {\n\t\t\tsplit = data[i].split('|');\n\t\t\tcountry_code = split[0].toUpperCase();\n\t\t\tcountry_zones = split[1].split(' ');\n\t\t\tcountries[country_code] = new Country(\n\t\t\t\tcountry_code,\n\t\t\t\tcountry_zones\n\t\t\t);\n\t\t}\n\t}\n\n\tfunction getCountry (name) {\n\t\tname = name.toUpperCase();\n\t\treturn countries[name] || null;\n\t}\n\n\tfunction zonesForCountry(country, with_offset) {\n\t\tcountry = getCountry(country);\n\n\t\tif (!country) return null;\n\n\t\tvar zones = country.zones.sort();\n\n\t\tif (with_offset) {\n\t\t\treturn zones.map(function (zone_name) {\n\t\t\t\tvar zone = getZone(zone_name);\n\t\t\t\treturn {\n\t\t\t\t\tname: zone_name,\n\t\t\t\t\toffset: zone.utcOffset(new Date())\n\t\t\t\t};\n\t\t\t});\n\t\t}\n\n\t\treturn zones;\n\t}\n\n\tfunction loadData (data) {\n\t\taddZone(data.zones);\n\t\taddLink(data.links);\n\t\taddCountries(data.countries);\n\t\ttz.dataVersion = data.version;\n\t}\n\n\tfunction zoneExists (name) {\n\t\tif (!zoneExists.didShowError) {\n\t\t\tzoneExists.didShowError = true;\n\t\t\t\tlogError(\"moment.tz.zoneExists('\" + name + \"') has been deprecated in favor of !moment.tz.zone('\" + name + \"')\");\n\t\t}\n\t\treturn !!getZone(name);\n\t}\n\n\tfunction needsOffset (m) {\n\t\tvar isUnixTimestamp = (m._f === 'X' || m._f === 'x');\n\t\treturn !!(m._a && (m._tzm === undefined) && !isUnixTimestamp);\n\t}\n\n\tfunction logError (message) {\n\t\tif (typeof console !== 'undefined' && typeof console.error === 'function') {\n\t\t\tconsole.error(message);\n\t\t}\n\t}\n\n\t/************************************\n\t\tmoment.tz namespace\n\t************************************/\n\n\tfunction tz (input) {\n\t\tvar args = Array.prototype.slice.call(arguments, 0, -1),\n\t\t\tname = arguments[arguments.length - 1],\n\t\t\tout = moment.utc.apply(null, args),\n\t\t\tzone;\n\n\t\tif (!moment.isMoment(input) && needsOffset(out) && (zone = getZone(name))) {\n\t\t\tout.add(zone.parse(out), 'minutes');\n\t\t}\n\n\t\tout.tz(name);\n\n\t\treturn out;\n\t}\n\n\ttz.version = VERSION;\n\ttz.dataVersion = '';\n\ttz._zones = zones;\n\ttz._links = links;\n\ttz._names = names;\n\ttz._countries\t= countries;\n\ttz.add = addZone;\n\ttz.link = addLink;\n\ttz.load = loadData;\n\ttz.zone = getZone;\n\ttz.zoneExists = zoneExists; // deprecated in 0.1.0\n\ttz.guess = guess;\n\ttz.names = getNames;\n\ttz.Zone = Zone;\n\ttz.unpack = unpack;\n\ttz.unpackBase60 = unpackBase60;\n\ttz.needsOffset = needsOffset;\n\ttz.moveInvalidForward = true;\n\ttz.moveAmbiguousForward = false;\n\ttz.countries = getCountryNames;\n\ttz.zonesForCountry = zonesForCountry;\n\n\t/************************************\n\t\tInterface with Moment.js\n\t************************************/\n\n\tvar fn = moment.fn;\n\n\tmoment.tz = tz;\n\n\tmoment.defaultZone = null;\n\n\tmoment.updateOffset = function (mom, keepTime) {\n\t\tvar zone = moment.defaultZone,\n\t\t\toffset;\n\n\t\tif (mom._z === undefined) {\n\t\t\tif (zone && needsOffset(mom) && !mom._isUTC && mom.isValid()) {\n\t\t\t\tmom._d = moment.utc(mom._a)._d;\n\t\t\t\tmom.utc().add(zone.parse(mom), 'minutes');\n\t\t\t}\n\t\t\tmom._z = zone;\n\t\t}\n\t\tif (mom._z) {\n\t\t\toffset = mom._z.utcOffset(mom);\n\t\t\tif (Math.abs(offset) < 16) {\n\t\t\t\toffset = offset / 60;\n\t\t\t}\n\t\t\tif (mom.utcOffset !== undefined) {\n\t\t\t\tvar z = mom._z;\n\t\t\t\tmom.utcOffset(-offset, keepTime);\n\t\t\t\tmom._z = z;\n\t\t\t} else {\n\t\t\t\tmom.zone(offset, keepTime);\n\t\t\t}\n\t\t}\n\t};\n\n\tfn.tz = function (name, keepTime) {\n\t\tif (name) {\n\t\t\tif (typeof name !== 'string') {\n\t\t\t\tthrow new Error('Time zone name must be a string, got ' + name + ' [' + typeof name + ']');\n\t\t\t}\n\t\t\tthis._z = getZone(name);\n\t\t\tif (this._z) {\n\t\t\t\tmoment.updateOffset(this, keepTime);\n\t\t\t} else {\n\t\t\t\tlogError(\"Moment Timezone has no data for \" + name + \". See http://momentjs.com/timezone/docs/#/data-loading/.\");\n\t\t\t}\n\t\t\treturn this;\n\t\t}\n\t\tif (this._z) { return this._z.name; }\n\t};\n\n\tfunction abbrWrap (old) {\n\t\treturn function () {\n\t\t\tif (this._z) { return this._z.abbr(this); }\n\t\t\treturn old.call(this);\n\t\t};\n\t}\n\n\tfunction resetZoneWrap (old) {\n\t\treturn function () {\n\t\t\tthis._z = null;\n\t\t\treturn old.apply(this, arguments);\n\t\t};\n\t}\n\n\tfunction resetZoneWrap2 (old) {\n\t\treturn function () {\n\t\t\tif (arguments.length > 0) this._z = null;\n\t\t\treturn old.apply(this, arguments);\n\t\t};\n\t}\n\n\tfn.zoneName = abbrWrap(fn.zoneName);\n\tfn.zoneAbbr = abbrWrap(fn.zoneAbbr);\n\tfn.utc = resetZoneWrap(fn.utc);\n\tfn.local = resetZoneWrap(fn.local);\n\tfn.utcOffset = resetZoneWrap2(fn.utcOffset);\n\n\tmoment.tz.setDefault = function(name) {\n\t\tif (major < 2 || (major === 2 && minor < 9)) {\n\t\t\tlogError('Moment Timezone setDefault() requires Moment.js >= 2.9.0. You are using Moment.js ' + moment.version + '.');\n\t\t}\n\t\tmoment.defaultZone = name ? getZone(name) : null;\n\t\treturn moment;\n\t};\n\n\t// Cloning a moment should include the _z property.\n\tvar momentProperties = moment.momentProperties;\n\tif (Object.prototype.toString.call(momentProperties) === '[object Array]') {\n\t\t// moment 2.8.1+\n\t\tmomentProperties.push('_z');\n\t\tmomentProperties.push('_a');\n\t} else if (momentProperties) {\n\t\t// moment 2.7.0\n\t\tmomentProperties._z = null;\n\t}\n\n\t// INJECT DATA\n\n\treturn moment;\n}));\n","//! moment.js locale configuration\n//! locale : Afrikaans [af]\n//! author : Werner Mollentze : https://github.com/wernerm\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var af = moment.defineLocale('af', {\n months: 'Januarie_Februarie_Maart_April_Mei_Junie_Julie_Augustus_September_Oktober_November_Desember'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mrt_Apr_Mei_Jun_Jul_Aug_Sep_Okt_Nov_Des'.split('_'),\n weekdays: 'Sondag_Maandag_Dinsdag_Woensdag_Donderdag_Vrydag_Saterdag'.split(\n '_'\n ),\n weekdaysShort: 'Son_Maa_Din_Woe_Don_Vry_Sat'.split('_'),\n weekdaysMin: 'So_Ma_Di_Wo_Do_Vr_Sa'.split('_'),\n meridiemParse: /vm|nm/i,\n isPM: function (input) {\n return /^nm$/i.test(input);\n },\n meridiem: function (hours, minutes, isLower) {\n if (hours < 12) {\n return isLower ? 'vm' : 'VM';\n } else {\n return isLower ? 'nm' : 'NM';\n }\n },\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Vandag om] LT',\n nextDay: '[Môre om] LT',\n nextWeek: 'dddd [om] LT',\n lastDay: '[Gister om] LT',\n lastWeek: '[Laas] dddd [om] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'oor %s',\n past: '%s gelede',\n s: \"'n paar sekondes\",\n ss: '%d sekondes',\n m: \"'n minuut\",\n mm: '%d minute',\n h: \"'n uur\",\n hh: '%d ure',\n d: \"'n dag\",\n dd: '%d dae',\n M: \"'n maand\",\n MM: '%d maande',\n y: \"'n jaar\",\n yy: '%d jaar',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(ste|de)/,\n ordinal: function (number) {\n return (\n number +\n (number === 1 || number === 8 || number >= 20 ? 'ste' : 'de')\n ); // Thanks to Joris Röling : https://github.com/jjupiter\n },\n week: {\n dow: 1, // Maandag is die eerste dag van die week.\n doy: 4, // Die week wat die 4de Januarie bevat is die eerste week van die jaar.\n },\n });\n\n return af;\n\n})));\n","//! moment.js locale configuration\n//! locale : Arabic (Algeria) [ar-dz]\n//! author : Amine Roukh: https://github.com/Amine27\n//! author : Abdel Said: https://github.com/abdelsaid\n//! author : Ahmed Elkhatib\n//! author : forabi https://github.com/forabi\n//! author : Noureddine LOUAHEDJ : https://github.com/noureddinem\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var pluralForm = function (n) {\n return n === 0\n ? 0\n : n === 1\n ? 1\n : n === 2\n ? 2\n : n % 100 >= 3 && n % 100 <= 10\n ? 3\n : n % 100 >= 11\n ? 4\n : 5;\n },\n plurals = {\n s: [\n 'أقل من ثانية',\n 'ثانية واحدة',\n ['ثانيتان', 'ثانيتين'],\n '%d ثوان',\n '%d ثانية',\n '%d ثانية',\n ],\n m: [\n 'أقل من دقيقة',\n 'دقيقة واحدة',\n ['دقيقتان', 'دقيقتين'],\n '%d دقائق',\n '%d دقيقة',\n '%d دقيقة',\n ],\n h: [\n 'أقل من ساعة',\n 'ساعة واحدة',\n ['ساعتان', 'ساعتين'],\n '%d ساعات',\n '%d ساعة',\n '%d ساعة',\n ],\n d: [\n 'أقل من يوم',\n 'يوم واحد',\n ['يومان', 'يومين'],\n '%d أيام',\n '%d يومًا',\n '%d يوم',\n ],\n M: [\n 'أقل من شهر',\n 'شهر واحد',\n ['شهران', 'شهرين'],\n '%d أشهر',\n '%d شهرا',\n '%d شهر',\n ],\n y: [\n 'أقل من عام',\n 'عام واحد',\n ['عامان', 'عامين'],\n '%d أعوام',\n '%d عامًا',\n '%d عام',\n ],\n },\n pluralize = function (u) {\n return function (number, withoutSuffix, string, isFuture) {\n var f = pluralForm(number),\n str = plurals[u][pluralForm(number)];\n if (f === 2) {\n str = str[withoutSuffix ? 0 : 1];\n }\n return str.replace(/%d/i, number);\n };\n },\n months = [\n 'جانفي',\n 'فيفري',\n 'مارس',\n 'أفريل',\n 'ماي',\n 'جوان',\n 'جويلية',\n 'أوت',\n 'سبتمبر',\n 'أكتوبر',\n 'نوفمبر',\n 'ديسمبر',\n ];\n\n var arDz = moment.defineLocale('ar-dz', {\n months: months,\n monthsShort: months,\n weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),\n weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),\n weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'D/\\u200FM/\\u200FYYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n meridiemParse: /ص|م/,\n isPM: function (input) {\n return 'م' === input;\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return 'ص';\n } else {\n return 'م';\n }\n },\n calendar: {\n sameDay: '[اليوم عند الساعة] LT',\n nextDay: '[غدًا عند الساعة] LT',\n nextWeek: 'dddd [عند الساعة] LT',\n lastDay: '[أمس عند الساعة] LT',\n lastWeek: 'dddd [عند الساعة] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'بعد %s',\n past: 'منذ %s',\n s: pluralize('s'),\n ss: pluralize('s'),\n m: pluralize('m'),\n mm: pluralize('m'),\n h: pluralize('h'),\n hh: pluralize('h'),\n d: pluralize('d'),\n dd: pluralize('d'),\n M: pluralize('M'),\n MM: pluralize('M'),\n y: pluralize('y'),\n yy: pluralize('y'),\n },\n postformat: function (string) {\n return string.replace(/,/g, '،');\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return arDz;\n\n})));\n","//! moment.js locale configuration\n//! locale : Arabic (Kuwait) [ar-kw]\n//! author : Nusret Parlak: https://github.com/nusretparlak\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var arKw = moment.defineLocale('ar-kw', {\n months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split(\n '_'\n ),\n monthsShort:\n 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split(\n '_'\n ),\n weekdays: 'الأحد_الإتنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),\n weekdaysShort: 'احد_اتنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),\n weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[اليوم على الساعة] LT',\n nextDay: '[غدا على الساعة] LT',\n nextWeek: 'dddd [على الساعة] LT',\n lastDay: '[أمس على الساعة] LT',\n lastWeek: 'dddd [على الساعة] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'في %s',\n past: 'منذ %s',\n s: 'ثوان',\n ss: '%d ثانية',\n m: 'دقيقة',\n mm: '%d دقائق',\n h: 'ساعة',\n hh: '%d ساعات',\n d: 'يوم',\n dd: '%d أيام',\n M: 'شهر',\n MM: '%d أشهر',\n y: 'سنة',\n yy: '%d سنوات',\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 12, // The week that contains Jan 12th is the first week of the year.\n },\n });\n\n return arKw;\n\n})));\n","//! moment.js locale configuration\n//! locale : Arabic (Libya) [ar-ly]\n//! author : Ali Hmer: https://github.com/kikoanis\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '1',\n 2: '2',\n 3: '3',\n 4: '4',\n 5: '5',\n 6: '6',\n 7: '7',\n 8: '8',\n 9: '9',\n 0: '0',\n },\n pluralForm = function (n) {\n return n === 0\n ? 0\n : n === 1\n ? 1\n : n === 2\n ? 2\n : n % 100 >= 3 && n % 100 <= 10\n ? 3\n : n % 100 >= 11\n ? 4\n : 5;\n },\n plurals = {\n s: [\n 'أقل من ثانية',\n 'ثانية واحدة',\n ['ثانيتان', 'ثانيتين'],\n '%d ثوان',\n '%d ثانية',\n '%d ثانية',\n ],\n m: [\n 'أقل من دقيقة',\n 'دقيقة واحدة',\n ['دقيقتان', 'دقيقتين'],\n '%d دقائق',\n '%d دقيقة',\n '%d دقيقة',\n ],\n h: [\n 'أقل من ساعة',\n 'ساعة واحدة',\n ['ساعتان', 'ساعتين'],\n '%d ساعات',\n '%d ساعة',\n '%d ساعة',\n ],\n d: [\n 'أقل من يوم',\n 'يوم واحد',\n ['يومان', 'يومين'],\n '%d أيام',\n '%d يومًا',\n '%d يوم',\n ],\n M: [\n 'أقل من شهر',\n 'شهر واحد',\n ['شهران', 'شهرين'],\n '%d أشهر',\n '%d شهرا',\n '%d شهر',\n ],\n y: [\n 'أقل من عام',\n 'عام واحد',\n ['عامان', 'عامين'],\n '%d أعوام',\n '%d عامًا',\n '%d عام',\n ],\n },\n pluralize = function (u) {\n return function (number, withoutSuffix, string, isFuture) {\n var f = pluralForm(number),\n str = plurals[u][pluralForm(number)];\n if (f === 2) {\n str = str[withoutSuffix ? 0 : 1];\n }\n return str.replace(/%d/i, number);\n };\n },\n months = [\n 'يناير',\n 'فبراير',\n 'مارس',\n 'أبريل',\n 'مايو',\n 'يونيو',\n 'يوليو',\n 'أغسطس',\n 'سبتمبر',\n 'أكتوبر',\n 'نوفمبر',\n 'ديسمبر',\n ];\n\n var arLy = moment.defineLocale('ar-ly', {\n months: months,\n monthsShort: months,\n weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),\n weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),\n weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'D/\\u200FM/\\u200FYYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n meridiemParse: /ص|م/,\n isPM: function (input) {\n return 'م' === input;\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return 'ص';\n } else {\n return 'م';\n }\n },\n calendar: {\n sameDay: '[اليوم عند الساعة] LT',\n nextDay: '[غدًا عند الساعة] LT',\n nextWeek: 'dddd [عند الساعة] LT',\n lastDay: '[أمس عند الساعة] LT',\n lastWeek: 'dddd [عند الساعة] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'بعد %s',\n past: 'منذ %s',\n s: pluralize('s'),\n ss: pluralize('s'),\n m: pluralize('m'),\n mm: pluralize('m'),\n h: pluralize('h'),\n hh: pluralize('h'),\n d: pluralize('d'),\n dd: pluralize('d'),\n M: pluralize('M'),\n MM: pluralize('M'),\n y: pluralize('y'),\n yy: pluralize('y'),\n },\n preparse: function (string) {\n return string.replace(/،/g, ',');\n },\n postformat: function (string) {\n return string\n .replace(/\\d/g, function (match) {\n return symbolMap[match];\n })\n .replace(/,/g, '،');\n },\n week: {\n dow: 6, // Saturday is the first day of the week.\n doy: 12, // The week that contains Jan 12th is the first week of the year.\n },\n });\n\n return arLy;\n\n})));\n","//! moment.js locale configuration\n//! locale : Arabic (Morocco) [ar-ma]\n//! author : ElFadili Yassine : https://github.com/ElFadiliY\n//! author : Abdel Said : https://github.com/abdelsaid\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var arMa = moment.defineLocale('ar-ma', {\n months: 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split(\n '_'\n ),\n monthsShort:\n 'يناير_فبراير_مارس_أبريل_ماي_يونيو_يوليوز_غشت_شتنبر_أكتوبر_نونبر_دجنبر'.split(\n '_'\n ),\n weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),\n weekdaysShort: 'احد_اثنين_ثلاثاء_اربعاء_خميس_جمعة_سبت'.split('_'),\n weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[اليوم على الساعة] LT',\n nextDay: '[غدا على الساعة] LT',\n nextWeek: 'dddd [على الساعة] LT',\n lastDay: '[أمس على الساعة] LT',\n lastWeek: 'dddd [على الساعة] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'في %s',\n past: 'منذ %s',\n s: 'ثوان',\n ss: '%d ثانية',\n m: 'دقيقة',\n mm: '%d دقائق',\n h: 'ساعة',\n hh: '%d ساعات',\n d: 'يوم',\n dd: '%d أيام',\n M: 'شهر',\n MM: '%d أشهر',\n y: 'سنة',\n yy: '%d سنوات',\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return arMa;\n\n})));\n","//! moment.js locale configuration\n//! locale : Arabic (Palestine) [ar-ps]\n//! author : Majd Al-Shihabi : https://github.com/majdal\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '١',\n 2: '٢',\n 3: '٣',\n 4: '٤',\n 5: '٥',\n 6: '٦',\n 7: '٧',\n 8: '٨',\n 9: '٩',\n 0: '٠',\n },\n numberMap = {\n '١': '1',\n '٢': '2',\n '٣': '3',\n '٤': '4',\n '٥': '5',\n '٦': '6',\n '٧': '7',\n '٨': '8',\n '٩': '9',\n '٠': '0',\n };\n\n var arPs = moment.defineLocale('ar-ps', {\n months: 'كانون الثاني_شباط_آذار_نيسان_أيّار_حزيران_تمّوز_آب_أيلول_تشري الأوّل_تشرين الثاني_كانون الأوّل'.split(\n '_'\n ),\n monthsShort:\n 'ك٢_شباط_آذار_نيسان_أيّار_حزيران_تمّوز_آب_أيلول_ت١_ت٢_ك١'.split('_'),\n weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),\n weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),\n weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n meridiemParse: /ص|م/,\n isPM: function (input) {\n return 'م' === input;\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return 'ص';\n } else {\n return 'م';\n }\n },\n calendar: {\n sameDay: '[اليوم على الساعة] LT',\n nextDay: '[غدا على الساعة] LT',\n nextWeek: 'dddd [على الساعة] LT',\n lastDay: '[أمس على الساعة] LT',\n lastWeek: 'dddd [على الساعة] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'في %s',\n past: 'منذ %s',\n s: 'ثوان',\n ss: '%d ثانية',\n m: 'دقيقة',\n mm: '%d دقائق',\n h: 'ساعة',\n hh: '%d ساعات',\n d: 'يوم',\n dd: '%d أيام',\n M: 'شهر',\n MM: '%d أشهر',\n y: 'سنة',\n yy: '%d سنوات',\n },\n preparse: function (string) {\n return string\n .replace(/[٣٤٥٦٧٨٩٠]/g, function (match) {\n return numberMap[match];\n })\n .split('') // reversed since negative lookbehind not supported everywhere\n .reverse()\n .join('')\n .replace(/[١٢](?![\\u062a\\u0643])/g, function (match) {\n return numberMap[match];\n })\n .split('')\n .reverse()\n .join('')\n .replace(/،/g, ',');\n },\n postformat: function (string) {\n return string\n .replace(/\\d/g, function (match) {\n return symbolMap[match];\n })\n .replace(/,/g, '،');\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return arPs;\n\n})));\n","//! moment.js locale configuration\n//! locale : Arabic (Saudi Arabia) [ar-sa]\n//! author : Suhail Alkowaileet : https://github.com/xsoh\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '١',\n 2: '٢',\n 3: '٣',\n 4: '٤',\n 5: '٥',\n 6: '٦',\n 7: '٧',\n 8: '٨',\n 9: '٩',\n 0: '٠',\n },\n numberMap = {\n '١': '1',\n '٢': '2',\n '٣': '3',\n '٤': '4',\n '٥': '5',\n '٦': '6',\n '٧': '7',\n '٨': '8',\n '٩': '9',\n '٠': '0',\n };\n\n var arSa = moment.defineLocale('ar-sa', {\n months: 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split(\n '_'\n ),\n monthsShort:\n 'يناير_فبراير_مارس_أبريل_مايو_يونيو_يوليو_أغسطس_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split(\n '_'\n ),\n weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),\n weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),\n weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n meridiemParse: /ص|م/,\n isPM: function (input) {\n return 'م' === input;\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return 'ص';\n } else {\n return 'م';\n }\n },\n calendar: {\n sameDay: '[اليوم على الساعة] LT',\n nextDay: '[غدا على الساعة] LT',\n nextWeek: 'dddd [على الساعة] LT',\n lastDay: '[أمس على الساعة] LT',\n lastWeek: 'dddd [على الساعة] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'في %s',\n past: 'منذ %s',\n s: 'ثوان',\n ss: '%d ثانية',\n m: 'دقيقة',\n mm: '%d دقائق',\n h: 'ساعة',\n hh: '%d ساعات',\n d: 'يوم',\n dd: '%d أيام',\n M: 'شهر',\n MM: '%d أشهر',\n y: 'سنة',\n yy: '%d سنوات',\n },\n preparse: function (string) {\n return string\n .replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {\n return numberMap[match];\n })\n .replace(/،/g, ',');\n },\n postformat: function (string) {\n return string\n .replace(/\\d/g, function (match) {\n return symbolMap[match];\n })\n .replace(/,/g, '،');\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return arSa;\n\n})));\n","//! moment.js locale configuration\n//! locale : Arabic (Tunisia) [ar-tn]\n//! author : Nader Toukabri : https://github.com/naderio\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var arTn = moment.defineLocale('ar-tn', {\n months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split(\n '_'\n ),\n monthsShort:\n 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split(\n '_'\n ),\n weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),\n weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),\n weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[اليوم على الساعة] LT',\n nextDay: '[غدا على الساعة] LT',\n nextWeek: 'dddd [على الساعة] LT',\n lastDay: '[أمس على الساعة] LT',\n lastWeek: 'dddd [على الساعة] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'في %s',\n past: 'منذ %s',\n s: 'ثوان',\n ss: '%d ثانية',\n m: 'دقيقة',\n mm: '%d دقائق',\n h: 'ساعة',\n hh: '%d ساعات',\n d: 'يوم',\n dd: '%d أيام',\n M: 'شهر',\n MM: '%d أشهر',\n y: 'سنة',\n yy: '%d سنوات',\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return arTn;\n\n})));\n","//! moment.js locale configuration\n//! locale : Arabic [ar]\n//! author : Abdel Said: https://github.com/abdelsaid\n//! author : Ahmed Elkhatib\n//! author : forabi https://github.com/forabi\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '١',\n 2: '٢',\n 3: '٣',\n 4: '٤',\n 5: '٥',\n 6: '٦',\n 7: '٧',\n 8: '٨',\n 9: '٩',\n 0: '٠',\n },\n numberMap = {\n '١': '1',\n '٢': '2',\n '٣': '3',\n '٤': '4',\n '٥': '5',\n '٦': '6',\n '٧': '7',\n '٨': '8',\n '٩': '9',\n '٠': '0',\n },\n pluralForm = function (n) {\n return n === 0\n ? 0\n : n === 1\n ? 1\n : n === 2\n ? 2\n : n % 100 >= 3 && n % 100 <= 10\n ? 3\n : n % 100 >= 11\n ? 4\n : 5;\n },\n plurals = {\n s: [\n 'أقل من ثانية',\n 'ثانية واحدة',\n ['ثانيتان', 'ثانيتين'],\n '%d ثوان',\n '%d ثانية',\n '%d ثانية',\n ],\n m: [\n 'أقل من دقيقة',\n 'دقيقة واحدة',\n ['دقيقتان', 'دقيقتين'],\n '%d دقائق',\n '%d دقيقة',\n '%d دقيقة',\n ],\n h: [\n 'أقل من ساعة',\n 'ساعة واحدة',\n ['ساعتان', 'ساعتين'],\n '%d ساعات',\n '%d ساعة',\n '%d ساعة',\n ],\n d: [\n 'أقل من يوم',\n 'يوم واحد',\n ['يومان', 'يومين'],\n '%d أيام',\n '%d يومًا',\n '%d يوم',\n ],\n M: [\n 'أقل من شهر',\n 'شهر واحد',\n ['شهران', 'شهرين'],\n '%d أشهر',\n '%d شهرا',\n '%d شهر',\n ],\n y: [\n 'أقل من عام',\n 'عام واحد',\n ['عامان', 'عامين'],\n '%d أعوام',\n '%d عامًا',\n '%d عام',\n ],\n },\n pluralize = function (u) {\n return function (number, withoutSuffix, string, isFuture) {\n var f = pluralForm(number),\n str = plurals[u][pluralForm(number)];\n if (f === 2) {\n str = str[withoutSuffix ? 0 : 1];\n }\n return str.replace(/%d/i, number);\n };\n },\n months = [\n 'يناير',\n 'فبراير',\n 'مارس',\n 'أبريل',\n 'مايو',\n 'يونيو',\n 'يوليو',\n 'أغسطس',\n 'سبتمبر',\n 'أكتوبر',\n 'نوفمبر',\n 'ديسمبر',\n ];\n\n var ar = moment.defineLocale('ar', {\n months: months,\n monthsShort: months,\n weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),\n weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),\n weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'D/\\u200FM/\\u200FYYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n meridiemParse: /ص|م/,\n isPM: function (input) {\n return 'م' === input;\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return 'ص';\n } else {\n return 'م';\n }\n },\n calendar: {\n sameDay: '[اليوم عند الساعة] LT',\n nextDay: '[غدًا عند الساعة] LT',\n nextWeek: 'dddd [عند الساعة] LT',\n lastDay: '[أمس عند الساعة] LT',\n lastWeek: 'dddd [عند الساعة] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'بعد %s',\n past: 'منذ %s',\n s: pluralize('s'),\n ss: pluralize('s'),\n m: pluralize('m'),\n mm: pluralize('m'),\n h: pluralize('h'),\n hh: pluralize('h'),\n d: pluralize('d'),\n dd: pluralize('d'),\n M: pluralize('M'),\n MM: pluralize('M'),\n y: pluralize('y'),\n yy: pluralize('y'),\n },\n preparse: function (string) {\n return string\n .replace(/[١٢٣٤٥٦٧٨٩٠]/g, function (match) {\n return numberMap[match];\n })\n .replace(/،/g, ',');\n },\n postformat: function (string) {\n return string\n .replace(/\\d/g, function (match) {\n return symbolMap[match];\n })\n .replace(/,/g, '،');\n },\n week: {\n dow: 6, // Saturday is the first day of the week.\n doy: 12, // The week that contains Jan 12th is the first week of the year.\n },\n });\n\n return ar;\n\n})));\n","//! moment.js locale configuration\n//! locale : Azerbaijani [az]\n//! author : topchiyev : https://github.com/topchiyev\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var suffixes = {\n 1: '-inci',\n 5: '-inci',\n 8: '-inci',\n 70: '-inci',\n 80: '-inci',\n 2: '-nci',\n 7: '-nci',\n 20: '-nci',\n 50: '-nci',\n 3: '-üncü',\n 4: '-üncü',\n 100: '-üncü',\n 6: '-ncı',\n 9: '-uncu',\n 10: '-uncu',\n 30: '-uncu',\n 60: '-ıncı',\n 90: '-ıncı',\n };\n\n var az = moment.defineLocale('az', {\n months: 'yanvar_fevral_mart_aprel_may_iyun_iyul_avqust_sentyabr_oktyabr_noyabr_dekabr'.split(\n '_'\n ),\n monthsShort: 'yan_fev_mar_apr_may_iyn_iyl_avq_sen_okt_noy_dek'.split('_'),\n weekdays:\n 'Bazar_Bazar ertəsi_Çərşənbə axşamı_Çərşənbə_Cümə axşamı_Cümə_Şənbə'.split(\n '_'\n ),\n weekdaysShort: 'Baz_BzE_ÇAx_Çər_CAx_Cüm_Şən'.split('_'),\n weekdaysMin: 'Bz_BE_ÇA_Çə_CA_Cü_Şə'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[bugün saat] LT',\n nextDay: '[sabah saat] LT',\n nextWeek: '[gələn həftə] dddd [saat] LT',\n lastDay: '[dünən] LT',\n lastWeek: '[keçən həftə] dddd [saat] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s sonra',\n past: '%s əvvəl',\n s: 'bir neçə saniyə',\n ss: '%d saniyə',\n m: 'bir dəqiqə',\n mm: '%d dəqiqə',\n h: 'bir saat',\n hh: '%d saat',\n d: 'bir gün',\n dd: '%d gün',\n M: 'bir ay',\n MM: '%d ay',\n y: 'bir il',\n yy: '%d il',\n },\n meridiemParse: /gecə|səhər|gündüz|axşam/,\n isPM: function (input) {\n return /^(gündüz|axşam)$/.test(input);\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'gecə';\n } else if (hour < 12) {\n return 'səhər';\n } else if (hour < 17) {\n return 'gündüz';\n } else {\n return 'axşam';\n }\n },\n dayOfMonthOrdinalParse: /\\d{1,2}-(ıncı|inci|nci|üncü|ncı|uncu)/,\n ordinal: function (number) {\n if (number === 0) {\n // special case for zero\n return number + '-ıncı';\n }\n var a = number % 10,\n b = (number % 100) - a,\n c = number >= 100 ? 100 : null;\n return number + (suffixes[a] || suffixes[b] || suffixes[c]);\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return az;\n\n})));\n","//! moment.js locale configuration\n//! locale : Belarusian [be]\n//! author : Dmitry Demidov : https://github.com/demidov91\n//! author: Praleska: http://praleska.pro/\n//! Author : Menelion Elensúle : https://github.com/Oire\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function plural(word, num) {\n var forms = word.split('_');\n return num % 10 === 1 && num % 100 !== 11\n ? forms[0]\n : num % 10 >= 2 && num % 10 <= 4 && (num % 100 < 10 || num % 100 >= 20)\n ? forms[1]\n : forms[2];\n }\n function relativeTimeWithPlural(number, withoutSuffix, key) {\n var format = {\n ss: withoutSuffix ? 'секунда_секунды_секунд' : 'секунду_секунды_секунд',\n mm: withoutSuffix ? 'хвіліна_хвіліны_хвілін' : 'хвіліну_хвіліны_хвілін',\n hh: withoutSuffix ? 'гадзіна_гадзіны_гадзін' : 'гадзіну_гадзіны_гадзін',\n dd: 'дзень_дні_дзён',\n MM: 'месяц_месяцы_месяцаў',\n yy: 'год_гады_гадоў',\n };\n if (key === 'm') {\n return withoutSuffix ? 'хвіліна' : 'хвіліну';\n } else if (key === 'h') {\n return withoutSuffix ? 'гадзіна' : 'гадзіну';\n } else {\n return number + ' ' + plural(format[key], +number);\n }\n }\n\n var be = moment.defineLocale('be', {\n months: {\n format: 'студзеня_лютага_сакавіка_красавіка_траўня_чэрвеня_ліпеня_жніўня_верасня_кастрычніка_лістапада_снежня'.split(\n '_'\n ),\n standalone:\n 'студзень_люты_сакавік_красавік_травень_чэрвень_ліпень_жнівень_верасень_кастрычнік_лістапад_снежань'.split(\n '_'\n ),\n },\n monthsShort:\n 'студ_лют_сак_крас_трав_чэрв_ліп_жнів_вер_каст_ліст_снеж'.split('_'),\n weekdays: {\n format: 'нядзелю_панядзелак_аўторак_сераду_чацвер_пятніцу_суботу'.split(\n '_'\n ),\n standalone:\n 'нядзеля_панядзелак_аўторак_серада_чацвер_пятніца_субота'.split(\n '_'\n ),\n isFormat: /\\[ ?[Ууў] ?(?:мінулую|наступную)? ?\\] ?dddd/,\n },\n weekdaysShort: 'нд_пн_ат_ср_чц_пт_сб'.split('_'),\n weekdaysMin: 'нд_пн_ат_ср_чц_пт_сб'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D MMMM YYYY г.',\n LLL: 'D MMMM YYYY г., HH:mm',\n LLLL: 'dddd, D MMMM YYYY г., HH:mm',\n },\n calendar: {\n sameDay: '[Сёння ў] LT',\n nextDay: '[Заўтра ў] LT',\n lastDay: '[Учора ў] LT',\n nextWeek: function () {\n return '[У] dddd [ў] LT';\n },\n lastWeek: function () {\n switch (this.day()) {\n case 0:\n case 3:\n case 5:\n case 6:\n return '[У мінулую] dddd [ў] LT';\n case 1:\n case 2:\n case 4:\n return '[У мінулы] dddd [ў] LT';\n }\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'праз %s',\n past: '%s таму',\n s: 'некалькі секунд',\n m: relativeTimeWithPlural,\n mm: relativeTimeWithPlural,\n h: relativeTimeWithPlural,\n hh: relativeTimeWithPlural,\n d: 'дзень',\n dd: relativeTimeWithPlural,\n M: 'месяц',\n MM: relativeTimeWithPlural,\n y: 'год',\n yy: relativeTimeWithPlural,\n },\n meridiemParse: /ночы|раніцы|дня|вечара/,\n isPM: function (input) {\n return /^(дня|вечара)$/.test(input);\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'ночы';\n } else if (hour < 12) {\n return 'раніцы';\n } else if (hour < 17) {\n return 'дня';\n } else {\n return 'вечара';\n }\n },\n dayOfMonthOrdinalParse: /\\d{1,2}-(і|ы|га)/,\n ordinal: function (number, period) {\n switch (period) {\n case 'M':\n case 'd':\n case 'DDD':\n case 'w':\n case 'W':\n return (number % 10 === 2 || number % 10 === 3) &&\n number % 100 !== 12 &&\n number % 100 !== 13\n ? number + '-і'\n : number + '-ы';\n case 'D':\n return number + '-га';\n default:\n return number;\n }\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return be;\n\n})));\n","//! moment.js locale configuration\n//! locale : Bulgarian [bg]\n//! author : Krasen Borisov : https://github.com/kraz\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var bg = moment.defineLocale('bg', {\n months: 'януари_февруари_март_април_май_юни_юли_август_септември_октомври_ноември_декември'.split(\n '_'\n ),\n monthsShort: 'яну_фев_мар_апр_май_юни_юли_авг_сеп_окт_ное_дек'.split('_'),\n weekdays: 'неделя_понеделник_вторник_сряда_четвъртък_петък_събота'.split(\n '_'\n ),\n weekdaysShort: 'нед_пон_вто_сря_чет_пет_съб'.split('_'),\n weekdaysMin: 'нд_пн_вт_ср_чт_пт_сб'.split('_'),\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'D.MM.YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY H:mm',\n LLLL: 'dddd, D MMMM YYYY H:mm',\n },\n calendar: {\n sameDay: '[Днес в] LT',\n nextDay: '[Утре в] LT',\n nextWeek: 'dddd [в] LT',\n lastDay: '[Вчера в] LT',\n lastWeek: function () {\n switch (this.day()) {\n case 0:\n case 3:\n case 6:\n return '[Миналата] dddd [в] LT';\n case 1:\n case 2:\n case 4:\n case 5:\n return '[Миналия] dddd [в] LT';\n }\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'след %s',\n past: 'преди %s',\n s: 'няколко секунди',\n ss: '%d секунди',\n m: 'минута',\n mm: '%d минути',\n h: 'час',\n hh: '%d часа',\n d: 'ден',\n dd: '%d дена',\n w: 'седмица',\n ww: '%d седмици',\n M: 'месец',\n MM: '%d месеца',\n y: 'година',\n yy: '%d години',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}-(ев|ен|ти|ви|ри|ми)/,\n ordinal: function (number) {\n var lastDigit = number % 10,\n last2Digits = number % 100;\n if (number === 0) {\n return number + '-ев';\n } else if (last2Digits === 0) {\n return number + '-ен';\n } else if (last2Digits > 10 && last2Digits < 20) {\n return number + '-ти';\n } else if (lastDigit === 1) {\n return number + '-ви';\n } else if (lastDigit === 2) {\n return number + '-ри';\n } else if (lastDigit === 7 || lastDigit === 8) {\n return number + '-ми';\n } else {\n return number + '-ти';\n }\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return bg;\n\n})));\n","//! moment.js locale configuration\n//! locale : Bambara [bm]\n//! author : Estelle Comment : https://github.com/estellecomment\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var bm = moment.defineLocale('bm', {\n months: 'Zanwuyekalo_Fewuruyekalo_Marisikalo_Awirilikalo_Mɛkalo_Zuwɛnkalo_Zuluyekalo_Utikalo_Sɛtanburukalo_ɔkutɔburukalo_Nowanburukalo_Desanburukalo'.split(\n '_'\n ),\n monthsShort: 'Zan_Few_Mar_Awi_Mɛ_Zuw_Zul_Uti_Sɛt_ɔku_Now_Des'.split('_'),\n weekdays: 'Kari_Ntɛnɛn_Tarata_Araba_Alamisa_Juma_Sibiri'.split('_'),\n weekdaysShort: 'Kar_Ntɛ_Tar_Ara_Ala_Jum_Sib'.split('_'),\n weekdaysMin: 'Ka_Nt_Ta_Ar_Al_Ju_Si'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'MMMM [tile] D [san] YYYY',\n LLL: 'MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm',\n LLLL: 'dddd MMMM [tile] D [san] YYYY [lɛrɛ] HH:mm',\n },\n calendar: {\n sameDay: '[Bi lɛrɛ] LT',\n nextDay: '[Sini lɛrɛ] LT',\n nextWeek: 'dddd [don lɛrɛ] LT',\n lastDay: '[Kunu lɛrɛ] LT',\n lastWeek: 'dddd [tɛmɛnen lɛrɛ] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s kɔnɔ',\n past: 'a bɛ %s bɔ',\n s: 'sanga dama dama',\n ss: 'sekondi %d',\n m: 'miniti kelen',\n mm: 'miniti %d',\n h: 'lɛrɛ kelen',\n hh: 'lɛrɛ %d',\n d: 'tile kelen',\n dd: 'tile %d',\n M: 'kalo kelen',\n MM: 'kalo %d',\n y: 'san kelen',\n yy: 'san %d',\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return bm;\n\n})));\n","//! moment.js locale configuration\n//! locale : Bengali (Bangladesh) [bn-bd]\n//! author : Asraf Hossain Patoary : https://github.com/ashwoolford\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '১',\n 2: '২',\n 3: '৩',\n 4: '৪',\n 5: '৫',\n 6: '৬',\n 7: '৭',\n 8: '৮',\n 9: '৯',\n 0: '০',\n },\n numberMap = {\n '১': '1',\n '২': '2',\n '৩': '3',\n '৪': '4',\n '৫': '5',\n '৬': '6',\n '৭': '7',\n '৮': '8',\n '৯': '9',\n '০': '0',\n };\n\n var bnBd = moment.defineLocale('bn-bd', {\n months: 'জানুয়ারি_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split(\n '_'\n ),\n monthsShort:\n 'জানু_ফেব্রু_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্ট_অক্টো_নভে_ডিসে'.split(\n '_'\n ),\n weekdays: 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split(\n '_'\n ),\n weekdaysShort: 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'),\n weekdaysMin: 'রবি_সোম_মঙ্গল_বুধ_বৃহ_শুক্র_শনি'.split('_'),\n longDateFormat: {\n LT: 'A h:mm সময়',\n LTS: 'A h:mm:ss সময়',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY, A h:mm সময়',\n LLLL: 'dddd, D MMMM YYYY, A h:mm সময়',\n },\n calendar: {\n sameDay: '[আজ] LT',\n nextDay: '[আগামীকাল] LT',\n nextWeek: 'dddd, LT',\n lastDay: '[গতকাল] LT',\n lastWeek: '[গত] dddd, LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s পরে',\n past: '%s আগে',\n s: 'কয়েক সেকেন্ড',\n ss: '%d সেকেন্ড',\n m: 'এক মিনিট',\n mm: '%d মিনিট',\n h: 'এক ঘন্টা',\n hh: '%d ঘন্টা',\n d: 'এক দিন',\n dd: '%d দিন',\n M: 'এক মাস',\n MM: '%d মাস',\n y: 'এক বছর',\n yy: '%d বছর',\n },\n preparse: function (string) {\n return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) {\n return numberMap[match];\n });\n },\n postformat: function (string) {\n return string.replace(/\\d/g, function (match) {\n return symbolMap[match];\n });\n },\n\n meridiemParse: /রাত|ভোর|সকাল|দুপুর|বিকাল|সন্ধ্যা|রাত/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (meridiem === 'রাত') {\n return hour < 4 ? hour : hour + 12;\n } else if (meridiem === 'ভোর') {\n return hour;\n } else if (meridiem === 'সকাল') {\n return hour;\n } else if (meridiem === 'দুপুর') {\n return hour >= 3 ? hour : hour + 12;\n } else if (meridiem === 'বিকাল') {\n return hour + 12;\n } else if (meridiem === 'সন্ধ্যা') {\n return hour + 12;\n }\n },\n\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'রাত';\n } else if (hour < 6) {\n return 'ভোর';\n } else if (hour < 12) {\n return 'সকাল';\n } else if (hour < 15) {\n return 'দুপুর';\n } else if (hour < 18) {\n return 'বিকাল';\n } else if (hour < 20) {\n return 'সন্ধ্যা';\n } else {\n return 'রাত';\n }\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return bnBd;\n\n})));\n","//! moment.js locale configuration\n//! locale : Bengali [bn]\n//! author : Kaushik Gandhi : https://github.com/kaushikgandhi\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '১',\n 2: '২',\n 3: '৩',\n 4: '৪',\n 5: '৫',\n 6: '৬',\n 7: '৭',\n 8: '৮',\n 9: '৯',\n 0: '০',\n },\n numberMap = {\n '১': '1',\n '২': '2',\n '৩': '3',\n '৪': '4',\n '৫': '5',\n '৬': '6',\n '৭': '7',\n '৮': '8',\n '৯': '9',\n '০': '0',\n };\n\n var bn = moment.defineLocale('bn', {\n months: 'জানুয়ারি_ফেব্রুয়ারি_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্টেম্বর_অক্টোবর_নভেম্বর_ডিসেম্বর'.split(\n '_'\n ),\n monthsShort:\n 'জানু_ফেব্রু_মার্চ_এপ্রিল_মে_জুন_জুলাই_আগস্ট_সেপ্ট_অক্টো_নভে_ডিসে'.split(\n '_'\n ),\n weekdays: 'রবিবার_সোমবার_মঙ্গলবার_বুধবার_বৃহস্পতিবার_শুক্রবার_শনিবার'.split(\n '_'\n ),\n weekdaysShort: 'রবি_সোম_মঙ্গল_বুধ_বৃহস্পতি_শুক্র_শনি'.split('_'),\n weekdaysMin: 'রবি_সোম_মঙ্গল_বুধ_বৃহ_শুক্র_শনি'.split('_'),\n longDateFormat: {\n LT: 'A h:mm সময়',\n LTS: 'A h:mm:ss সময়',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY, A h:mm সময়',\n LLLL: 'dddd, D MMMM YYYY, A h:mm সময়',\n },\n calendar: {\n sameDay: '[আজ] LT',\n nextDay: '[আগামীকাল] LT',\n nextWeek: 'dddd, LT',\n lastDay: '[গতকাল] LT',\n lastWeek: '[গত] dddd, LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s পরে',\n past: '%s আগে',\n s: 'কয়েক সেকেন্ড',\n ss: '%d সেকেন্ড',\n m: 'এক মিনিট',\n mm: '%d মিনিট',\n h: 'এক ঘন্টা',\n hh: '%d ঘন্টা',\n d: 'এক দিন',\n dd: '%d দিন',\n M: 'এক মাস',\n MM: '%d মাস',\n y: 'এক বছর',\n yy: '%d বছর',\n },\n preparse: function (string) {\n return string.replace(/[১২৩৪৫৬৭৮৯০]/g, function (match) {\n return numberMap[match];\n });\n },\n postformat: function (string) {\n return string.replace(/\\d/g, function (match) {\n return symbolMap[match];\n });\n },\n meridiemParse: /রাত|সকাল|দুপুর|বিকাল|রাত/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (\n (meridiem === 'রাত' && hour >= 4) ||\n (meridiem === 'দুপুর' && hour < 5) ||\n meridiem === 'বিকাল'\n ) {\n return hour + 12;\n } else {\n return hour;\n }\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'রাত';\n } else if (hour < 10) {\n return 'সকাল';\n } else if (hour < 17) {\n return 'দুপুর';\n } else if (hour < 20) {\n return 'বিকাল';\n } else {\n return 'রাত';\n }\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return bn;\n\n})));\n","//! moment.js locale configuration\n//! locale : Tibetan [bo]\n//! author : Thupten N. Chakrishar : https://github.com/vajradog\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '༡',\n 2: '༢',\n 3: '༣',\n 4: '༤',\n 5: '༥',\n 6: '༦',\n 7: '༧',\n 8: '༨',\n 9: '༩',\n 0: '༠',\n },\n numberMap = {\n '༡': '1',\n '༢': '2',\n '༣': '3',\n '༤': '4',\n '༥': '5',\n '༦': '6',\n '༧': '7',\n '༨': '8',\n '༩': '9',\n '༠': '0',\n };\n\n var bo = moment.defineLocale('bo', {\n months: 'ཟླ་བ་དང་པོ_ཟླ་བ་གཉིས་པ_ཟླ་བ་གསུམ་པ_ཟླ་བ་བཞི་པ_ཟླ་བ་ལྔ་པ_ཟླ་བ་དྲུག་པ_ཟླ་བ་བདུན་པ_ཟླ་བ་བརྒྱད་པ_ཟླ་བ་དགུ་པ_ཟླ་བ་བཅུ་པ_ཟླ་བ་བཅུ་གཅིག་པ_ཟླ་བ་བཅུ་གཉིས་པ'.split(\n '_'\n ),\n monthsShort:\n 'ཟླ་1_ཟླ་2_ཟླ་3_ཟླ་4_ཟླ་5_ཟླ་6_ཟླ་7_ཟླ་8_ཟླ་9_ཟླ་10_ཟླ་11_ཟླ་12'.split(\n '_'\n ),\n monthsShortRegex: /^(ཟླ་\\d{1,2})/,\n monthsParseExact: true,\n weekdays:\n 'གཟའ་ཉི་མ་_གཟའ་ཟླ་བ་_གཟའ་མིག་དམར་_གཟའ་ལྷག་པ་_གཟའ་ཕུར་བུ_གཟའ་པ་སངས་_གཟའ་སྤེན་པ་'.split(\n '_'\n ),\n weekdaysShort: 'ཉི་མ་_ཟླ་བ་_མིག་དམར་_ལྷག་པ་_ཕུར་བུ_པ་སངས་_སྤེན་པ་'.split(\n '_'\n ),\n weekdaysMin: 'ཉི_ཟླ_མིག_ལྷག_ཕུར_སངས_སྤེན'.split('_'),\n longDateFormat: {\n LT: 'A h:mm',\n LTS: 'A h:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY, A h:mm',\n LLLL: 'dddd, D MMMM YYYY, A h:mm',\n },\n calendar: {\n sameDay: '[དི་རིང] LT',\n nextDay: '[སང་ཉིན] LT',\n nextWeek: '[བདུན་ཕྲག་རྗེས་མ], LT',\n lastDay: '[ཁ་སང] LT',\n lastWeek: '[བདུན་ཕྲག་མཐའ་མ] dddd, LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s ལ་',\n past: '%s སྔན་ལ',\n s: 'ལམ་སང',\n ss: '%d སྐར་ཆ།',\n m: 'སྐར་མ་གཅིག',\n mm: '%d སྐར་མ',\n h: 'ཆུ་ཚོད་གཅིག',\n hh: '%d ཆུ་ཚོད',\n d: 'ཉིན་གཅིག',\n dd: '%d ཉིན་',\n M: 'ཟླ་བ་གཅིག',\n MM: '%d ཟླ་བ',\n y: 'ལོ་གཅིག',\n yy: '%d ལོ',\n },\n preparse: function (string) {\n return string.replace(/[༡༢༣༤༥༦༧༨༩༠]/g, function (match) {\n return numberMap[match];\n });\n },\n postformat: function (string) {\n return string.replace(/\\d/g, function (match) {\n return symbolMap[match];\n });\n },\n meridiemParse: /མཚན་མོ|ཞོགས་ཀས|ཉིན་གུང|དགོང་དག|མཚན་མོ/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (\n (meridiem === 'མཚན་མོ' && hour >= 4) ||\n (meridiem === 'ཉིན་གུང' && hour < 5) ||\n meridiem === 'དགོང་དག'\n ) {\n return hour + 12;\n } else {\n return hour;\n }\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'མཚན་མོ';\n } else if (hour < 10) {\n return 'ཞོགས་ཀས';\n } else if (hour < 17) {\n return 'ཉིན་གུང';\n } else if (hour < 20) {\n return 'དགོང་དག';\n } else {\n return 'མཚན་མོ';\n }\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return bo;\n\n})));\n","//! moment.js locale configuration\n//! locale : Breton [br]\n//! author : Jean-Baptiste Le Duigou : https://github.com/jbleduigou\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function relativeTimeWithMutation(number, withoutSuffix, key) {\n var format = {\n mm: 'munutenn',\n MM: 'miz',\n dd: 'devezh',\n };\n return number + ' ' + mutation(format[key], number);\n }\n function specialMutationForYears(number) {\n switch (lastNumber(number)) {\n case 1:\n case 3:\n case 4:\n case 5:\n case 9:\n return number + ' bloaz';\n default:\n return number + ' vloaz';\n }\n }\n function lastNumber(number) {\n if (number > 9) {\n return lastNumber(number % 10);\n }\n return number;\n }\n function mutation(text, number) {\n if (number === 2) {\n return softMutation(text);\n }\n return text;\n }\n function softMutation(text) {\n var mutationTable = {\n m: 'v',\n b: 'v',\n d: 'z',\n };\n if (mutationTable[text.charAt(0)] === undefined) {\n return text;\n }\n return mutationTable[text.charAt(0)] + text.substring(1);\n }\n\n var monthsParse = [\n /^gen/i,\n /^c[ʼ\\']hwe/i,\n /^meu/i,\n /^ebr/i,\n /^mae/i,\n /^(mez|eve)/i,\n /^gou/i,\n /^eos/i,\n /^gwe/i,\n /^her/i,\n /^du/i,\n /^ker/i,\n ],\n monthsRegex =\n /^(genver|c[ʼ\\']hwevrer|meurzh|ebrel|mae|mezheven|gouere|eost|gwengolo|here|du|kerzu|gen|c[ʼ\\']hwe|meu|ebr|mae|eve|gou|eos|gwe|her|du|ker)/i,\n monthsStrictRegex =\n /^(genver|c[ʼ\\']hwevrer|meurzh|ebrel|mae|mezheven|gouere|eost|gwengolo|here|du|kerzu)/i,\n monthsShortStrictRegex =\n /^(gen|c[ʼ\\']hwe|meu|ebr|mae|eve|gou|eos|gwe|her|du|ker)/i,\n fullWeekdaysParse = [\n /^sul/i,\n /^lun/i,\n /^meurzh/i,\n /^merc[ʼ\\']her/i,\n /^yaou/i,\n /^gwener/i,\n /^sadorn/i,\n ],\n shortWeekdaysParse = [\n /^Sul/i,\n /^Lun/i,\n /^Meu/i,\n /^Mer/i,\n /^Yao/i,\n /^Gwe/i,\n /^Sad/i,\n ],\n minWeekdaysParse = [\n /^Su/i,\n /^Lu/i,\n /^Me([^r]|$)/i,\n /^Mer/i,\n /^Ya/i,\n /^Gw/i,\n /^Sa/i,\n ];\n\n var br = moment.defineLocale('br', {\n months: 'Genver_Cʼhwevrer_Meurzh_Ebrel_Mae_Mezheven_Gouere_Eost_Gwengolo_Here_Du_Kerzu'.split(\n '_'\n ),\n monthsShort: 'Gen_Cʼhwe_Meu_Ebr_Mae_Eve_Gou_Eos_Gwe_Her_Du_Ker'.split('_'),\n weekdays: 'Sul_Lun_Meurzh_Mercʼher_Yaou_Gwener_Sadorn'.split('_'),\n weekdaysShort: 'Sul_Lun_Meu_Mer_Yao_Gwe_Sad'.split('_'),\n weekdaysMin: 'Su_Lu_Me_Mer_Ya_Gw_Sa'.split('_'),\n weekdaysParse: minWeekdaysParse,\n fullWeekdaysParse: fullWeekdaysParse,\n shortWeekdaysParse: shortWeekdaysParse,\n minWeekdaysParse: minWeekdaysParse,\n\n monthsRegex: monthsRegex,\n monthsShortRegex: monthsRegex,\n monthsStrictRegex: monthsStrictRegex,\n monthsShortStrictRegex: monthsShortStrictRegex,\n monthsParse: monthsParse,\n longMonthsParse: monthsParse,\n shortMonthsParse: monthsParse,\n\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D [a viz] MMMM YYYY',\n LLL: 'D [a viz] MMMM YYYY HH:mm',\n LLLL: 'dddd, D [a viz] MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Hiziv da] LT',\n nextDay: '[Warcʼhoazh da] LT',\n nextWeek: 'dddd [da] LT',\n lastDay: '[Decʼh da] LT',\n lastWeek: 'dddd [paset da] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'a-benn %s',\n past: '%s ʼzo',\n s: 'un nebeud segondennoù',\n ss: '%d eilenn',\n m: 'ur vunutenn',\n mm: relativeTimeWithMutation,\n h: 'un eur',\n hh: '%d eur',\n d: 'un devezh',\n dd: relativeTimeWithMutation,\n M: 'ur miz',\n MM: relativeTimeWithMutation,\n y: 'ur bloaz',\n yy: specialMutationForYears,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(añ|vet)/,\n ordinal: function (number) {\n var output = number === 1 ? 'añ' : 'vet';\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n meridiemParse: /a.m.|g.m./, // goude merenn | a-raok merenn\n isPM: function (token) {\n return token === 'g.m.';\n },\n meridiem: function (hour, minute, isLower) {\n return hour < 12 ? 'a.m.' : 'g.m.';\n },\n });\n\n return br;\n\n})));\n","//! moment.js locale configuration\n//! locale : Bosnian [bs]\n//! author : Nedim Cholich : https://github.com/frontyard\n//! author : Rasid Redzic : https://github.com/rasidre\n//! based on (hr) translation by Bojan Marković\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function processRelativeTime(number, withoutSuffix, key, isFuture) {\n switch (key) {\n case 'm':\n return withoutSuffix\n ? 'jedna minuta'\n : isFuture\n ? 'jednu minutu'\n : 'jedne minute';\n }\n }\n\n function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jedan sat';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }\n\n var bs = moment.defineLocale('bs', {\n months: 'januar_februar_mart_april_maj_juni_juli_august_septembar_oktobar_novembar_decembar'.split(\n '_'\n ),\n monthsShort:\n 'jan._feb._mar._apr._maj._jun._jul._aug._sep._okt._nov._dec.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split(\n '_'\n ),\n weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),\n weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D. MMMM YYYY',\n LLL: 'D. MMMM YYYY H:mm',\n LLLL: 'dddd, D. MMMM YYYY H:mm',\n },\n calendar: {\n sameDay: '[danas u] LT',\n nextDay: '[sutra u] LT',\n nextWeek: function () {\n switch (this.day()) {\n case 0:\n return '[u] [nedjelju] [u] LT';\n case 3:\n return '[u] [srijedu] [u] LT';\n case 6:\n return '[u] [subotu] [u] LT';\n case 1:\n case 2:\n case 4:\n case 5:\n return '[u] dddd [u] LT';\n }\n },\n lastDay: '[jučer u] LT',\n lastWeek: function () {\n switch (this.day()) {\n case 0:\n case 3:\n return '[prošlu] dddd [u] LT';\n case 6:\n return '[prošle] [subote] [u] LT';\n case 1:\n case 2:\n case 4:\n case 5:\n return '[prošli] dddd [u] LT';\n }\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'za %s',\n past: 'prije %s',\n s: 'par sekundi',\n ss: translate,\n m: processRelativeTime,\n mm: translate,\n h: translate,\n hh: translate,\n d: 'dan',\n dd: translate,\n M: 'mjesec',\n MM: translate,\n y: 'godinu',\n yy: translate,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return bs;\n\n})));\n","//! moment.js locale configuration\n//! locale : Catalan [ca]\n//! author : Juan G. Hurtado : https://github.com/juanghurtado\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var ca = moment.defineLocale('ca', {\n months: {\n standalone:\n 'gener_febrer_març_abril_maig_juny_juliol_agost_setembre_octubre_novembre_desembre'.split(\n '_'\n ),\n format: \"de gener_de febrer_de març_d'abril_de maig_de juny_de juliol_d'agost_de setembre_d'octubre_de novembre_de desembre\".split(\n '_'\n ),\n isFormat: /D[oD]?(\\s)+MMMM/,\n },\n monthsShort:\n 'gen._febr._març_abr._maig_juny_jul._ag._set._oct._nov._des.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays:\n 'diumenge_dilluns_dimarts_dimecres_dijous_divendres_dissabte'.split(\n '_'\n ),\n weekdaysShort: 'dg._dl._dt._dc._dj._dv._ds.'.split('_'),\n weekdaysMin: 'dg_dl_dt_dc_dj_dv_ds'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM [de] YYYY',\n ll: 'D MMM YYYY',\n LLL: 'D MMMM [de] YYYY [a les] H:mm',\n lll: 'D MMM YYYY, H:mm',\n LLLL: 'dddd D MMMM [de] YYYY [a les] H:mm',\n llll: 'ddd D MMM YYYY, H:mm',\n },\n calendar: {\n sameDay: function () {\n return '[avui a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT';\n },\n nextDay: function () {\n return '[demà a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT';\n },\n nextWeek: function () {\n return 'dddd [a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT';\n },\n lastDay: function () {\n return '[ahir a ' + (this.hours() !== 1 ? 'les' : 'la') + '] LT';\n },\n lastWeek: function () {\n return (\n '[el] dddd [passat a ' +\n (this.hours() !== 1 ? 'les' : 'la') +\n '] LT'\n );\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: \"d'aquí %s\",\n past: 'fa %s',\n s: 'uns segons',\n ss: '%d segons',\n m: 'un minut',\n mm: '%d minuts',\n h: 'una hora',\n hh: '%d hores',\n d: 'un dia',\n dd: '%d dies',\n M: 'un mes',\n MM: '%d mesos',\n y: 'un any',\n yy: '%d anys',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(r|n|t|è|a)/,\n ordinal: function (number, period) {\n var output =\n number === 1\n ? 'r'\n : number === 2\n ? 'n'\n : number === 3\n ? 'r'\n : number === 4\n ? 't'\n : 'è';\n if (period === 'w' || period === 'W') {\n output = 'a';\n }\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return ca;\n\n})));\n","//! moment.js locale configuration\n//! locale : Czech [cs]\n//! author : petrbela : https://github.com/petrbela\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var months = {\n standalone:\n 'leden_únor_březen_duben_květen_červen_červenec_srpen_září_říjen_listopad_prosinec'.split(\n '_'\n ),\n format: 'ledna_února_března_dubna_května_června_července_srpna_září_října_listopadu_prosince'.split(\n '_'\n ),\n isFormat: /DD?[o.]?(\\[[^\\[\\]]*\\]|\\s)+MMMM/,\n },\n monthsShort = 'led_úno_bře_dub_kvě_čvn_čvc_srp_zář_říj_lis_pro'.split('_'),\n monthsParse = [\n /^led/i,\n /^úno/i,\n /^bře/i,\n /^dub/i,\n /^kvě/i,\n /^(čvn|červen$|června)/i,\n /^(čvc|červenec|července)/i,\n /^srp/i,\n /^zář/i,\n /^říj/i,\n /^lis/i,\n /^pro/i,\n ],\n // NOTE: 'červen' is substring of 'červenec'; therefore 'červenec' must precede 'červen' in the regex to be fully matched.\n // Otherwise parser matches '1. červenec' as '1. červen' + 'ec'.\n monthsRegex =\n /^(leden|únor|březen|duben|květen|červenec|července|červen|června|srpen|září|říjen|listopad|prosinec|led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i;\n\n function plural(n) {\n return n > 1 && n < 5 && ~~(n / 10) !== 1;\n }\n function translate(number, withoutSuffix, key, isFuture) {\n var result = number + ' ';\n switch (key) {\n case 's': // a few seconds / in a few seconds / a few seconds ago\n return withoutSuffix || isFuture ? 'pár sekund' : 'pár sekundami';\n case 'ss': // 9 seconds / in 9 seconds / 9 seconds ago\n if (withoutSuffix || isFuture) {\n return result + (plural(number) ? 'sekundy' : 'sekund');\n } else {\n return result + 'sekundami';\n }\n case 'm': // a minute / in a minute / a minute ago\n return withoutSuffix ? 'minuta' : isFuture ? 'minutu' : 'minutou';\n case 'mm': // 9 minutes / in 9 minutes / 9 minutes ago\n if (withoutSuffix || isFuture) {\n return result + (plural(number) ? 'minuty' : 'minut');\n } else {\n return result + 'minutami';\n }\n case 'h': // an hour / in an hour / an hour ago\n return withoutSuffix ? 'hodina' : isFuture ? 'hodinu' : 'hodinou';\n case 'hh': // 9 hours / in 9 hours / 9 hours ago\n if (withoutSuffix || isFuture) {\n return result + (plural(number) ? 'hodiny' : 'hodin');\n } else {\n return result + 'hodinami';\n }\n case 'd': // a day / in a day / a day ago\n return withoutSuffix || isFuture ? 'den' : 'dnem';\n case 'dd': // 9 days / in 9 days / 9 days ago\n if (withoutSuffix || isFuture) {\n return result + (plural(number) ? 'dny' : 'dní');\n } else {\n return result + 'dny';\n }\n case 'M': // a month / in a month / a month ago\n return withoutSuffix || isFuture ? 'měsíc' : 'měsícem';\n case 'MM': // 9 months / in 9 months / 9 months ago\n if (withoutSuffix || isFuture) {\n return result + (plural(number) ? 'měsíce' : 'měsíců');\n } else {\n return result + 'měsíci';\n }\n case 'y': // a year / in a year / a year ago\n return withoutSuffix || isFuture ? 'rok' : 'rokem';\n case 'yy': // 9 years / in 9 years / 9 years ago\n if (withoutSuffix || isFuture) {\n return result + (plural(number) ? 'roky' : 'let');\n } else {\n return result + 'lety';\n }\n }\n }\n\n var cs = moment.defineLocale('cs', {\n months: months,\n monthsShort: monthsShort,\n monthsRegex: monthsRegex,\n monthsShortRegex: monthsRegex,\n // NOTE: 'červen' is substring of 'červenec'; therefore 'červenec' must precede 'červen' in the regex to be fully matched.\n // Otherwise parser matches '1. červenec' as '1. červen' + 'ec'.\n monthsStrictRegex:\n /^(leden|ledna|února|únor|březen|března|duben|dubna|květen|května|červenec|července|červen|června|srpen|srpna|září|říjen|října|listopadu|listopad|prosinec|prosince)/i,\n monthsShortStrictRegex:\n /^(led|úno|bře|dub|kvě|čvn|čvc|srp|zář|říj|lis|pro)/i,\n monthsParse: monthsParse,\n longMonthsParse: monthsParse,\n shortMonthsParse: monthsParse,\n weekdays: 'neděle_pondělí_úterý_středa_čtvrtek_pátek_sobota'.split('_'),\n weekdaysShort: 'ne_po_út_st_čt_pá_so'.split('_'),\n weekdaysMin: 'ne_po_út_st_čt_pá_so'.split('_'),\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D. MMMM YYYY',\n LLL: 'D. MMMM YYYY H:mm',\n LLLL: 'dddd D. MMMM YYYY H:mm',\n l: 'D. M. YYYY',\n },\n calendar: {\n sameDay: '[dnes v] LT',\n nextDay: '[zítra v] LT',\n nextWeek: function () {\n switch (this.day()) {\n case 0:\n return '[v neděli v] LT';\n case 1:\n case 2:\n return '[v] dddd [v] LT';\n case 3:\n return '[ve středu v] LT';\n case 4:\n return '[ve čtvrtek v] LT';\n case 5:\n return '[v pátek v] LT';\n case 6:\n return '[v sobotu v] LT';\n }\n },\n lastDay: '[včera v] LT',\n lastWeek: function () {\n switch (this.day()) {\n case 0:\n return '[minulou neděli v] LT';\n case 1:\n case 2:\n return '[minulé] dddd [v] LT';\n case 3:\n return '[minulou středu v] LT';\n case 4:\n case 5:\n return '[minulý] dddd [v] LT';\n case 6:\n return '[minulou sobotu v] LT';\n }\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'za %s',\n past: 'před %s',\n s: translate,\n ss: translate,\n m: translate,\n mm: translate,\n h: translate,\n hh: translate,\n d: translate,\n dd: translate,\n M: translate,\n MM: translate,\n y: translate,\n yy: translate,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return cs;\n\n})));\n","//! moment.js locale configuration\n//! locale : Chuvash [cv]\n//! author : Anatoly Mironov : https://github.com/mirontoli\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var cv = moment.defineLocale('cv', {\n months: 'кӑрлач_нарӑс_пуш_ака_май_ҫӗртме_утӑ_ҫурла_авӑн_юпа_чӳк_раштав'.split(\n '_'\n ),\n monthsShort: 'кӑр_нар_пуш_ака_май_ҫӗр_утӑ_ҫур_авн_юпа_чӳк_раш'.split('_'),\n weekdays:\n 'вырсарникун_тунтикун_ытларикун_юнкун_кӗҫнерникун_эрнекун_шӑматкун'.split(\n '_'\n ),\n weekdaysShort: 'выр_тун_ытл_юн_кӗҫ_эрн_шӑм'.split('_'),\n weekdaysMin: 'вр_тн_ыт_юн_кҫ_эр_шм'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD-MM-YYYY',\n LL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ]',\n LLL: 'YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm',\n LLLL: 'dddd, YYYY [ҫулхи] MMMM [уйӑхӗн] D[-мӗшӗ], HH:mm',\n },\n calendar: {\n sameDay: '[Паян] LT [сехетре]',\n nextDay: '[Ыран] LT [сехетре]',\n lastDay: '[Ӗнер] LT [сехетре]',\n nextWeek: '[Ҫитес] dddd LT [сехетре]',\n lastWeek: '[Иртнӗ] dddd LT [сехетре]',\n sameElse: 'L',\n },\n relativeTime: {\n future: function (output) {\n var affix = /сехет$/i.exec(output)\n ? 'рен'\n : /ҫул$/i.exec(output)\n ? 'тан'\n : 'ран';\n return output + affix;\n },\n past: '%s каялла',\n s: 'пӗр-ик ҫеккунт',\n ss: '%d ҫеккунт',\n m: 'пӗр минут',\n mm: '%d минут',\n h: 'пӗр сехет',\n hh: '%d сехет',\n d: 'пӗр кун',\n dd: '%d кун',\n M: 'пӗр уйӑх',\n MM: '%d уйӑх',\n y: 'пӗр ҫул',\n yy: '%d ҫул',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}-мӗш/,\n ordinal: '%d-мӗш',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return cv;\n\n})));\n","//! moment.js locale configuration\n//! locale : Welsh [cy]\n//! author : Robert Allen : https://github.com/robgallen\n//! author : https://github.com/ryangreaves\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var cy = moment.defineLocale('cy', {\n months: 'Ionawr_Chwefror_Mawrth_Ebrill_Mai_Mehefin_Gorffennaf_Awst_Medi_Hydref_Tachwedd_Rhagfyr'.split(\n '_'\n ),\n monthsShort: 'Ion_Chwe_Maw_Ebr_Mai_Meh_Gor_Aws_Med_Hyd_Tach_Rhag'.split(\n '_'\n ),\n weekdays:\n 'Dydd Sul_Dydd Llun_Dydd Mawrth_Dydd Mercher_Dydd Iau_Dydd Gwener_Dydd Sadwrn'.split(\n '_'\n ),\n weekdaysShort: 'Sul_Llun_Maw_Mer_Iau_Gwe_Sad'.split('_'),\n weekdaysMin: 'Su_Ll_Ma_Me_Ia_Gw_Sa'.split('_'),\n weekdaysParseExact: true,\n // time formats are the same as en-gb\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Heddiw am] LT',\n nextDay: '[Yfory am] LT',\n nextWeek: 'dddd [am] LT',\n lastDay: '[Ddoe am] LT',\n lastWeek: 'dddd [diwethaf am] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'mewn %s',\n past: '%s yn ôl',\n s: 'ychydig eiliadau',\n ss: '%d eiliad',\n m: 'munud',\n mm: '%d munud',\n h: 'awr',\n hh: '%d awr',\n d: 'diwrnod',\n dd: '%d diwrnod',\n M: 'mis',\n MM: '%d mis',\n y: 'blwyddyn',\n yy: '%d flynedd',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(fed|ain|af|il|ydd|ed|eg)/,\n // traditional ordinal numbers above 31 are not commonly used in colloquial Welsh\n ordinal: function (number) {\n var b = number,\n output = '',\n lookup = [\n '',\n 'af',\n 'il',\n 'ydd',\n 'ydd',\n 'ed',\n 'ed',\n 'ed',\n 'fed',\n 'fed',\n 'fed', // 1af to 10fed\n 'eg',\n 'fed',\n 'eg',\n 'eg',\n 'fed',\n 'eg',\n 'eg',\n 'fed',\n 'eg',\n 'fed', // 11eg to 20fed\n ];\n if (b > 20) {\n if (b === 40 || b === 50 || b === 60 || b === 80 || b === 100) {\n output = 'fed'; // not 30ain, 70ain or 90ain\n } else {\n output = 'ain';\n }\n } else if (b > 0) {\n output = lookup[b];\n }\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return cy;\n\n})));\n","//! moment.js locale configuration\n//! locale : Danish [da]\n//! author : Ulrik Nielsen : https://github.com/mrbase\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var da = moment.defineLocale('da', {\n months: 'januar_februar_marts_april_maj_juni_juli_august_september_oktober_november_december'.split(\n '_'\n ),\n monthsShort: 'jan_feb_mar_apr_maj_jun_jul_aug_sep_okt_nov_dec'.split('_'),\n weekdays: 'søndag_mandag_tirsdag_onsdag_torsdag_fredag_lørdag'.split('_'),\n weekdaysShort: 'søn_man_tir_ons_tor_fre_lør'.split('_'),\n weekdaysMin: 'sø_ma_ti_on_to_fr_lø'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D. MMMM YYYY',\n LLL: 'D. MMMM YYYY HH:mm',\n LLLL: 'dddd [d.] D. MMMM YYYY [kl.] HH:mm',\n },\n calendar: {\n sameDay: '[i dag kl.] LT',\n nextDay: '[i morgen kl.] LT',\n nextWeek: 'på dddd [kl.] LT',\n lastDay: '[i går kl.] LT',\n lastWeek: '[i] dddd[s kl.] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'om %s',\n past: '%s siden',\n s: 'få sekunder',\n ss: '%d sekunder',\n m: 'et minut',\n mm: '%d minutter',\n h: 'en time',\n hh: '%d timer',\n d: 'en dag',\n dd: '%d dage',\n M: 'en måned',\n MM: '%d måneder',\n y: 'et år',\n yy: '%d år',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return da;\n\n})));\n","//! moment.js locale configuration\n//! locale : German (Austria) [de-at]\n//! author : lluchs : https://github.com/lluchs\n//! author: Menelion Elensúle: https://github.com/Oire\n//! author : Martin Groller : https://github.com/MadMG\n//! author : Mikolaj Dadela : https://github.com/mik01aj\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function processRelativeTime(number, withoutSuffix, key, isFuture) {\n var format = {\n m: ['eine Minute', 'einer Minute'],\n h: ['eine Stunde', 'einer Stunde'],\n d: ['ein Tag', 'einem Tag'],\n dd: [number + ' Tage', number + ' Tagen'],\n w: ['eine Woche', 'einer Woche'],\n M: ['ein Monat', 'einem Monat'],\n MM: [number + ' Monate', number + ' Monaten'],\n y: ['ein Jahr', 'einem Jahr'],\n yy: [number + ' Jahre', number + ' Jahren'],\n };\n return withoutSuffix ? format[key][0] : format[key][1];\n }\n\n var deAt = moment.defineLocale('de-at', {\n months: 'Jänner_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split(\n '_'\n ),\n monthsShort:\n 'Jän._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),\n monthsParseExact: true,\n weekdays:\n 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split(\n '_'\n ),\n weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),\n weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D. MMMM YYYY',\n LLL: 'D. MMMM YYYY HH:mm',\n LLLL: 'dddd, D. MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[heute um] LT [Uhr]',\n sameElse: 'L',\n nextDay: '[morgen um] LT [Uhr]',\n nextWeek: 'dddd [um] LT [Uhr]',\n lastDay: '[gestern um] LT [Uhr]',\n lastWeek: '[letzten] dddd [um] LT [Uhr]',\n },\n relativeTime: {\n future: 'in %s',\n past: 'vor %s',\n s: 'ein paar Sekunden',\n ss: '%d Sekunden',\n m: processRelativeTime,\n mm: '%d Minuten',\n h: processRelativeTime,\n hh: '%d Stunden',\n d: processRelativeTime,\n dd: processRelativeTime,\n w: processRelativeTime,\n ww: '%d Wochen',\n M: processRelativeTime,\n MM: processRelativeTime,\n y: processRelativeTime,\n yy: processRelativeTime,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return deAt;\n\n})));\n","//! moment.js locale configuration\n//! locale : German (Switzerland) [de-ch]\n//! author : sschueller : https://github.com/sschueller\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function processRelativeTime(number, withoutSuffix, key, isFuture) {\n var format = {\n m: ['eine Minute', 'einer Minute'],\n h: ['eine Stunde', 'einer Stunde'],\n d: ['ein Tag', 'einem Tag'],\n dd: [number + ' Tage', number + ' Tagen'],\n w: ['eine Woche', 'einer Woche'],\n M: ['ein Monat', 'einem Monat'],\n MM: [number + ' Monate', number + ' Monaten'],\n y: ['ein Jahr', 'einem Jahr'],\n yy: [number + ' Jahre', number + ' Jahren'],\n };\n return withoutSuffix ? format[key][0] : format[key][1];\n }\n\n var deCh = moment.defineLocale('de-ch', {\n months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split(\n '_'\n ),\n monthsShort:\n 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),\n monthsParseExact: true,\n weekdays:\n 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split(\n '_'\n ),\n weekdaysShort: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),\n weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D. MMMM YYYY',\n LLL: 'D. MMMM YYYY HH:mm',\n LLLL: 'dddd, D. MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[heute um] LT [Uhr]',\n sameElse: 'L',\n nextDay: '[morgen um] LT [Uhr]',\n nextWeek: 'dddd [um] LT [Uhr]',\n lastDay: '[gestern um] LT [Uhr]',\n lastWeek: '[letzten] dddd [um] LT [Uhr]',\n },\n relativeTime: {\n future: 'in %s',\n past: 'vor %s',\n s: 'ein paar Sekunden',\n ss: '%d Sekunden',\n m: processRelativeTime,\n mm: '%d Minuten',\n h: processRelativeTime,\n hh: '%d Stunden',\n d: processRelativeTime,\n dd: processRelativeTime,\n w: processRelativeTime,\n ww: '%d Wochen',\n M: processRelativeTime,\n MM: processRelativeTime,\n y: processRelativeTime,\n yy: processRelativeTime,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return deCh;\n\n})));\n","//! moment.js locale configuration\n//! locale : German [de]\n//! author : lluchs : https://github.com/lluchs\n//! author: Menelion Elensúle: https://github.com/Oire\n//! author : Mikolaj Dadela : https://github.com/mik01aj\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function processRelativeTime(number, withoutSuffix, key, isFuture) {\n var format = {\n m: ['eine Minute', 'einer Minute'],\n h: ['eine Stunde', 'einer Stunde'],\n d: ['ein Tag', 'einem Tag'],\n dd: [number + ' Tage', number + ' Tagen'],\n w: ['eine Woche', 'einer Woche'],\n M: ['ein Monat', 'einem Monat'],\n MM: [number + ' Monate', number + ' Monaten'],\n y: ['ein Jahr', 'einem Jahr'],\n yy: [number + ' Jahre', number + ' Jahren'],\n };\n return withoutSuffix ? format[key][0] : format[key][1];\n }\n\n var de = moment.defineLocale('de', {\n months: 'Januar_Februar_März_April_Mai_Juni_Juli_August_September_Oktober_November_Dezember'.split(\n '_'\n ),\n monthsShort:\n 'Jan._Feb._März_Apr._Mai_Juni_Juli_Aug._Sep._Okt._Nov._Dez.'.split('_'),\n monthsParseExact: true,\n weekdays:\n 'Sonntag_Montag_Dienstag_Mittwoch_Donnerstag_Freitag_Samstag'.split(\n '_'\n ),\n weekdaysShort: 'So._Mo._Di._Mi._Do._Fr._Sa.'.split('_'),\n weekdaysMin: 'So_Mo_Di_Mi_Do_Fr_Sa'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D. MMMM YYYY',\n LLL: 'D. MMMM YYYY HH:mm',\n LLLL: 'dddd, D. MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[heute um] LT [Uhr]',\n sameElse: 'L',\n nextDay: '[morgen um] LT [Uhr]',\n nextWeek: 'dddd [um] LT [Uhr]',\n lastDay: '[gestern um] LT [Uhr]',\n lastWeek: '[letzten] dddd [um] LT [Uhr]',\n },\n relativeTime: {\n future: 'in %s',\n past: 'vor %s',\n s: 'ein paar Sekunden',\n ss: '%d Sekunden',\n m: processRelativeTime,\n mm: '%d Minuten',\n h: processRelativeTime,\n hh: '%d Stunden',\n d: processRelativeTime,\n dd: processRelativeTime,\n w: processRelativeTime,\n ww: '%d Wochen',\n M: processRelativeTime,\n MM: processRelativeTime,\n y: processRelativeTime,\n yy: processRelativeTime,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return de;\n\n})));\n","//! moment.js locale configuration\n//! locale : Maldivian [dv]\n//! author : Jawish Hameed : https://github.com/jawish\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var months = [\n 'ޖެނުއަރީ',\n 'ފެބްރުއަރީ',\n 'މާރިޗު',\n 'އޭޕްރީލު',\n 'މޭ',\n 'ޖޫން',\n 'ޖުލައި',\n 'އޯގަސްޓު',\n 'ސެޕްޓެމްބަރު',\n 'އޮކްޓޯބަރު',\n 'ނޮވެމްބަރު',\n 'ޑިސެމްބަރު',\n ],\n weekdays = [\n 'އާދިއްތަ',\n 'ހޯމަ',\n 'އަންގާރަ',\n 'ބުދަ',\n 'ބުރާސްފަތި',\n 'ހުކުރު',\n 'ހޮނިހިރު',\n ];\n\n var dv = moment.defineLocale('dv', {\n months: months,\n monthsShort: months,\n weekdays: weekdays,\n weekdaysShort: weekdays,\n weekdaysMin: 'އާދި_ހޯމަ_އަން_ބުދަ_ބުރާ_ހުކު_ހޮނި'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'D/M/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n meridiemParse: /މކ|މފ/,\n isPM: function (input) {\n return 'މފ' === input;\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return 'މކ';\n } else {\n return 'މފ';\n }\n },\n calendar: {\n sameDay: '[މިއަދު] LT',\n nextDay: '[މާދަމާ] LT',\n nextWeek: 'dddd LT',\n lastDay: '[އިއްޔެ] LT',\n lastWeek: '[ފާއިތުވި] dddd LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'ތެރޭގައި %s',\n past: 'ކުރިން %s',\n s: 'ސިކުންތުކޮޅެއް',\n ss: 'd% ސިކުންތު',\n m: 'މިނިޓެއް',\n mm: 'މިނިޓު %d',\n h: 'ގަޑިއިރެއް',\n hh: 'ގަޑިއިރު %d',\n d: 'ދުވަހެއް',\n dd: 'ދުވަސް %d',\n M: 'މަހެއް',\n MM: 'މަސް %d',\n y: 'އަހަރެއް',\n yy: 'އަހަރު %d',\n },\n preparse: function (string) {\n return string.replace(/،/g, ',');\n },\n postformat: function (string) {\n return string.replace(/,/g, '،');\n },\n week: {\n dow: 7, // Sunday is the first day of the week.\n doy: 12, // The week that contains Jan 12th is the first week of the year.\n },\n });\n\n return dv;\n\n})));\n","//! moment.js locale configuration\n//! locale : Greek [el]\n//! author : Aggelos Karalias : https://github.com/mehiel\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function isFunction(input) {\n return (\n (typeof Function !== 'undefined' && input instanceof Function) ||\n Object.prototype.toString.call(input) === '[object Function]'\n );\n }\n\n var el = moment.defineLocale('el', {\n monthsNominativeEl:\n 'Ιανουάριος_Φεβρουάριος_Μάρτιος_Απρίλιος_Μάιος_Ιούνιος_Ιούλιος_Αύγουστος_Σεπτέμβριος_Οκτώβριος_Νοέμβριος_Δεκέμβριος'.split(\n '_'\n ),\n monthsGenitiveEl:\n 'Ιανουαρίου_Φεβρουαρίου_Μαρτίου_Απριλίου_Μαΐου_Ιουνίου_Ιουλίου_Αυγούστου_Σεπτεμβρίου_Οκτωβρίου_Νοεμβρίου_Δεκεμβρίου'.split(\n '_'\n ),\n months: function (momentToFormat, format) {\n if (!momentToFormat) {\n return this._monthsNominativeEl;\n } else if (\n typeof format === 'string' &&\n /D/.test(format.substring(0, format.indexOf('MMMM')))\n ) {\n // if there is a day number before 'MMMM'\n return this._monthsGenitiveEl[momentToFormat.month()];\n } else {\n return this._monthsNominativeEl[momentToFormat.month()];\n }\n },\n monthsShort: 'Ιαν_Φεβ_Μαρ_Απρ_Μαϊ_Ιουν_Ιουλ_Αυγ_Σεπ_Οκτ_Νοε_Δεκ'.split('_'),\n weekdays: 'Κυριακή_Δευτέρα_Τρίτη_Τετάρτη_Πέμπτη_Παρασκευή_Σάββατο'.split(\n '_'\n ),\n weekdaysShort: 'Κυρ_Δευ_Τρι_Τετ_Πεμ_Παρ_Σαβ'.split('_'),\n weekdaysMin: 'Κυ_Δε_Τρ_Τε_Πε_Πα_Σα'.split('_'),\n meridiem: function (hours, minutes, isLower) {\n if (hours > 11) {\n return isLower ? 'μμ' : 'ΜΜ';\n } else {\n return isLower ? 'πμ' : 'ΠΜ';\n }\n },\n isPM: function (input) {\n return (input + '').toLowerCase()[0] === 'μ';\n },\n meridiemParse: /[ΠΜ]\\.?Μ?\\.?/i,\n longDateFormat: {\n LT: 'h:mm A',\n LTS: 'h:mm:ss A',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY h:mm A',\n LLLL: 'dddd, D MMMM YYYY h:mm A',\n },\n calendarEl: {\n sameDay: '[Σήμερα {}] LT',\n nextDay: '[Αύριο {}] LT',\n nextWeek: 'dddd [{}] LT',\n lastDay: '[Χθες {}] LT',\n lastWeek: function () {\n switch (this.day()) {\n case 6:\n return '[το προηγούμενο] dddd [{}] LT';\n default:\n return '[την προηγούμενη] dddd [{}] LT';\n }\n },\n sameElse: 'L',\n },\n calendar: function (key, mom) {\n var output = this._calendarEl[key],\n hours = mom && mom.hours();\n if (isFunction(output)) {\n output = output.apply(mom);\n }\n return output.replace('{}', hours % 12 === 1 ? 'στη' : 'στις');\n },\n relativeTime: {\n future: 'σε %s',\n past: '%s πριν',\n s: 'λίγα δευτερόλεπτα',\n ss: '%d δευτερόλεπτα',\n m: 'ένα λεπτό',\n mm: '%d λεπτά',\n h: 'μία ώρα',\n hh: '%d ώρες',\n d: 'μία μέρα',\n dd: '%d μέρες',\n M: 'ένας μήνας',\n MM: '%d μήνες',\n y: 'ένας χρόνος',\n yy: '%d χρόνια',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}η/,\n ordinal: '%dη',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4st is the first week of the year.\n },\n });\n\n return el;\n\n})));\n","//! moment.js locale configuration\n//! locale : English (Australia) [en-au]\n//! author : Jared Morse : https://github.com/jarcoal\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var enAu = moment.defineLocale('en-au', {\n months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),\n weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n longDateFormat: {\n LT: 'h:mm A',\n LTS: 'h:mm:ss A',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY h:mm A',\n LLLL: 'dddd, D MMMM YYYY h:mm A',\n },\n calendar: {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(st|nd|rd|th)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n ~~((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return enAu;\n\n})));\n","//! moment.js locale configuration\n//! locale : English (Canada) [en-ca]\n//! author : Jonathan Abourbih : https://github.com/jonbca\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var enCa = moment.defineLocale('en-ca', {\n months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),\n weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n longDateFormat: {\n LT: 'h:mm A',\n LTS: 'h:mm:ss A',\n L: 'YYYY-MM-DD',\n LL: 'MMMM D, YYYY',\n LLL: 'MMMM D, YYYY h:mm A',\n LLLL: 'dddd, MMMM D, YYYY h:mm A',\n },\n calendar: {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(st|nd|rd|th)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n ~~((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n });\n\n return enCa;\n\n})));\n","//! moment.js locale configuration\n//! locale : English (United Kingdom) [en-gb]\n//! author : Chris Gedrim : https://github.com/chrisgedrim\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var enGb = moment.defineLocale('en-gb', {\n months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),\n weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(st|nd|rd|th)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n ~~((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return enGb;\n\n})));\n","//! moment.js locale configuration\n//! locale : English (Ireland) [en-ie]\n//! author : Chris Cartlidge : https://github.com/chriscartlidge\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var enIe = moment.defineLocale('en-ie', {\n months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),\n weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(st|nd|rd|th)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n ~~((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return enIe;\n\n})));\n","//! moment.js locale configuration\n//! locale : English (Israel) [en-il]\n//! author : Chris Gedrim : https://github.com/chrisgedrim\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var enIl = moment.defineLocale('en-il', {\n months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),\n weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(st|nd|rd|th)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n ~~((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n });\n\n return enIl;\n\n})));\n","//! moment.js locale configuration\n//! locale : English (India) [en-in]\n//! author : Jatin Agrawal : https://github.com/jatinag22\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var enIn = moment.defineLocale('en-in', {\n months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),\n weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n longDateFormat: {\n LT: 'h:mm A',\n LTS: 'h:mm:ss A',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY h:mm A',\n LLLL: 'dddd, D MMMM YYYY h:mm A',\n },\n calendar: {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(st|nd|rd|th)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n ~~((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 1st is the first week of the year.\n },\n });\n\n return enIn;\n\n})));\n","//! moment.js locale configuration\n//! locale : English (New Zealand) [en-nz]\n//! author : Luke McGregor : https://github.com/lukemcgregor\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var enNz = moment.defineLocale('en-nz', {\n months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),\n weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n longDateFormat: {\n LT: 'h:mm A',\n LTS: 'h:mm:ss A',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY h:mm A',\n LLLL: 'dddd, D MMMM YYYY h:mm A',\n },\n calendar: {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(st|nd|rd|th)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n ~~((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return enNz;\n\n})));\n","//! moment.js locale configuration\n//! locale : English (Singapore) [en-sg]\n//! author : Matthew Castrillon-Madrigal : https://github.com/techdimension\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var enSg = moment.defineLocale('en-sg', {\n months: 'January_February_March_April_May_June_July_August_September_October_November_December'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'),\n weekdays: 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split(\n '_'\n ),\n weekdaysShort: 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'),\n weekdaysMin: 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Today at] LT',\n nextDay: '[Tomorrow at] LT',\n nextWeek: 'dddd [at] LT',\n lastDay: '[Yesterday at] LT',\n lastWeek: '[Last] dddd [at] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'in %s',\n past: '%s ago',\n s: 'a few seconds',\n ss: '%d seconds',\n m: 'a minute',\n mm: '%d minutes',\n h: 'an hour',\n hh: '%d hours',\n d: 'a day',\n dd: '%d days',\n M: 'a month',\n MM: '%d months',\n y: 'a year',\n yy: '%d years',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(st|nd|rd|th)/,\n ordinal: function (number) {\n var b = number % 10,\n output =\n ~~((number % 100) / 10) === 1\n ? 'th'\n : b === 1\n ? 'st'\n : b === 2\n ? 'nd'\n : b === 3\n ? 'rd'\n : 'th';\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return enSg;\n\n})));\n","//! moment.js locale configuration\n//! locale : Esperanto [eo]\n//! author : Colin Dean : https://github.com/colindean\n//! author : Mia Nordentoft Imperatori : https://github.com/miestasmia\n//! comment : miestasmia corrected the translation by colindean\n//! comment : Vivakvo corrected the translation by colindean and miestasmia\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var eo = moment.defineLocale('eo', {\n months: 'januaro_februaro_marto_aprilo_majo_junio_julio_aŭgusto_septembro_oktobro_novembro_decembro'.split(\n '_'\n ),\n monthsShort: 'jan_feb_mart_apr_maj_jun_jul_aŭg_sept_okt_nov_dec'.split('_'),\n weekdays: 'dimanĉo_lundo_mardo_merkredo_ĵaŭdo_vendredo_sabato'.split('_'),\n weekdaysShort: 'dim_lun_mard_merk_ĵaŭ_ven_sab'.split('_'),\n weekdaysMin: 'di_lu_ma_me_ĵa_ve_sa'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'YYYY-MM-DD',\n LL: '[la] D[-an de] MMMM, YYYY',\n LLL: '[la] D[-an de] MMMM, YYYY HH:mm',\n LLLL: 'dddd[n], [la] D[-an de] MMMM, YYYY HH:mm',\n llll: 'ddd, [la] D[-an de] MMM, YYYY HH:mm',\n },\n meridiemParse: /[ap]\\.t\\.m/i,\n isPM: function (input) {\n return input.charAt(0).toLowerCase() === 'p';\n },\n meridiem: function (hours, minutes, isLower) {\n if (hours > 11) {\n return isLower ? 'p.t.m.' : 'P.T.M.';\n } else {\n return isLower ? 'a.t.m.' : 'A.T.M.';\n }\n },\n calendar: {\n sameDay: '[Hodiaŭ je] LT',\n nextDay: '[Morgaŭ je] LT',\n nextWeek: 'dddd[n je] LT',\n lastDay: '[Hieraŭ je] LT',\n lastWeek: '[pasintan] dddd[n je] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'post %s',\n past: 'antaŭ %s',\n s: 'kelkaj sekundoj',\n ss: '%d sekundoj',\n m: 'unu minuto',\n mm: '%d minutoj',\n h: 'unu horo',\n hh: '%d horoj',\n d: 'unu tago', //ne 'diurno', ĉar estas uzita por proksimumo\n dd: '%d tagoj',\n M: 'unu monato',\n MM: '%d monatoj',\n y: 'unu jaro',\n yy: '%d jaroj',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}a/,\n ordinal: '%da',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return eo;\n\n})));\n","//! moment.js locale configuration\n//! locale : Spanish (Dominican Republic) [es-do]\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var monthsShortDot =\n 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split(\n '_'\n ),\n monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),\n monthsParse = [\n /^ene/i,\n /^feb/i,\n /^mar/i,\n /^abr/i,\n /^may/i,\n /^jun/i,\n /^jul/i,\n /^ago/i,\n /^sep/i,\n /^oct/i,\n /^nov/i,\n /^dic/i,\n ],\n monthsRegex =\n /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\\.?|feb\\.?|mar\\.?|abr\\.?|may\\.?|jun\\.?|jul\\.?|ago\\.?|sep\\.?|oct\\.?|nov\\.?|dic\\.?)/i;\n\n var esDo = moment.defineLocale('es-do', {\n months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split(\n '_'\n ),\n monthsShort: function (m, format) {\n if (!m) {\n return monthsShortDot;\n } else if (/-MMM-/.test(format)) {\n return monthsShort[m.month()];\n } else {\n return monthsShortDot[m.month()];\n }\n },\n monthsRegex: monthsRegex,\n monthsShortRegex: monthsRegex,\n monthsStrictRegex:\n /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,\n monthsShortStrictRegex:\n /^(ene\\.?|feb\\.?|mar\\.?|abr\\.?|may\\.?|jun\\.?|jul\\.?|ago\\.?|sep\\.?|oct\\.?|nov\\.?|dic\\.?)/i,\n monthsParse: monthsParse,\n longMonthsParse: monthsParse,\n shortMonthsParse: monthsParse,\n weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),\n weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),\n weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'h:mm A',\n LTS: 'h:mm:ss A',\n L: 'DD/MM/YYYY',\n LL: 'D [de] MMMM [de] YYYY',\n LLL: 'D [de] MMMM [de] YYYY h:mm A',\n LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A',\n },\n calendar: {\n sameDay: function () {\n return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n nextDay: function () {\n return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n nextWeek: function () {\n return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n lastDay: function () {\n return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n lastWeek: function () {\n return (\n '[el] dddd [pasado a la' +\n (this.hours() !== 1 ? 's' : '') +\n '] LT'\n );\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'en %s',\n past: 'hace %s',\n s: 'unos segundos',\n ss: '%d segundos',\n m: 'un minuto',\n mm: '%d minutos',\n h: 'una hora',\n hh: '%d horas',\n d: 'un día',\n dd: '%d días',\n w: 'una semana',\n ww: '%d semanas',\n M: 'un mes',\n MM: '%d meses',\n y: 'un año',\n yy: '%d años',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}º/,\n ordinal: '%dº',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return esDo;\n\n})));\n","//! moment.js locale configuration\n//! locale : Spanish (Mexico) [es-mx]\n//! author : JC Franco : https://github.com/jcfranco\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var monthsShortDot =\n 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split(\n '_'\n ),\n monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),\n monthsParse = [\n /^ene/i,\n /^feb/i,\n /^mar/i,\n /^abr/i,\n /^may/i,\n /^jun/i,\n /^jul/i,\n /^ago/i,\n /^sep/i,\n /^oct/i,\n /^nov/i,\n /^dic/i,\n ],\n monthsRegex =\n /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\\.?|feb\\.?|mar\\.?|abr\\.?|may\\.?|jun\\.?|jul\\.?|ago\\.?|sep\\.?|oct\\.?|nov\\.?|dic\\.?)/i;\n\n var esMx = moment.defineLocale('es-mx', {\n months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split(\n '_'\n ),\n monthsShort: function (m, format) {\n if (!m) {\n return monthsShortDot;\n } else if (/-MMM-/.test(format)) {\n return monthsShort[m.month()];\n } else {\n return monthsShortDot[m.month()];\n }\n },\n monthsRegex: monthsRegex,\n monthsShortRegex: monthsRegex,\n monthsStrictRegex:\n /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,\n monthsShortStrictRegex:\n /^(ene\\.?|feb\\.?|mar\\.?|abr\\.?|may\\.?|jun\\.?|jul\\.?|ago\\.?|sep\\.?|oct\\.?|nov\\.?|dic\\.?)/i,\n monthsParse: monthsParse,\n longMonthsParse: monthsParse,\n shortMonthsParse: monthsParse,\n weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),\n weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),\n weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D [de] MMMM [de] YYYY',\n LLL: 'D [de] MMMM [de] YYYY H:mm',\n LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm',\n },\n calendar: {\n sameDay: function () {\n return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n nextDay: function () {\n return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n nextWeek: function () {\n return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n lastDay: function () {\n return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n lastWeek: function () {\n return (\n '[el] dddd [pasado a la' +\n (this.hours() !== 1 ? 's' : '') +\n '] LT'\n );\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'en %s',\n past: 'hace %s',\n s: 'unos segundos',\n ss: '%d segundos',\n m: 'un minuto',\n mm: '%d minutos',\n h: 'una hora',\n hh: '%d horas',\n d: 'un día',\n dd: '%d días',\n w: 'una semana',\n ww: '%d semanas',\n M: 'un mes',\n MM: '%d meses',\n y: 'un año',\n yy: '%d años',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}º/,\n ordinal: '%dº',\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n invalidDate: 'Fecha inválida',\n });\n\n return esMx;\n\n})));\n","//! moment.js locale configuration\n//! locale : Spanish (United States) [es-us]\n//! author : bustta : https://github.com/bustta\n//! author : chrisrodz : https://github.com/chrisrodz\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var monthsShortDot =\n 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split(\n '_'\n ),\n monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),\n monthsParse = [\n /^ene/i,\n /^feb/i,\n /^mar/i,\n /^abr/i,\n /^may/i,\n /^jun/i,\n /^jul/i,\n /^ago/i,\n /^sep/i,\n /^oct/i,\n /^nov/i,\n /^dic/i,\n ],\n monthsRegex =\n /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\\.?|feb\\.?|mar\\.?|abr\\.?|may\\.?|jun\\.?|jul\\.?|ago\\.?|sep\\.?|oct\\.?|nov\\.?|dic\\.?)/i;\n\n var esUs = moment.defineLocale('es-us', {\n months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split(\n '_'\n ),\n monthsShort: function (m, format) {\n if (!m) {\n return monthsShortDot;\n } else if (/-MMM-/.test(format)) {\n return monthsShort[m.month()];\n } else {\n return monthsShortDot[m.month()];\n }\n },\n monthsRegex: monthsRegex,\n monthsShortRegex: monthsRegex,\n monthsStrictRegex:\n /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,\n monthsShortStrictRegex:\n /^(ene\\.?|feb\\.?|mar\\.?|abr\\.?|may\\.?|jun\\.?|jul\\.?|ago\\.?|sep\\.?|oct\\.?|nov\\.?|dic\\.?)/i,\n monthsParse: monthsParse,\n longMonthsParse: monthsParse,\n shortMonthsParse: monthsParse,\n weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),\n weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),\n weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'h:mm A',\n LTS: 'h:mm:ss A',\n L: 'MM/DD/YYYY',\n LL: 'D [de] MMMM [de] YYYY',\n LLL: 'D [de] MMMM [de] YYYY h:mm A',\n LLLL: 'dddd, D [de] MMMM [de] YYYY h:mm A',\n },\n calendar: {\n sameDay: function () {\n return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n nextDay: function () {\n return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n nextWeek: function () {\n return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n lastDay: function () {\n return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n lastWeek: function () {\n return (\n '[el] dddd [pasado a la' +\n (this.hours() !== 1 ? 's' : '') +\n '] LT'\n );\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'en %s',\n past: 'hace %s',\n s: 'unos segundos',\n ss: '%d segundos',\n m: 'un minuto',\n mm: '%d minutos',\n h: 'una hora',\n hh: '%d horas',\n d: 'un día',\n dd: '%d días',\n w: 'una semana',\n ww: '%d semanas',\n M: 'un mes',\n MM: '%d meses',\n y: 'un año',\n yy: '%d años',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}º/,\n ordinal: '%dº',\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return esUs;\n\n})));\n","//! moment.js locale configuration\n//! locale : Spanish [es]\n//! author : Julio Napurí : https://github.com/julionc\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var monthsShortDot =\n 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split(\n '_'\n ),\n monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'),\n monthsParse = [\n /^ene/i,\n /^feb/i,\n /^mar/i,\n /^abr/i,\n /^may/i,\n /^jun/i,\n /^jul/i,\n /^ago/i,\n /^sep/i,\n /^oct/i,\n /^nov/i,\n /^dic/i,\n ],\n monthsRegex =\n /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\\.?|feb\\.?|mar\\.?|abr\\.?|may\\.?|jun\\.?|jul\\.?|ago\\.?|sep\\.?|oct\\.?|nov\\.?|dic\\.?)/i;\n\n var es = moment.defineLocale('es', {\n months: 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split(\n '_'\n ),\n monthsShort: function (m, format) {\n if (!m) {\n return monthsShortDot;\n } else if (/-MMM-/.test(format)) {\n return monthsShort[m.month()];\n } else {\n return monthsShortDot[m.month()];\n }\n },\n monthsRegex: monthsRegex,\n monthsShortRegex: monthsRegex,\n monthsStrictRegex:\n /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,\n monthsShortStrictRegex:\n /^(ene\\.?|feb\\.?|mar\\.?|abr\\.?|may\\.?|jun\\.?|jul\\.?|ago\\.?|sep\\.?|oct\\.?|nov\\.?|dic\\.?)/i,\n monthsParse: monthsParse,\n longMonthsParse: monthsParse,\n shortMonthsParse: monthsParse,\n weekdays: 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),\n weekdaysShort: 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),\n weekdaysMin: 'do_lu_ma_mi_ju_vi_sá'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D [de] MMMM [de] YYYY',\n LLL: 'D [de] MMMM [de] YYYY H:mm',\n LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm',\n },\n calendar: {\n sameDay: function () {\n return '[hoy a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n nextDay: function () {\n return '[mañana a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n nextWeek: function () {\n return 'dddd [a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n lastDay: function () {\n return '[ayer a la' + (this.hours() !== 1 ? 's' : '') + '] LT';\n },\n lastWeek: function () {\n return (\n '[el] dddd [pasado a la' +\n (this.hours() !== 1 ? 's' : '') +\n '] LT'\n );\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'en %s',\n past: 'hace %s',\n s: 'unos segundos',\n ss: '%d segundos',\n m: 'un minuto',\n mm: '%d minutos',\n h: 'una hora',\n hh: '%d horas',\n d: 'un día',\n dd: '%d días',\n w: 'una semana',\n ww: '%d semanas',\n M: 'un mes',\n MM: '%d meses',\n y: 'un año',\n yy: '%d años',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}º/,\n ordinal: '%dº',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n invalidDate: 'Fecha inválida',\n });\n\n return es;\n\n})));\n","//! moment.js locale configuration\n//! locale : Estonian [et]\n//! author : Henry Kehlmann : https://github.com/madhenry\n//! improvements : Illimar Tambek : https://github.com/ragulka\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function processRelativeTime(number, withoutSuffix, key, isFuture) {\n var format = {\n s: ['mõne sekundi', 'mõni sekund', 'paar sekundit'],\n ss: [number + 'sekundi', number + 'sekundit'],\n m: ['ühe minuti', 'üks minut'],\n mm: [number + ' minuti', number + ' minutit'],\n h: ['ühe tunni', 'tund aega', 'üks tund'],\n hh: [number + ' tunni', number + ' tundi'],\n d: ['ühe päeva', 'üks päev'],\n M: ['kuu aja', 'kuu aega', 'üks kuu'],\n MM: [number + ' kuu', number + ' kuud'],\n y: ['ühe aasta', 'aasta', 'üks aasta'],\n yy: [number + ' aasta', number + ' aastat'],\n };\n if (withoutSuffix) {\n return format[key][2] ? format[key][2] : format[key][1];\n }\n return isFuture ? format[key][0] : format[key][1];\n }\n\n var et = moment.defineLocale('et', {\n months: 'jaanuar_veebruar_märts_aprill_mai_juuni_juuli_august_september_oktoober_november_detsember'.split(\n '_'\n ),\n monthsShort:\n 'jaan_veebr_märts_apr_mai_juuni_juuli_aug_sept_okt_nov_dets'.split('_'),\n weekdays:\n 'pühapäev_esmaspäev_teisipäev_kolmapäev_neljapäev_reede_laupäev'.split(\n '_'\n ),\n weekdaysShort: 'P_E_T_K_N_R_L'.split('_'),\n weekdaysMin: 'P_E_T_K_N_R_L'.split('_'),\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D. MMMM YYYY',\n LLL: 'D. MMMM YYYY H:mm',\n LLLL: 'dddd, D. MMMM YYYY H:mm',\n },\n calendar: {\n sameDay: '[Täna,] LT',\n nextDay: '[Homme,] LT',\n nextWeek: '[Järgmine] dddd LT',\n lastDay: '[Eile,] LT',\n lastWeek: '[Eelmine] dddd LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s pärast',\n past: '%s tagasi',\n s: processRelativeTime,\n ss: processRelativeTime,\n m: processRelativeTime,\n mm: processRelativeTime,\n h: processRelativeTime,\n hh: processRelativeTime,\n d: processRelativeTime,\n dd: '%d päeva',\n M: processRelativeTime,\n MM: processRelativeTime,\n y: processRelativeTime,\n yy: processRelativeTime,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return et;\n\n})));\n","//! moment.js locale configuration\n//! locale : Basque [eu]\n//! author : Eneko Illarramendi : https://github.com/eillarra\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var eu = moment.defineLocale('eu', {\n months: 'urtarrila_otsaila_martxoa_apirila_maiatza_ekaina_uztaila_abuztua_iraila_urria_azaroa_abendua'.split(\n '_'\n ),\n monthsShort:\n 'urt._ots._mar._api._mai._eka._uzt._abu._ira._urr._aza._abe.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays:\n 'igandea_astelehena_asteartea_asteazkena_osteguna_ostirala_larunbata'.split(\n '_'\n ),\n weekdaysShort: 'ig._al._ar._az._og._ol._lr.'.split('_'),\n weekdaysMin: 'ig_al_ar_az_og_ol_lr'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'YYYY-MM-DD',\n LL: 'YYYY[ko] MMMM[ren] D[a]',\n LLL: 'YYYY[ko] MMMM[ren] D[a] HH:mm',\n LLLL: 'dddd, YYYY[ko] MMMM[ren] D[a] HH:mm',\n l: 'YYYY-M-D',\n ll: 'YYYY[ko] MMM D[a]',\n lll: 'YYYY[ko] MMM D[a] HH:mm',\n llll: 'ddd, YYYY[ko] MMM D[a] HH:mm',\n },\n calendar: {\n sameDay: '[gaur] LT[etan]',\n nextDay: '[bihar] LT[etan]',\n nextWeek: 'dddd LT[etan]',\n lastDay: '[atzo] LT[etan]',\n lastWeek: '[aurreko] dddd LT[etan]',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s barru',\n past: 'duela %s',\n s: 'segundo batzuk',\n ss: '%d segundo',\n m: 'minutu bat',\n mm: '%d minutu',\n h: 'ordu bat',\n hh: '%d ordu',\n d: 'egun bat',\n dd: '%d egun',\n M: 'hilabete bat',\n MM: '%d hilabete',\n y: 'urte bat',\n yy: '%d urte',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return eu;\n\n})));\n","//! moment.js locale configuration\n//! locale : Persian [fa]\n//! author : Ebrahim Byagowi : https://github.com/ebraminio\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '۱',\n 2: '۲',\n 3: '۳',\n 4: '۴',\n 5: '۵',\n 6: '۶',\n 7: '۷',\n 8: '۸',\n 9: '۹',\n 0: '۰',\n },\n numberMap = {\n '۱': '1',\n '۲': '2',\n '۳': '3',\n '۴': '4',\n '۵': '5',\n '۶': '6',\n '۷': '7',\n '۸': '8',\n '۹': '9',\n '۰': '0',\n };\n\n var fa = moment.defineLocale('fa', {\n months: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split(\n '_'\n ),\n monthsShort:\n 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split(\n '_'\n ),\n weekdays:\n 'یک\\u200cشنبه_دوشنبه_سه\\u200cشنبه_چهارشنبه_پنج\\u200cشنبه_جمعه_شنبه'.split(\n '_'\n ),\n weekdaysShort:\n 'یک\\u200cشنبه_دوشنبه_سه\\u200cشنبه_چهارشنبه_پنج\\u200cشنبه_جمعه_شنبه'.split(\n '_'\n ),\n weekdaysMin: 'ی_د_س_چ_پ_ج_ش'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n meridiemParse: /قبل از ظهر|بعد از ظهر/,\n isPM: function (input) {\n return /بعد از ظهر/.test(input);\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return 'قبل از ظهر';\n } else {\n return 'بعد از ظهر';\n }\n },\n calendar: {\n sameDay: '[امروز ساعت] LT',\n nextDay: '[فردا ساعت] LT',\n nextWeek: 'dddd [ساعت] LT',\n lastDay: '[دیروز ساعت] LT',\n lastWeek: 'dddd [پیش] [ساعت] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'در %s',\n past: '%s پیش',\n s: 'چند ثانیه',\n ss: '%d ثانیه',\n m: 'یک دقیقه',\n mm: '%d دقیقه',\n h: 'یک ساعت',\n hh: '%d ساعت',\n d: 'یک روز',\n dd: '%d روز',\n M: 'یک ماه',\n MM: '%d ماه',\n y: 'یک سال',\n yy: '%d سال',\n },\n preparse: function (string) {\n return string\n .replace(/[۰-۹]/g, function (match) {\n return numberMap[match];\n })\n .replace(/،/g, ',');\n },\n postformat: function (string) {\n return string\n .replace(/\\d/g, function (match) {\n return symbolMap[match];\n })\n .replace(/,/g, '،');\n },\n dayOfMonthOrdinalParse: /\\d{1,2}م/,\n ordinal: '%dم',\n week: {\n dow: 6, // Saturday is the first day of the week.\n doy: 12, // The week that contains Jan 12th is the first week of the year.\n },\n });\n\n return fa;\n\n})));\n","//! moment.js locale configuration\n//! locale : Finnish [fi]\n//! author : Tarmo Aidantausta : https://github.com/bleadof\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var numbersPast =\n 'nolla yksi kaksi kolme neljä viisi kuusi seitsemän kahdeksan yhdeksän'.split(\n ' '\n ),\n numbersFuture = [\n 'nolla',\n 'yhden',\n 'kahden',\n 'kolmen',\n 'neljän',\n 'viiden',\n 'kuuden',\n numbersPast[7],\n numbersPast[8],\n numbersPast[9],\n ];\n function translate(number, withoutSuffix, key, isFuture) {\n var result = '';\n switch (key) {\n case 's':\n return isFuture ? 'muutaman sekunnin' : 'muutama sekunti';\n case 'ss':\n result = isFuture ? 'sekunnin' : 'sekuntia';\n break;\n case 'm':\n return isFuture ? 'minuutin' : 'minuutti';\n case 'mm':\n result = isFuture ? 'minuutin' : 'minuuttia';\n break;\n case 'h':\n return isFuture ? 'tunnin' : 'tunti';\n case 'hh':\n result = isFuture ? 'tunnin' : 'tuntia';\n break;\n case 'd':\n return isFuture ? 'päivän' : 'päivä';\n case 'dd':\n result = isFuture ? 'päivän' : 'päivää';\n break;\n case 'M':\n return isFuture ? 'kuukauden' : 'kuukausi';\n case 'MM':\n result = isFuture ? 'kuukauden' : 'kuukautta';\n break;\n case 'y':\n return isFuture ? 'vuoden' : 'vuosi';\n case 'yy':\n result = isFuture ? 'vuoden' : 'vuotta';\n break;\n }\n result = verbalNumber(number, isFuture) + ' ' + result;\n return result;\n }\n function verbalNumber(number, isFuture) {\n return number < 10\n ? isFuture\n ? numbersFuture[number]\n : numbersPast[number]\n : number;\n }\n\n var fi = moment.defineLocale('fi', {\n months: 'tammikuu_helmikuu_maaliskuu_huhtikuu_toukokuu_kesäkuu_heinäkuu_elokuu_syyskuu_lokakuu_marraskuu_joulukuu'.split(\n '_'\n ),\n monthsShort:\n 'tammi_helmi_maalis_huhti_touko_kesä_heinä_elo_syys_loka_marras_joulu'.split(\n '_'\n ),\n weekdays:\n 'sunnuntai_maanantai_tiistai_keskiviikko_torstai_perjantai_lauantai'.split(\n '_'\n ),\n weekdaysShort: 'su_ma_ti_ke_to_pe_la'.split('_'),\n weekdaysMin: 'su_ma_ti_ke_to_pe_la'.split('_'),\n longDateFormat: {\n LT: 'HH.mm',\n LTS: 'HH.mm.ss',\n L: 'DD.MM.YYYY',\n LL: 'Do MMMM[ta] YYYY',\n LLL: 'Do MMMM[ta] YYYY, [klo] HH.mm',\n LLLL: 'dddd, Do MMMM[ta] YYYY, [klo] HH.mm',\n l: 'D.M.YYYY',\n ll: 'Do MMM YYYY',\n lll: 'Do MMM YYYY, [klo] HH.mm',\n llll: 'ddd, Do MMM YYYY, [klo] HH.mm',\n },\n calendar: {\n sameDay: '[tänään] [klo] LT',\n nextDay: '[huomenna] [klo] LT',\n nextWeek: 'dddd [klo] LT',\n lastDay: '[eilen] [klo] LT',\n lastWeek: '[viime] dddd[na] [klo] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s päästä',\n past: '%s sitten',\n s: translate,\n ss: translate,\n m: translate,\n mm: translate,\n h: translate,\n hh: translate,\n d: translate,\n dd: translate,\n M: translate,\n MM: translate,\n y: translate,\n yy: translate,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return fi;\n\n})));\n","//! moment.js locale configuration\n//! locale : Filipino [fil]\n//! author : Dan Hagman : https://github.com/hagmandan\n//! author : Matthew Co : https://github.com/matthewdeeco\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var fil = moment.defineLocale('fil', {\n months: 'Enero_Pebrero_Marso_Abril_Mayo_Hunyo_Hulyo_Agosto_Setyembre_Oktubre_Nobyembre_Disyembre'.split(\n '_'\n ),\n monthsShort: 'Ene_Peb_Mar_Abr_May_Hun_Hul_Ago_Set_Okt_Nob_Dis'.split('_'),\n weekdays: 'Linggo_Lunes_Martes_Miyerkules_Huwebes_Biyernes_Sabado'.split(\n '_'\n ),\n weekdaysShort: 'Lin_Lun_Mar_Miy_Huw_Biy_Sab'.split('_'),\n weekdaysMin: 'Li_Lu_Ma_Mi_Hu_Bi_Sab'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'MM/D/YYYY',\n LL: 'MMMM D, YYYY',\n LLL: 'MMMM D, YYYY HH:mm',\n LLLL: 'dddd, MMMM DD, YYYY HH:mm',\n },\n calendar: {\n sameDay: 'LT [ngayong araw]',\n nextDay: '[Bukas ng] LT',\n nextWeek: 'LT [sa susunod na] dddd',\n lastDay: 'LT [kahapon]',\n lastWeek: 'LT [noong nakaraang] dddd',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'sa loob ng %s',\n past: '%s ang nakalipas',\n s: 'ilang segundo',\n ss: '%d segundo',\n m: 'isang minuto',\n mm: '%d minuto',\n h: 'isang oras',\n hh: '%d oras',\n d: 'isang araw',\n dd: '%d araw',\n M: 'isang buwan',\n MM: '%d buwan',\n y: 'isang taon',\n yy: '%d taon',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}/,\n ordinal: function (number) {\n return number;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return fil;\n\n})));\n","//! moment.js locale configuration\n//! locale : Faroese [fo]\n//! author : Ragnar Johannesen : https://github.com/ragnar123\n//! author : Kristian Sakarisson : https://github.com/sakarisson\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var fo = moment.defineLocale('fo', {\n months: 'januar_februar_mars_apríl_mai_juni_juli_august_september_oktober_november_desember'.split(\n '_'\n ),\n monthsShort: 'jan_feb_mar_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_'),\n weekdays:\n 'sunnudagur_mánadagur_týsdagur_mikudagur_hósdagur_fríggjadagur_leygardagur'.split(\n '_'\n ),\n weekdaysShort: 'sun_mán_týs_mik_hós_frí_ley'.split('_'),\n weekdaysMin: 'su_má_tý_mi_hó_fr_le'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D. MMMM, YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Í dag kl.] LT',\n nextDay: '[Í morgin kl.] LT',\n nextWeek: 'dddd [kl.] LT',\n lastDay: '[Í gjár kl.] LT',\n lastWeek: '[síðstu] dddd [kl] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'um %s',\n past: '%s síðani',\n s: 'fá sekund',\n ss: '%d sekundir',\n m: 'ein minuttur',\n mm: '%d minuttir',\n h: 'ein tími',\n hh: '%d tímar',\n d: 'ein dagur',\n dd: '%d dagar',\n M: 'ein mánaður',\n MM: '%d mánaðir',\n y: 'eitt ár',\n yy: '%d ár',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return fo;\n\n})));\n","//! moment.js locale configuration\n//! locale : French (Canada) [fr-ca]\n//! author : Jonathan Abourbih : https://github.com/jonbca\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var frCa = moment.defineLocale('fr-ca', {\n months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split(\n '_'\n ),\n monthsShort:\n 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),\n weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),\n weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'YYYY-MM-DD',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Aujourd’hui à] LT',\n nextDay: '[Demain à] LT',\n nextWeek: 'dddd [à] LT',\n lastDay: '[Hier à] LT',\n lastWeek: 'dddd [dernier à] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'dans %s',\n past: 'il y a %s',\n s: 'quelques secondes',\n ss: '%d secondes',\n m: 'une minute',\n mm: '%d minutes',\n h: 'une heure',\n hh: '%d heures',\n d: 'un jour',\n dd: '%d jours',\n M: 'un mois',\n MM: '%d mois',\n y: 'un an',\n yy: '%d ans',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(er|e)/,\n ordinal: function (number, period) {\n switch (period) {\n // Words with masculine grammatical gender: mois, trimestre, jour\n default:\n case 'M':\n case 'Q':\n case 'D':\n case 'DDD':\n case 'd':\n return number + (number === 1 ? 'er' : 'e');\n\n // Words with feminine grammatical gender: semaine\n case 'w':\n case 'W':\n return number + (number === 1 ? 're' : 'e');\n }\n },\n });\n\n return frCa;\n\n})));\n","//! moment.js locale configuration\n//! locale : French (Switzerland) [fr-ch]\n//! author : Gaspard Bucher : https://github.com/gaspard\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var frCh = moment.defineLocale('fr-ch', {\n months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split(\n '_'\n ),\n monthsShort:\n 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),\n weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),\n weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Aujourd’hui à] LT',\n nextDay: '[Demain à] LT',\n nextWeek: 'dddd [à] LT',\n lastDay: '[Hier à] LT',\n lastWeek: 'dddd [dernier à] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'dans %s',\n past: 'il y a %s',\n s: 'quelques secondes',\n ss: '%d secondes',\n m: 'une minute',\n mm: '%d minutes',\n h: 'une heure',\n hh: '%d heures',\n d: 'un jour',\n dd: '%d jours',\n M: 'un mois',\n MM: '%d mois',\n y: 'un an',\n yy: '%d ans',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(er|e)/,\n ordinal: function (number, period) {\n switch (period) {\n // Words with masculine grammatical gender: mois, trimestre, jour\n default:\n case 'M':\n case 'Q':\n case 'D':\n case 'DDD':\n case 'd':\n return number + (number === 1 ? 'er' : 'e');\n\n // Words with feminine grammatical gender: semaine\n case 'w':\n case 'W':\n return number + (number === 1 ? 're' : 'e');\n }\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return frCh;\n\n})));\n","//! moment.js locale configuration\n//! locale : French [fr]\n//! author : John Fischer : https://github.com/jfroffice\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var monthsStrictRegex =\n /^(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i,\n monthsShortStrictRegex =\n /(janv\\.?|févr\\.?|mars|avr\\.?|mai|juin|juil\\.?|août|sept\\.?|oct\\.?|nov\\.?|déc\\.?)/i,\n monthsRegex =\n /(janv\\.?|févr\\.?|mars|avr\\.?|mai|juin|juil\\.?|août|sept\\.?|oct\\.?|nov\\.?|déc\\.?|janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i,\n monthsParse = [\n /^janv/i,\n /^févr/i,\n /^mars/i,\n /^avr/i,\n /^mai/i,\n /^juin/i,\n /^juil/i,\n /^août/i,\n /^sept/i,\n /^oct/i,\n /^nov/i,\n /^déc/i,\n ];\n\n var fr = moment.defineLocale('fr', {\n months: 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split(\n '_'\n ),\n monthsShort:\n 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split(\n '_'\n ),\n monthsRegex: monthsRegex,\n monthsShortRegex: monthsRegex,\n monthsStrictRegex: monthsStrictRegex,\n monthsShortStrictRegex: monthsShortStrictRegex,\n monthsParse: monthsParse,\n longMonthsParse: monthsParse,\n shortMonthsParse: monthsParse,\n weekdays: 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),\n weekdaysShort: 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),\n weekdaysMin: 'di_lu_ma_me_je_ve_sa'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Aujourd’hui à] LT',\n nextDay: '[Demain à] LT',\n nextWeek: 'dddd [à] LT',\n lastDay: '[Hier à] LT',\n lastWeek: 'dddd [dernier à] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'dans %s',\n past: 'il y a %s',\n s: 'quelques secondes',\n ss: '%d secondes',\n m: 'une minute',\n mm: '%d minutes',\n h: 'une heure',\n hh: '%d heures',\n d: 'un jour',\n dd: '%d jours',\n w: 'une semaine',\n ww: '%d semaines',\n M: 'un mois',\n MM: '%d mois',\n y: 'un an',\n yy: '%d ans',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(er|)/,\n ordinal: function (number, period) {\n switch (period) {\n // TODO: Return 'e' when day of month > 1. Move this case inside\n // block for masculine words below.\n // See https://github.com/moment/moment/issues/3375\n case 'D':\n return number + (number === 1 ? 'er' : '');\n\n // Words with masculine grammatical gender: mois, trimestre, jour\n default:\n case 'M':\n case 'Q':\n case 'DDD':\n case 'd':\n return number + (number === 1 ? 'er' : 'e');\n\n // Words with feminine grammatical gender: semaine\n case 'w':\n case 'W':\n return number + (number === 1 ? 're' : 'e');\n }\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return fr;\n\n})));\n","//! moment.js locale configuration\n//! locale : Frisian [fy]\n//! author : Robin van der Vliet : https://github.com/robin0van0der0v\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var monthsShortWithDots =\n 'jan._feb._mrt._apr._mai_jun._jul._aug._sep._okt._nov._des.'.split('_'),\n monthsShortWithoutDots =\n 'jan_feb_mrt_apr_mai_jun_jul_aug_sep_okt_nov_des'.split('_');\n\n var fy = moment.defineLocale('fy', {\n months: 'jannewaris_febrewaris_maart_april_maaie_juny_july_augustus_septimber_oktober_novimber_desimber'.split(\n '_'\n ),\n monthsShort: function (m, format) {\n if (!m) {\n return monthsShortWithDots;\n } else if (/-MMM-/.test(format)) {\n return monthsShortWithoutDots[m.month()];\n } else {\n return monthsShortWithDots[m.month()];\n }\n },\n monthsParseExact: true,\n weekdays: 'snein_moandei_tiisdei_woansdei_tongersdei_freed_sneon'.split(\n '_'\n ),\n weekdaysShort: 'si._mo._ti._wo._to._fr._so.'.split('_'),\n weekdaysMin: 'Si_Mo_Ti_Wo_To_Fr_So'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD-MM-YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[hjoed om] LT',\n nextDay: '[moarn om] LT',\n nextWeek: 'dddd [om] LT',\n lastDay: '[juster om] LT',\n lastWeek: '[ôfrûne] dddd [om] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'oer %s',\n past: '%s lyn',\n s: 'in pear sekonden',\n ss: '%d sekonden',\n m: 'ien minút',\n mm: '%d minuten',\n h: 'ien oere',\n hh: '%d oeren',\n d: 'ien dei',\n dd: '%d dagen',\n M: 'ien moanne',\n MM: '%d moannen',\n y: 'ien jier',\n yy: '%d jierren',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(ste|de)/,\n ordinal: function (number) {\n return (\n number +\n (number === 1 || number === 8 || number >= 20 ? 'ste' : 'de')\n );\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return fy;\n\n})));\n","//! moment.js locale configuration\n//! locale : Irish or Irish Gaelic [ga]\n//! author : André Silva : https://github.com/askpt\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var months = [\n 'Eanáir',\n 'Feabhra',\n 'Márta',\n 'Aibreán',\n 'Bealtaine',\n 'Meitheamh',\n 'Iúil',\n 'Lúnasa',\n 'Meán Fómhair',\n 'Deireadh Fómhair',\n 'Samhain',\n 'Nollaig',\n ],\n monthsShort = [\n 'Ean',\n 'Feabh',\n 'Márt',\n 'Aib',\n 'Beal',\n 'Meith',\n 'Iúil',\n 'Lún',\n 'M.F.',\n 'D.F.',\n 'Samh',\n 'Noll',\n ],\n weekdays = [\n 'Dé Domhnaigh',\n 'Dé Luain',\n 'Dé Máirt',\n 'Dé Céadaoin',\n 'Déardaoin',\n 'Dé hAoine',\n 'Dé Sathairn',\n ],\n weekdaysShort = ['Domh', 'Luan', 'Máirt', 'Céad', 'Déar', 'Aoine', 'Sath'],\n weekdaysMin = ['Do', 'Lu', 'Má', 'Cé', 'Dé', 'A', 'Sa'];\n\n var ga = moment.defineLocale('ga', {\n months: months,\n monthsShort: monthsShort,\n monthsParseExact: true,\n weekdays: weekdays,\n weekdaysShort: weekdaysShort,\n weekdaysMin: weekdaysMin,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Inniu ag] LT',\n nextDay: '[Amárach ag] LT',\n nextWeek: 'dddd [ag] LT',\n lastDay: '[Inné ag] LT',\n lastWeek: 'dddd [seo caite] [ag] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'i %s',\n past: '%s ó shin',\n s: 'cúpla soicind',\n ss: '%d soicind',\n m: 'nóiméad',\n mm: '%d nóiméad',\n h: 'uair an chloig',\n hh: '%d uair an chloig',\n d: 'lá',\n dd: '%d lá',\n M: 'mí',\n MM: '%d míonna',\n y: 'bliain',\n yy: '%d bliain',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(d|na|mh)/,\n ordinal: function (number) {\n var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh';\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return ga;\n\n})));\n","//! moment.js locale configuration\n//! locale : Scottish Gaelic [gd]\n//! author : Jon Ashdown : https://github.com/jonashdown\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var months = [\n 'Am Faoilleach',\n 'An Gearran',\n 'Am Màrt',\n 'An Giblean',\n 'An Cèitean',\n 'An t-Ògmhios',\n 'An t-Iuchar',\n 'An Lùnastal',\n 'An t-Sultain',\n 'An Dàmhair',\n 'An t-Samhain',\n 'An Dùbhlachd',\n ],\n monthsShort = [\n 'Faoi',\n 'Gear',\n 'Màrt',\n 'Gibl',\n 'Cèit',\n 'Ògmh',\n 'Iuch',\n 'Lùn',\n 'Sult',\n 'Dàmh',\n 'Samh',\n 'Dùbh',\n ],\n weekdays = [\n 'Didòmhnaich',\n 'Diluain',\n 'Dimàirt',\n 'Diciadain',\n 'Diardaoin',\n 'Dihaoine',\n 'Disathairne',\n ],\n weekdaysShort = ['Did', 'Dil', 'Dim', 'Dic', 'Dia', 'Dih', 'Dis'],\n weekdaysMin = ['Dò', 'Lu', 'Mà', 'Ci', 'Ar', 'Ha', 'Sa'];\n\n var gd = moment.defineLocale('gd', {\n months: months,\n monthsShort: monthsShort,\n monthsParseExact: true,\n weekdays: weekdays,\n weekdaysShort: weekdaysShort,\n weekdaysMin: weekdaysMin,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[An-diugh aig] LT',\n nextDay: '[A-màireach aig] LT',\n nextWeek: 'dddd [aig] LT',\n lastDay: '[An-dè aig] LT',\n lastWeek: 'dddd [seo chaidh] [aig] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'ann an %s',\n past: 'bho chionn %s',\n s: 'beagan diogan',\n ss: '%d diogan',\n m: 'mionaid',\n mm: '%d mionaidean',\n h: 'uair',\n hh: '%d uairean',\n d: 'latha',\n dd: '%d latha',\n M: 'mìos',\n MM: '%d mìosan',\n y: 'bliadhna',\n yy: '%d bliadhna',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(d|na|mh)/,\n ordinal: function (number) {\n var output = number === 1 ? 'd' : number % 10 === 2 ? 'na' : 'mh';\n return number + output;\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return gd;\n\n})));\n","//! moment.js locale configuration\n//! locale : Galician [gl]\n//! author : Juan G. Hurtado : https://github.com/juanghurtado\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var gl = moment.defineLocale('gl', {\n months: 'xaneiro_febreiro_marzo_abril_maio_xuño_xullo_agosto_setembro_outubro_novembro_decembro'.split(\n '_'\n ),\n monthsShort:\n 'xan._feb._mar._abr._mai._xuñ._xul._ago._set._out._nov._dec.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'domingo_luns_martes_mércores_xoves_venres_sábado'.split('_'),\n weekdaysShort: 'dom._lun._mar._mér._xov._ven._sáb.'.split('_'),\n weekdaysMin: 'do_lu_ma_mé_xo_ve_sá'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D [de] MMMM [de] YYYY',\n LLL: 'D [de] MMMM [de] YYYY H:mm',\n LLLL: 'dddd, D [de] MMMM [de] YYYY H:mm',\n },\n calendar: {\n sameDay: function () {\n return '[hoxe ' + (this.hours() !== 1 ? 'ás' : 'á') + '] LT';\n },\n nextDay: function () {\n return '[mañá ' + (this.hours() !== 1 ? 'ás' : 'á') + '] LT';\n },\n nextWeek: function () {\n return 'dddd [' + (this.hours() !== 1 ? 'ás' : 'a') + '] LT';\n },\n lastDay: function () {\n return '[onte ' + (this.hours() !== 1 ? 'á' : 'a') + '] LT';\n },\n lastWeek: function () {\n return (\n '[o] dddd [pasado ' + (this.hours() !== 1 ? 'ás' : 'a') + '] LT'\n );\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: function (str) {\n if (str.indexOf('un') === 0) {\n return 'n' + str;\n }\n return 'en ' + str;\n },\n past: 'hai %s',\n s: 'uns segundos',\n ss: '%d segundos',\n m: 'un minuto',\n mm: '%d minutos',\n h: 'unha hora',\n hh: '%d horas',\n d: 'un día',\n dd: '%d días',\n M: 'un mes',\n MM: '%d meses',\n y: 'un ano',\n yy: '%d anos',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}º/,\n ordinal: '%dº',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return gl;\n\n})));\n","//! moment.js locale configuration\n//! locale : Konkani Devanagari script [gom-deva]\n//! author : The Discoverer : https://github.com/WikiDiscoverer\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function processRelativeTime(number, withoutSuffix, key, isFuture) {\n var format = {\n s: ['थोडया सॅकंडांनी', 'थोडे सॅकंड'],\n ss: [number + ' सॅकंडांनी', number + ' सॅकंड'],\n m: ['एका मिणटान', 'एक मिनूट'],\n mm: [number + ' मिणटांनी', number + ' मिणटां'],\n h: ['एका वरान', 'एक वर'],\n hh: [number + ' वरांनी', number + ' वरां'],\n d: ['एका दिसान', 'एक दीस'],\n dd: [number + ' दिसांनी', number + ' दीस'],\n M: ['एका म्हयन्यान', 'एक म्हयनो'],\n MM: [number + ' म्हयन्यानी', number + ' म्हयने'],\n y: ['एका वर्सान', 'एक वर्स'],\n yy: [number + ' वर्सांनी', number + ' वर्सां'],\n };\n return isFuture ? format[key][0] : format[key][1];\n }\n\n var gomDeva = moment.defineLocale('gom-deva', {\n months: {\n standalone:\n 'जानेवारी_फेब्रुवारी_मार्च_एप्रील_मे_जून_जुलय_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split(\n '_'\n ),\n format: 'जानेवारीच्या_फेब्रुवारीच्या_मार्चाच्या_एप्रीलाच्या_मेयाच्या_जूनाच्या_जुलयाच्या_ऑगस्टाच्या_सप्टेंबराच्या_ऑक्टोबराच्या_नोव्हेंबराच्या_डिसेंबराच्या'.split(\n '_'\n ),\n isFormat: /MMMM(\\s)+D[oD]?/,\n },\n monthsShort:\n 'जाने._फेब्रु._मार्च_एप्री._मे_जून_जुल._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'आयतार_सोमार_मंगळार_बुधवार_बिरेस्तार_सुक्रार_शेनवार'.split('_'),\n weekdaysShort: 'आयत._सोम._मंगळ._बुध._ब्रेस्त._सुक्र._शेन.'.split('_'),\n weekdaysMin: 'आ_सो_मं_बु_ब्रे_सु_शे'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'A h:mm [वाजतां]',\n LTS: 'A h:mm:ss [वाजतां]',\n L: 'DD-MM-YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY A h:mm [वाजतां]',\n LLLL: 'dddd, MMMM Do, YYYY, A h:mm [वाजतां]',\n llll: 'ddd, D MMM YYYY, A h:mm [वाजतां]',\n },\n calendar: {\n sameDay: '[आयज] LT',\n nextDay: '[फाल्यां] LT',\n nextWeek: '[फुडलो] dddd[,] LT',\n lastDay: '[काल] LT',\n lastWeek: '[फाटलो] dddd[,] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s',\n past: '%s आदीं',\n s: processRelativeTime,\n ss: processRelativeTime,\n m: processRelativeTime,\n mm: processRelativeTime,\n h: processRelativeTime,\n hh: processRelativeTime,\n d: processRelativeTime,\n dd: processRelativeTime,\n M: processRelativeTime,\n MM: processRelativeTime,\n y: processRelativeTime,\n yy: processRelativeTime,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(वेर)/,\n ordinal: function (number, period) {\n switch (period) {\n // the ordinal 'वेर' only applies to day of the month\n case 'D':\n return number + 'वेर';\n default:\n case 'M':\n case 'Q':\n case 'DDD':\n case 'd':\n case 'w':\n case 'W':\n return number;\n }\n },\n week: {\n dow: 0, // Sunday is the first day of the week\n doy: 3, // The week that contains Jan 4th is the first week of the year (7 + 0 - 4)\n },\n meridiemParse: /राती|सकाळीं|दनपारां|सांजे/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (meridiem === 'राती') {\n return hour < 4 ? hour : hour + 12;\n } else if (meridiem === 'सकाळीं') {\n return hour;\n } else if (meridiem === 'दनपारां') {\n return hour > 12 ? hour : hour + 12;\n } else if (meridiem === 'सांजे') {\n return hour + 12;\n }\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'राती';\n } else if (hour < 12) {\n return 'सकाळीं';\n } else if (hour < 16) {\n return 'दनपारां';\n } else if (hour < 20) {\n return 'सांजे';\n } else {\n return 'राती';\n }\n },\n });\n\n return gomDeva;\n\n})));\n","//! moment.js locale configuration\n//! locale : Konkani Latin script [gom-latn]\n//! author : The Discoverer : https://github.com/WikiDiscoverer\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function processRelativeTime(number, withoutSuffix, key, isFuture) {\n var format = {\n s: ['thoddea sekondamni', 'thodde sekond'],\n ss: [number + ' sekondamni', number + ' sekond'],\n m: ['eka mintan', 'ek minut'],\n mm: [number + ' mintamni', number + ' mintam'],\n h: ['eka voran', 'ek vor'],\n hh: [number + ' voramni', number + ' voram'],\n d: ['eka disan', 'ek dis'],\n dd: [number + ' disamni', number + ' dis'],\n M: ['eka mhoinean', 'ek mhoino'],\n MM: [number + ' mhoineamni', number + ' mhoine'],\n y: ['eka vorsan', 'ek voros'],\n yy: [number + ' vorsamni', number + ' vorsam'],\n };\n return isFuture ? format[key][0] : format[key][1];\n }\n\n var gomLatn = moment.defineLocale('gom-latn', {\n months: {\n standalone:\n 'Janer_Febrer_Mars_Abril_Mai_Jun_Julai_Agost_Setembr_Otubr_Novembr_Dezembr'.split(\n '_'\n ),\n format: 'Janerachea_Febrerachea_Marsachea_Abrilachea_Maiachea_Junachea_Julaiachea_Agostachea_Setembrachea_Otubrachea_Novembrachea_Dezembrachea'.split(\n '_'\n ),\n isFormat: /MMMM(\\s)+D[oD]?/,\n },\n monthsShort:\n 'Jan._Feb._Mars_Abr._Mai_Jun_Jul._Ago._Set._Otu._Nov._Dez.'.split('_'),\n monthsParseExact: true,\n weekdays: \"Aitar_Somar_Mongllar_Budhvar_Birestar_Sukrar_Son'var\".split('_'),\n weekdaysShort: 'Ait._Som._Mon._Bud._Bre._Suk._Son.'.split('_'),\n weekdaysMin: 'Ai_Sm_Mo_Bu_Br_Su_Sn'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'A h:mm [vazta]',\n LTS: 'A h:mm:ss [vazta]',\n L: 'DD-MM-YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY A h:mm [vazta]',\n LLLL: 'dddd, MMMM Do, YYYY, A h:mm [vazta]',\n llll: 'ddd, D MMM YYYY, A h:mm [vazta]',\n },\n calendar: {\n sameDay: '[Aiz] LT',\n nextDay: '[Faleam] LT',\n nextWeek: '[Fuddlo] dddd[,] LT',\n lastDay: '[Kal] LT',\n lastWeek: '[Fattlo] dddd[,] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s',\n past: '%s adim',\n s: processRelativeTime,\n ss: processRelativeTime,\n m: processRelativeTime,\n mm: processRelativeTime,\n h: processRelativeTime,\n hh: processRelativeTime,\n d: processRelativeTime,\n dd: processRelativeTime,\n M: processRelativeTime,\n MM: processRelativeTime,\n y: processRelativeTime,\n yy: processRelativeTime,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(er)/,\n ordinal: function (number, period) {\n switch (period) {\n // the ordinal 'er' only applies to day of the month\n case 'D':\n return number + 'er';\n default:\n case 'M':\n case 'Q':\n case 'DDD':\n case 'd':\n case 'w':\n case 'W':\n return number;\n }\n },\n week: {\n dow: 0, // Sunday is the first day of the week\n doy: 3, // The week that contains Jan 4th is the first week of the year (7 + 0 - 4)\n },\n meridiemParse: /rati|sokallim|donparam|sanje/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (meridiem === 'rati') {\n return hour < 4 ? hour : hour + 12;\n } else if (meridiem === 'sokallim') {\n return hour;\n } else if (meridiem === 'donparam') {\n return hour > 12 ? hour : hour + 12;\n } else if (meridiem === 'sanje') {\n return hour + 12;\n }\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'rati';\n } else if (hour < 12) {\n return 'sokallim';\n } else if (hour < 16) {\n return 'donparam';\n } else if (hour < 20) {\n return 'sanje';\n } else {\n return 'rati';\n }\n },\n });\n\n return gomLatn;\n\n})));\n","//! moment.js locale configuration\n//! locale : Gujarati [gu]\n//! author : Kaushik Thanki : https://github.com/Kaushik1987\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '૧',\n 2: '૨',\n 3: '૩',\n 4: '૪',\n 5: '૫',\n 6: '૬',\n 7: '૭',\n 8: '૮',\n 9: '૯',\n 0: '૦',\n },\n numberMap = {\n '૧': '1',\n '૨': '2',\n '૩': '3',\n '૪': '4',\n '૫': '5',\n '૬': '6',\n '૭': '7',\n '૮': '8',\n '૯': '9',\n '૦': '0',\n };\n\n var gu = moment.defineLocale('gu', {\n months: 'જાન્યુઆરી_ફેબ્રુઆરી_માર્ચ_એપ્રિલ_મે_જૂન_જુલાઈ_ઑગસ્ટ_સપ્ટેમ્બર_ઑક્ટ્બર_નવેમ્બર_ડિસેમ્બર'.split(\n '_'\n ),\n monthsShort:\n 'જાન્યુ._ફેબ્રુ._માર્ચ_એપ્રિ._મે_જૂન_જુલા._ઑગ._સપ્ટે._ઑક્ટ્._નવે._ડિસે.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'રવિવાર_સોમવાર_મંગળવાર_બુધ્વાર_ગુરુવાર_શુક્રવાર_શનિવાર'.split(\n '_'\n ),\n weekdaysShort: 'રવિ_સોમ_મંગળ_બુધ્_ગુરુ_શુક્ર_શનિ'.split('_'),\n weekdaysMin: 'ર_સો_મં_બુ_ગુ_શુ_શ'.split('_'),\n longDateFormat: {\n LT: 'A h:mm વાગ્યે',\n LTS: 'A h:mm:ss વાગ્યે',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY, A h:mm વાગ્યે',\n LLLL: 'dddd, D MMMM YYYY, A h:mm વાગ્યે',\n },\n calendar: {\n sameDay: '[આજ] LT',\n nextDay: '[કાલે] LT',\n nextWeek: 'dddd, LT',\n lastDay: '[ગઇકાલે] LT',\n lastWeek: '[પાછલા] dddd, LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s મા',\n past: '%s પહેલા',\n s: 'અમુક પળો',\n ss: '%d સેકંડ',\n m: 'એક મિનિટ',\n mm: '%d મિનિટ',\n h: 'એક કલાક',\n hh: '%d કલાક',\n d: 'એક દિવસ',\n dd: '%d દિવસ',\n M: 'એક મહિનો',\n MM: '%d મહિનો',\n y: 'એક વર્ષ',\n yy: '%d વર્ષ',\n },\n preparse: function (string) {\n return string.replace(/[૧૨૩૪૫૬૭૮૯૦]/g, function (match) {\n return numberMap[match];\n });\n },\n postformat: function (string) {\n return string.replace(/\\d/g, function (match) {\n return symbolMap[match];\n });\n },\n // Gujarati notation for meridiems are quite fuzzy in practice. While there exists\n // a rigid notion of a 'Pahar' it is not used as rigidly in modern Gujarati.\n meridiemParse: /રાત|બપોર|સવાર|સાંજ/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (meridiem === 'રાત') {\n return hour < 4 ? hour : hour + 12;\n } else if (meridiem === 'સવાર') {\n return hour;\n } else if (meridiem === 'બપોર') {\n return hour >= 10 ? hour : hour + 12;\n } else if (meridiem === 'સાંજ') {\n return hour + 12;\n }\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'રાત';\n } else if (hour < 10) {\n return 'સવાર';\n } else if (hour < 17) {\n return 'બપોર';\n } else if (hour < 20) {\n return 'સાંજ';\n } else {\n return 'રાત';\n }\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return gu;\n\n})));\n","//! moment.js locale configuration\n//! locale : Hebrew [he]\n//! author : Tomer Cohen : https://github.com/tomer\n//! author : Moshe Simantov : https://github.com/DevelopmentIL\n//! author : Tal Ater : https://github.com/TalAter\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var he = moment.defineLocale('he', {\n months: 'ינואר_פברואר_מרץ_אפריל_מאי_יוני_יולי_אוגוסט_ספטמבר_אוקטובר_נובמבר_דצמבר'.split(\n '_'\n ),\n monthsShort:\n 'ינו׳_פבר׳_מרץ_אפר׳_מאי_יוני_יולי_אוג׳_ספט׳_אוק׳_נוב׳_דצמ׳'.split('_'),\n weekdays: 'ראשון_שני_שלישי_רביעי_חמישי_שישי_שבת'.split('_'),\n weekdaysShort: 'א׳_ב׳_ג׳_ד׳_ה׳_ו׳_ש׳'.split('_'),\n weekdaysMin: 'א_ב_ג_ד_ה_ו_ש'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D [ב]MMMM YYYY',\n LLL: 'D [ב]MMMM YYYY HH:mm',\n LLLL: 'dddd, D [ב]MMMM YYYY HH:mm',\n l: 'D/M/YYYY',\n ll: 'D MMM YYYY',\n lll: 'D MMM YYYY HH:mm',\n llll: 'ddd, D MMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[היום ב־]LT',\n nextDay: '[מחר ב־]LT',\n nextWeek: 'dddd [בשעה] LT',\n lastDay: '[אתמול ב־]LT',\n lastWeek: '[ביום] dddd [האחרון בשעה] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'בעוד %s',\n past: 'לפני %s',\n s: 'מספר שניות',\n ss: '%d שניות',\n m: 'דקה',\n mm: '%d דקות',\n h: 'שעה',\n hh: function (number) {\n if (number === 2) {\n return 'שעתיים';\n }\n return number + ' שעות';\n },\n d: 'יום',\n dd: function (number) {\n if (number === 2) {\n return 'יומיים';\n }\n return number + ' ימים';\n },\n M: 'חודש',\n MM: function (number) {\n if (number === 2) {\n return 'חודשיים';\n }\n return number + ' חודשים';\n },\n y: 'שנה',\n yy: function (number) {\n if (number === 2) {\n return 'שנתיים';\n } else if (number % 10 === 0 && number !== 10) {\n return number + ' שנה';\n }\n return number + ' שנים';\n },\n },\n meridiemParse:\n /אחה\"צ|לפנה\"צ|אחרי הצהריים|לפני הצהריים|לפנות בוקר|בבוקר|בערב/i,\n isPM: function (input) {\n return /^(אחה\"צ|אחרי הצהריים|בערב)$/.test(input);\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 5) {\n return 'לפנות בוקר';\n } else if (hour < 10) {\n return 'בבוקר';\n } else if (hour < 12) {\n return isLower ? 'לפנה\"צ' : 'לפני הצהריים';\n } else if (hour < 18) {\n return isLower ? 'אחה\"צ' : 'אחרי הצהריים';\n } else {\n return 'בערב';\n }\n },\n });\n\n return he;\n\n})));\n","//! moment.js locale configuration\n//! locale : Hindi [hi]\n//! author : Mayank Singhal : https://github.com/mayanksinghal\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '१',\n 2: '२',\n 3: '३',\n 4: '४',\n 5: '५',\n 6: '६',\n 7: '७',\n 8: '८',\n 9: '९',\n 0: '०',\n },\n numberMap = {\n '१': '1',\n '२': '2',\n '३': '3',\n '४': '4',\n '५': '5',\n '६': '6',\n '७': '7',\n '८': '8',\n '९': '9',\n '०': '0',\n },\n monthsParse = [\n /^जन/i,\n /^फ़र|फर/i,\n /^मार्च/i,\n /^अप्रै/i,\n /^मई/i,\n /^जून/i,\n /^जुल/i,\n /^अग/i,\n /^सितं|सित/i,\n /^अक्टू/i,\n /^नव|नवं/i,\n /^दिसं|दिस/i,\n ],\n shortMonthsParse = [\n /^जन/i,\n /^फ़र/i,\n /^मार्च/i,\n /^अप्रै/i,\n /^मई/i,\n /^जून/i,\n /^जुल/i,\n /^अग/i,\n /^सित/i,\n /^अक्टू/i,\n /^नव/i,\n /^दिस/i,\n ];\n\n var hi = moment.defineLocale('hi', {\n months: {\n format: 'जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर'.split(\n '_'\n ),\n standalone:\n 'जनवरी_फरवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितंबर_अक्टूबर_नवंबर_दिसंबर'.split(\n '_'\n ),\n },\n monthsShort:\n 'जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.'.split('_'),\n weekdays: 'रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'),\n weekdaysShort: 'रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि'.split('_'),\n weekdaysMin: 'र_सो_मं_बु_गु_शु_श'.split('_'),\n longDateFormat: {\n LT: 'A h:mm बजे',\n LTS: 'A h:mm:ss बजे',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY, A h:mm बजे',\n LLLL: 'dddd, D MMMM YYYY, A h:mm बजे',\n },\n\n monthsParse: monthsParse,\n longMonthsParse: monthsParse,\n shortMonthsParse: shortMonthsParse,\n\n monthsRegex:\n /^(जनवरी|जन\\.?|फ़रवरी|फरवरी|फ़र\\.?|मार्च?|अप्रैल|अप्रै\\.?|मई?|जून?|जुलाई|जुल\\.?|अगस्त|अग\\.?|सितम्बर|सितंबर|सित\\.?|अक्टूबर|अक्टू\\.?|नवम्बर|नवंबर|नव\\.?|दिसम्बर|दिसंबर|दिस\\.?)/i,\n\n monthsShortRegex:\n /^(जनवरी|जन\\.?|फ़रवरी|फरवरी|फ़र\\.?|मार्च?|अप्रैल|अप्रै\\.?|मई?|जून?|जुलाई|जुल\\.?|अगस्त|अग\\.?|सितम्बर|सितंबर|सित\\.?|अक्टूबर|अक्टू\\.?|नवम्बर|नवंबर|नव\\.?|दिसम्बर|दिसंबर|दिस\\.?)/i,\n\n monthsStrictRegex:\n /^(जनवरी?|फ़रवरी|फरवरी?|मार्च?|अप्रैल?|मई?|जून?|जुलाई?|अगस्त?|सितम्बर|सितंबर|सित?\\.?|अक्टूबर|अक्टू\\.?|नवम्बर|नवंबर?|दिसम्बर|दिसंबर?)/i,\n\n monthsShortStrictRegex:\n /^(जन\\.?|फ़र\\.?|मार्च?|अप्रै\\.?|मई?|जून?|जुल\\.?|अग\\.?|सित\\.?|अक्टू\\.?|नव\\.?|दिस\\.?)/i,\n\n calendar: {\n sameDay: '[आज] LT',\n nextDay: '[कल] LT',\n nextWeek: 'dddd, LT',\n lastDay: '[कल] LT',\n lastWeek: '[पिछले] dddd, LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s में',\n past: '%s पहले',\n s: 'कुछ ही क्षण',\n ss: '%d सेकंड',\n m: 'एक मिनट',\n mm: '%d मिनट',\n h: 'एक घंटा',\n hh: '%d घंटे',\n d: 'एक दिन',\n dd: '%d दिन',\n M: 'एक महीने',\n MM: '%d महीने',\n y: 'एक वर्ष',\n yy: '%d वर्ष',\n },\n preparse: function (string) {\n return string.replace(/[१२३४५६७८९०]/g, function (match) {\n return numberMap[match];\n });\n },\n postformat: function (string) {\n return string.replace(/\\d/g, function (match) {\n return symbolMap[match];\n });\n },\n // Hindi notation for meridiems are quite fuzzy in practice. While there exists\n // a rigid notion of a 'Pahar' it is not used as rigidly in modern Hindi.\n meridiemParse: /रात|सुबह|दोपहर|शाम/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (meridiem === 'रात') {\n return hour < 4 ? hour : hour + 12;\n } else if (meridiem === 'सुबह') {\n return hour;\n } else if (meridiem === 'दोपहर') {\n return hour >= 10 ? hour : hour + 12;\n } else if (meridiem === 'शाम') {\n return hour + 12;\n }\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'रात';\n } else if (hour < 10) {\n return 'सुबह';\n } else if (hour < 17) {\n return 'दोपहर';\n } else if (hour < 20) {\n return 'शाम';\n } else {\n return 'रात';\n }\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return hi;\n\n})));\n","//! moment.js locale configuration\n//! locale : Croatian [hr]\n//! author : Bojan Marković : https://github.com/bmarkovic\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function translate(number, withoutSuffix, key) {\n var result = number + ' ';\n switch (key) {\n case 'ss':\n if (number === 1) {\n result += 'sekunda';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sekunde';\n } else {\n result += 'sekundi';\n }\n return result;\n case 'm':\n return withoutSuffix ? 'jedna minuta' : 'jedne minute';\n case 'mm':\n if (number === 1) {\n result += 'minuta';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'minute';\n } else {\n result += 'minuta';\n }\n return result;\n case 'h':\n return withoutSuffix ? 'jedan sat' : 'jednog sata';\n case 'hh':\n if (number === 1) {\n result += 'sat';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'sata';\n } else {\n result += 'sati';\n }\n return result;\n case 'dd':\n if (number === 1) {\n result += 'dan';\n } else {\n result += 'dana';\n }\n return result;\n case 'MM':\n if (number === 1) {\n result += 'mjesec';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'mjeseca';\n } else {\n result += 'mjeseci';\n }\n return result;\n case 'yy':\n if (number === 1) {\n result += 'godina';\n } else if (number === 2 || number === 3 || number === 4) {\n result += 'godine';\n } else {\n result += 'godina';\n }\n return result;\n }\n }\n\n var hr = moment.defineLocale('hr', {\n months: {\n format: 'siječnja_veljače_ožujka_travnja_svibnja_lipnja_srpnja_kolovoza_rujna_listopada_studenoga_prosinca'.split(\n '_'\n ),\n standalone:\n 'siječanj_veljača_ožujak_travanj_svibanj_lipanj_srpanj_kolovoz_rujan_listopad_studeni_prosinac'.split(\n '_'\n ),\n },\n monthsShort:\n 'sij._velj._ožu._tra._svi._lip._srp._kol._ruj._lis._stu._pro.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'nedjelja_ponedjeljak_utorak_srijeda_četvrtak_petak_subota'.split(\n '_'\n ),\n weekdaysShort: 'ned._pon._uto._sri._čet._pet._sub.'.split('_'),\n weekdaysMin: 'ne_po_ut_sr_če_pe_su'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'Do MMMM YYYY',\n LLL: 'Do MMMM YYYY H:mm',\n LLLL: 'dddd, Do MMMM YYYY H:mm',\n },\n calendar: {\n sameDay: '[danas u] LT',\n nextDay: '[sutra u] LT',\n nextWeek: function () {\n switch (this.day()) {\n case 0:\n return '[u] [nedjelju] [u] LT';\n case 3:\n return '[u] [srijedu] [u] LT';\n case 6:\n return '[u] [subotu] [u] LT';\n case 1:\n case 2:\n case 4:\n case 5:\n return '[u] dddd [u] LT';\n }\n },\n lastDay: '[jučer u] LT',\n lastWeek: function () {\n switch (this.day()) {\n case 0:\n return '[prošlu] [nedjelju] [u] LT';\n case 3:\n return '[prošlu] [srijedu] [u] LT';\n case 6:\n return '[prošle] [subote] [u] LT';\n case 1:\n case 2:\n case 4:\n case 5:\n return '[prošli] dddd [u] LT';\n }\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'za %s',\n past: 'prije %s',\n s: 'par sekundi',\n ss: translate,\n m: translate,\n mm: translate,\n h: translate,\n hh: translate,\n d: 'dan',\n dd: translate,\n M: 'mjesec',\n MM: translate,\n y: 'godinu',\n yy: translate,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return hr;\n\n})));\n","//! moment.js locale configuration\n//! locale : Hungarian [hu]\n//! author : Adam Brunner : https://github.com/adambrunner\n//! author : Peter Viszt : https://github.com/passatgt\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var weekEndings =\n 'vasárnap hétfőn kedden szerdán csütörtökön pénteken szombaton'.split(' ');\n function translate(number, withoutSuffix, key, isFuture) {\n var num = number;\n switch (key) {\n case 's':\n return isFuture || withoutSuffix\n ? 'néhány másodperc'\n : 'néhány másodperce';\n case 'ss':\n return num + (isFuture || withoutSuffix)\n ? ' másodperc'\n : ' másodperce';\n case 'm':\n return 'egy' + (isFuture || withoutSuffix ? ' perc' : ' perce');\n case 'mm':\n return num + (isFuture || withoutSuffix ? ' perc' : ' perce');\n case 'h':\n return 'egy' + (isFuture || withoutSuffix ? ' óra' : ' órája');\n case 'hh':\n return num + (isFuture || withoutSuffix ? ' óra' : ' órája');\n case 'd':\n return 'egy' + (isFuture || withoutSuffix ? ' nap' : ' napja');\n case 'dd':\n return num + (isFuture || withoutSuffix ? ' nap' : ' napja');\n case 'M':\n return 'egy' + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');\n case 'MM':\n return num + (isFuture || withoutSuffix ? ' hónap' : ' hónapja');\n case 'y':\n return 'egy' + (isFuture || withoutSuffix ? ' év' : ' éve');\n case 'yy':\n return num + (isFuture || withoutSuffix ? ' év' : ' éve');\n }\n return '';\n }\n function week(isFuture) {\n return (\n (isFuture ? '' : '[múlt] ') +\n '[' +\n weekEndings[this.day()] +\n '] LT[-kor]'\n );\n }\n\n var hu = moment.defineLocale('hu', {\n months: 'január_február_március_április_május_június_július_augusztus_szeptember_október_november_december'.split(\n '_'\n ),\n monthsShort:\n 'jan._feb._márc._ápr._máj._jún._júl._aug._szept._okt._nov._dec.'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'vasárnap_hétfő_kedd_szerda_csütörtök_péntek_szombat'.split('_'),\n weekdaysShort: 'vas_hét_kedd_sze_csüt_pén_szo'.split('_'),\n weekdaysMin: 'v_h_k_sze_cs_p_szo'.split('_'),\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'YYYY.MM.DD.',\n LL: 'YYYY. MMMM D.',\n LLL: 'YYYY. MMMM D. H:mm',\n LLLL: 'YYYY. MMMM D., dddd H:mm',\n },\n meridiemParse: /de|du/i,\n isPM: function (input) {\n return input.charAt(1).toLowerCase() === 'u';\n },\n meridiem: function (hours, minutes, isLower) {\n if (hours < 12) {\n return isLower === true ? 'de' : 'DE';\n } else {\n return isLower === true ? 'du' : 'DU';\n }\n },\n calendar: {\n sameDay: '[ma] LT[-kor]',\n nextDay: '[holnap] LT[-kor]',\n nextWeek: function () {\n return week.call(this, true);\n },\n lastDay: '[tegnap] LT[-kor]',\n lastWeek: function () {\n return week.call(this, false);\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s múlva',\n past: '%s',\n s: translate,\n ss: translate,\n m: translate,\n mm: translate,\n h: translate,\n hh: translate,\n d: translate,\n dd: translate,\n M: translate,\n MM: translate,\n y: translate,\n yy: translate,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return hu;\n\n})));\n","//! moment.js locale configuration\n//! locale : Armenian [hy-am]\n//! author : Armendarabyan : https://github.com/armendarabyan\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var hyAm = moment.defineLocale('hy-am', {\n months: {\n format: 'հունվարի_փետրվարի_մարտի_ապրիլի_մայիսի_հունիսի_հուլիսի_օգոստոսի_սեպտեմբերի_հոկտեմբերի_նոյեմբերի_դեկտեմբերի'.split(\n '_'\n ),\n standalone:\n 'հունվար_փետրվար_մարտ_ապրիլ_մայիս_հունիս_հուլիս_օգոստոս_սեպտեմբեր_հոկտեմբեր_նոյեմբեր_դեկտեմբեր'.split(\n '_'\n ),\n },\n monthsShort: 'հնվ_փտր_մրտ_ապր_մյս_հնս_հլս_օգս_սպտ_հկտ_նմբ_դկտ'.split('_'),\n weekdays:\n 'կիրակի_երկուշաբթի_երեքշաբթի_չորեքշաբթի_հինգշաբթի_ուրբաթ_շաբաթ'.split(\n '_'\n ),\n weekdaysShort: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),\n weekdaysMin: 'կրկ_երկ_երք_չրք_հնգ_ուրբ_շբթ'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D MMMM YYYY թ.',\n LLL: 'D MMMM YYYY թ., HH:mm',\n LLLL: 'dddd, D MMMM YYYY թ., HH:mm',\n },\n calendar: {\n sameDay: '[այսօր] LT',\n nextDay: '[վաղը] LT',\n lastDay: '[երեկ] LT',\n nextWeek: function () {\n return 'dddd [օրը ժամը] LT';\n },\n lastWeek: function () {\n return '[անցած] dddd [օրը ժամը] LT';\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s հետո',\n past: '%s առաջ',\n s: 'մի քանի վայրկյան',\n ss: '%d վայրկյան',\n m: 'րոպե',\n mm: '%d րոպե',\n h: 'ժամ',\n hh: '%d ժամ',\n d: 'օր',\n dd: '%d օր',\n M: 'ամիս',\n MM: '%d ամիս',\n y: 'տարի',\n yy: '%d տարի',\n },\n meridiemParse: /գիշերվա|առավոտվա|ցերեկվա|երեկոյան/,\n isPM: function (input) {\n return /^(ցերեկվա|երեկոյան)$/.test(input);\n },\n meridiem: function (hour) {\n if (hour < 4) {\n return 'գիշերվա';\n } else if (hour < 12) {\n return 'առավոտվա';\n } else if (hour < 17) {\n return 'ցերեկվա';\n } else {\n return 'երեկոյան';\n }\n },\n dayOfMonthOrdinalParse: /\\d{1,2}|\\d{1,2}-(ին|րդ)/,\n ordinal: function (number, period) {\n switch (period) {\n case 'DDD':\n case 'w':\n case 'W':\n case 'DDDo':\n if (number === 1) {\n return number + '-ին';\n }\n return number + '-րդ';\n default:\n return number;\n }\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return hyAm;\n\n})));\n","//! moment.js locale configuration\n//! locale : Indonesian [id]\n//! author : Mohammad Satrio Utomo : https://github.com/tyok\n//! reference: http://id.wikisource.org/wiki/Pedoman_Umum_Ejaan_Bahasa_Indonesia_yang_Disempurnakan\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var id = moment.defineLocale('id', {\n months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_November_Desember'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Agt_Sep_Okt_Nov_Des'.split('_'),\n weekdays: 'Minggu_Senin_Selasa_Rabu_Kamis_Jumat_Sabtu'.split('_'),\n weekdaysShort: 'Min_Sen_Sel_Rab_Kam_Jum_Sab'.split('_'),\n weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sb'.split('_'),\n longDateFormat: {\n LT: 'HH.mm',\n LTS: 'HH.mm.ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY [pukul] HH.mm',\n LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm',\n },\n meridiemParse: /pagi|siang|sore|malam/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (meridiem === 'pagi') {\n return hour;\n } else if (meridiem === 'siang') {\n return hour >= 11 ? hour : hour + 12;\n } else if (meridiem === 'sore' || meridiem === 'malam') {\n return hour + 12;\n }\n },\n meridiem: function (hours, minutes, isLower) {\n if (hours < 11) {\n return 'pagi';\n } else if (hours < 15) {\n return 'siang';\n } else if (hours < 19) {\n return 'sore';\n } else {\n return 'malam';\n }\n },\n calendar: {\n sameDay: '[Hari ini pukul] LT',\n nextDay: '[Besok pukul] LT',\n nextWeek: 'dddd [pukul] LT',\n lastDay: '[Kemarin pukul] LT',\n lastWeek: 'dddd [lalu pukul] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'dalam %s',\n past: '%s yang lalu',\n s: 'beberapa detik',\n ss: '%d detik',\n m: 'semenit',\n mm: '%d menit',\n h: 'sejam',\n hh: '%d jam',\n d: 'sehari',\n dd: '%d hari',\n M: 'sebulan',\n MM: '%d bulan',\n y: 'setahun',\n yy: '%d tahun',\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return id;\n\n})));\n","//! moment.js locale configuration\n//! locale : Icelandic [is]\n//! author : Hinrik Örn Sigurðsson : https://github.com/hinrik\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n function plural(n) {\n if (n % 100 === 11) {\n return true;\n } else if (n % 10 === 1) {\n return false;\n }\n return true;\n }\n function translate(number, withoutSuffix, key, isFuture) {\n var result = number + ' ';\n switch (key) {\n case 's':\n return withoutSuffix || isFuture\n ? 'nokkrar sekúndur'\n : 'nokkrum sekúndum';\n case 'ss':\n if (plural(number)) {\n return (\n result +\n (withoutSuffix || isFuture ? 'sekúndur' : 'sekúndum')\n );\n }\n return result + 'sekúnda';\n case 'm':\n return withoutSuffix ? 'mínúta' : 'mínútu';\n case 'mm':\n if (plural(number)) {\n return (\n result + (withoutSuffix || isFuture ? 'mínútur' : 'mínútum')\n );\n } else if (withoutSuffix) {\n return result + 'mínúta';\n }\n return result + 'mínútu';\n case 'hh':\n if (plural(number)) {\n return (\n result +\n (withoutSuffix || isFuture\n ? 'klukkustundir'\n : 'klukkustundum')\n );\n }\n return result + 'klukkustund';\n case 'd':\n if (withoutSuffix) {\n return 'dagur';\n }\n return isFuture ? 'dag' : 'degi';\n case 'dd':\n if (plural(number)) {\n if (withoutSuffix) {\n return result + 'dagar';\n }\n return result + (isFuture ? 'daga' : 'dögum');\n } else if (withoutSuffix) {\n return result + 'dagur';\n }\n return result + (isFuture ? 'dag' : 'degi');\n case 'M':\n if (withoutSuffix) {\n return 'mánuður';\n }\n return isFuture ? 'mánuð' : 'mánuði';\n case 'MM':\n if (plural(number)) {\n if (withoutSuffix) {\n return result + 'mánuðir';\n }\n return result + (isFuture ? 'mánuði' : 'mánuðum');\n } else if (withoutSuffix) {\n return result + 'mánuður';\n }\n return result + (isFuture ? 'mánuð' : 'mánuði');\n case 'y':\n return withoutSuffix || isFuture ? 'ár' : 'ári';\n case 'yy':\n if (plural(number)) {\n return result + (withoutSuffix || isFuture ? 'ár' : 'árum');\n }\n return result + (withoutSuffix || isFuture ? 'ár' : 'ári');\n }\n }\n\n var is = moment.defineLocale('is', {\n months: 'janúar_febrúar_mars_apríl_maí_júní_júlí_ágúst_september_október_nóvember_desember'.split(\n '_'\n ),\n monthsShort: 'jan_feb_mar_apr_maí_jún_júl_ágú_sep_okt_nóv_des'.split('_'),\n weekdays:\n 'sunnudagur_mánudagur_þriðjudagur_miðvikudagur_fimmtudagur_föstudagur_laugardagur'.split(\n '_'\n ),\n weekdaysShort: 'sun_mán_þri_mið_fim_fös_lau'.split('_'),\n weekdaysMin: 'Su_Má_Þr_Mi_Fi_Fö_La'.split('_'),\n longDateFormat: {\n LT: 'H:mm',\n LTS: 'H:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D. MMMM YYYY',\n LLL: 'D. MMMM YYYY [kl.] H:mm',\n LLLL: 'dddd, D. MMMM YYYY [kl.] H:mm',\n },\n calendar: {\n sameDay: '[í dag kl.] LT',\n nextDay: '[á morgun kl.] LT',\n nextWeek: 'dddd [kl.] LT',\n lastDay: '[í gær kl.] LT',\n lastWeek: '[síðasta] dddd [kl.] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'eftir %s',\n past: 'fyrir %s síðan',\n s: translate,\n ss: translate,\n m: translate,\n mm: translate,\n h: 'klukkustund',\n hh: translate,\n d: translate,\n dd: translate,\n M: translate,\n MM: translate,\n y: translate,\n yy: translate,\n },\n dayOfMonthOrdinalParse: /\\d{1,2}\\./,\n ordinal: '%d.',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return is;\n\n})));\n","//! moment.js locale configuration\n//! locale : Italian (Switzerland) [it-ch]\n//! author : xfh : https://github.com/xfh\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var itCh = moment.defineLocale('it-ch', {\n months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split(\n '_'\n ),\n monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),\n weekdays: 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split(\n '_'\n ),\n weekdaysShort: 'dom_lun_mar_mer_gio_ven_sab'.split('_'),\n weekdaysMin: 'do_lu_ma_me_gi_ve_sa'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Oggi alle] LT',\n nextDay: '[Domani alle] LT',\n nextWeek: 'dddd [alle] LT',\n lastDay: '[Ieri alle] LT',\n lastWeek: function () {\n switch (this.day()) {\n case 0:\n return '[la scorsa] dddd [alle] LT';\n default:\n return '[lo scorso] dddd [alle] LT';\n }\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: function (s) {\n return (/^[0-9].+$/.test(s) ? 'tra' : 'in') + ' ' + s;\n },\n past: '%s fa',\n s: 'alcuni secondi',\n ss: '%d secondi',\n m: 'un minuto',\n mm: '%d minuti',\n h: \"un'ora\",\n hh: '%d ore',\n d: 'un giorno',\n dd: '%d giorni',\n M: 'un mese',\n MM: '%d mesi',\n y: 'un anno',\n yy: '%d anni',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}º/,\n ordinal: '%dº',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return itCh;\n\n})));\n","//! moment.js locale configuration\n//! locale : Italian [it]\n//! author : Lorenzo : https://github.com/aliem\n//! author: Mattia Larentis: https://github.com/nostalgiaz\n//! author: Marco : https://github.com/Manfre98\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var it = moment.defineLocale('it', {\n months: 'gennaio_febbraio_marzo_aprile_maggio_giugno_luglio_agosto_settembre_ottobre_novembre_dicembre'.split(\n '_'\n ),\n monthsShort: 'gen_feb_mar_apr_mag_giu_lug_ago_set_ott_nov_dic'.split('_'),\n weekdays: 'domenica_lunedì_martedì_mercoledì_giovedì_venerdì_sabato'.split(\n '_'\n ),\n weekdaysShort: 'dom_lun_mar_mer_gio_ven_sab'.split('_'),\n weekdaysMin: 'do_lu_ma_me_gi_ve_sa'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: function () {\n return (\n '[Oggi a' +\n (this.hours() > 1 ? 'lle ' : this.hours() === 0 ? ' ' : \"ll'\") +\n ']LT'\n );\n },\n nextDay: function () {\n return (\n '[Domani a' +\n (this.hours() > 1 ? 'lle ' : this.hours() === 0 ? ' ' : \"ll'\") +\n ']LT'\n );\n },\n nextWeek: function () {\n return (\n 'dddd [a' +\n (this.hours() > 1 ? 'lle ' : this.hours() === 0 ? ' ' : \"ll'\") +\n ']LT'\n );\n },\n lastDay: function () {\n return (\n '[Ieri a' +\n (this.hours() > 1 ? 'lle ' : this.hours() === 0 ? ' ' : \"ll'\") +\n ']LT'\n );\n },\n lastWeek: function () {\n switch (this.day()) {\n case 0:\n return (\n '[La scorsa] dddd [a' +\n (this.hours() > 1\n ? 'lle '\n : this.hours() === 0\n ? ' '\n : \"ll'\") +\n ']LT'\n );\n default:\n return (\n '[Lo scorso] dddd [a' +\n (this.hours() > 1\n ? 'lle '\n : this.hours() === 0\n ? ' '\n : \"ll'\") +\n ']LT'\n );\n }\n },\n sameElse: 'L',\n },\n relativeTime: {\n future: 'tra %s',\n past: '%s fa',\n s: 'alcuni secondi',\n ss: '%d secondi',\n m: 'un minuto',\n mm: '%d minuti',\n h: \"un'ora\",\n hh: '%d ore',\n d: 'un giorno',\n dd: '%d giorni',\n w: 'una settimana',\n ww: '%d settimane',\n M: 'un mese',\n MM: '%d mesi',\n y: 'un anno',\n yy: '%d anni',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}º/,\n ordinal: '%dº',\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return it;\n\n})));\n","//! moment.js locale configuration\n//! locale : Japanese [ja]\n//! author : LI Long : https://github.com/baryon\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var ja = moment.defineLocale('ja', {\n eras: [\n {\n since: '2019-05-01',\n offset: 1,\n name: '令和',\n narrow: '㋿',\n abbr: 'R',\n },\n {\n since: '1989-01-08',\n until: '2019-04-30',\n offset: 1,\n name: '平成',\n narrow: '㍻',\n abbr: 'H',\n },\n {\n since: '1926-12-25',\n until: '1989-01-07',\n offset: 1,\n name: '昭和',\n narrow: '㍼',\n abbr: 'S',\n },\n {\n since: '1912-07-30',\n until: '1926-12-24',\n offset: 1,\n name: '大正',\n narrow: '㍽',\n abbr: 'T',\n },\n {\n since: '1873-01-01',\n until: '1912-07-29',\n offset: 6,\n name: '明治',\n narrow: '㍾',\n abbr: 'M',\n },\n {\n since: '0001-01-01',\n until: '1873-12-31',\n offset: 1,\n name: '西暦',\n narrow: 'AD',\n abbr: 'AD',\n },\n {\n since: '0000-12-31',\n until: -Infinity,\n offset: 1,\n name: '紀元前',\n narrow: 'BC',\n abbr: 'BC',\n },\n ],\n eraYearOrdinalRegex: /(元|\\d+)年/,\n eraYearOrdinalParse: function (input, match) {\n return match[1] === '元' ? 1 : parseInt(match[1] || input, 10);\n },\n months: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split('_'),\n monthsShort: '1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月'.split(\n '_'\n ),\n weekdays: '日曜日_月曜日_火曜日_水曜日_木曜日_金曜日_土曜日'.split('_'),\n weekdaysShort: '日_月_火_水_木_金_土'.split('_'),\n weekdaysMin: '日_月_火_水_木_金_土'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'YYYY/MM/DD',\n LL: 'YYYY年M月D日',\n LLL: 'YYYY年M月D日 HH:mm',\n LLLL: 'YYYY年M月D日 dddd HH:mm',\n l: 'YYYY/MM/DD',\n ll: 'YYYY年M月D日',\n lll: 'YYYY年M月D日 HH:mm',\n llll: 'YYYY年M月D日(ddd) HH:mm',\n },\n meridiemParse: /午前|午後/i,\n isPM: function (input) {\n return input === '午後';\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return '午前';\n } else {\n return '午後';\n }\n },\n calendar: {\n sameDay: '[今日] LT',\n nextDay: '[明日] LT',\n nextWeek: function (now) {\n if (now.week() !== this.week()) {\n return '[来週]dddd LT';\n } else {\n return 'dddd LT';\n }\n },\n lastDay: '[昨日] LT',\n lastWeek: function (now) {\n if (this.week() !== now.week()) {\n return '[先週]dddd LT';\n } else {\n return 'dddd LT';\n }\n },\n sameElse: 'L',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}日/,\n ordinal: function (number, period) {\n switch (period) {\n case 'y':\n return number === 1 ? '元年' : number + '年';\n case 'd':\n case 'D':\n case 'DDD':\n return number + '日';\n default:\n return number;\n }\n },\n relativeTime: {\n future: '%s後',\n past: '%s前',\n s: '数秒',\n ss: '%d秒',\n m: '1分',\n mm: '%d分',\n h: '1時間',\n hh: '%d時間',\n d: '1日',\n dd: '%d日',\n M: '1ヶ月',\n MM: '%dヶ月',\n y: '1年',\n yy: '%d年',\n },\n });\n\n return ja;\n\n})));\n","//! moment.js locale configuration\n//! locale : Javanese [jv]\n//! author : Rony Lantip : https://github.com/lantip\n//! reference: http://jv.wikipedia.org/wiki/Basa_Jawa\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var jv = moment.defineLocale('jv', {\n months: 'Januari_Februari_Maret_April_Mei_Juni_Juli_Agustus_September_Oktober_Nopember_Desember'.split(\n '_'\n ),\n monthsShort: 'Jan_Feb_Mar_Apr_Mei_Jun_Jul_Ags_Sep_Okt_Nop_Des'.split('_'),\n weekdays: 'Minggu_Senen_Seloso_Rebu_Kemis_Jemuwah_Septu'.split('_'),\n weekdaysShort: 'Min_Sen_Sel_Reb_Kem_Jem_Sep'.split('_'),\n weekdaysMin: 'Mg_Sn_Sl_Rb_Km_Jm_Sp'.split('_'),\n longDateFormat: {\n LT: 'HH.mm',\n LTS: 'HH.mm.ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY [pukul] HH.mm',\n LLLL: 'dddd, D MMMM YYYY [pukul] HH.mm',\n },\n meridiemParse: /enjing|siyang|sonten|ndalu/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (meridiem === 'enjing') {\n return hour;\n } else if (meridiem === 'siyang') {\n return hour >= 11 ? hour : hour + 12;\n } else if (meridiem === 'sonten' || meridiem === 'ndalu') {\n return hour + 12;\n }\n },\n meridiem: function (hours, minutes, isLower) {\n if (hours < 11) {\n return 'enjing';\n } else if (hours < 15) {\n return 'siyang';\n } else if (hours < 19) {\n return 'sonten';\n } else {\n return 'ndalu';\n }\n },\n calendar: {\n sameDay: '[Dinten puniko pukul] LT',\n nextDay: '[Mbenjang pukul] LT',\n nextWeek: 'dddd [pukul] LT',\n lastDay: '[Kala wingi pukul] LT',\n lastWeek: 'dddd [kepengker pukul] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: 'wonten ing %s',\n past: '%s ingkang kepengker',\n s: 'sawetawis detik',\n ss: '%d detik',\n m: 'setunggal menit',\n mm: '%d menit',\n h: 'setunggal jam',\n hh: '%d jam',\n d: 'sedinten',\n dd: '%d dinten',\n M: 'sewulan',\n MM: '%d wulan',\n y: 'setaun',\n yy: '%d taun',\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return jv;\n\n})));\n","//! moment.js locale configuration\n//! locale : Georgian [ka]\n//! author : Irakli Janiashvili : https://github.com/IrakliJani\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var ka = moment.defineLocale('ka', {\n months: 'იანვარი_თებერვალი_მარტი_აპრილი_მაისი_ივნისი_ივლისი_აგვისტო_სექტემბერი_ოქტომბერი_ნოემბერი_დეკემბერი'.split(\n '_'\n ),\n monthsShort: 'იან_თებ_მარ_აპრ_მაი_ივნ_ივლ_აგვ_სექ_ოქტ_ნოე_დეკ'.split('_'),\n weekdays: {\n standalone:\n 'კვირა_ორშაბათი_სამშაბათი_ოთხშაბათი_ხუთშაბათი_პარასკევი_შაბათი'.split(\n '_'\n ),\n format: 'კვირას_ორშაბათს_სამშაბათს_ოთხშაბათს_ხუთშაბათს_პარასკევს_შაბათს'.split(\n '_'\n ),\n isFormat: /(წინა|შემდეგ)/,\n },\n weekdaysShort: 'კვი_ორშ_სამ_ოთხ_ხუთ_პარ_შაბ'.split('_'),\n weekdaysMin: 'კვ_ორ_სა_ოთ_ხუ_პა_შა'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[დღეს] LT[-ზე]',\n nextDay: '[ხვალ] LT[-ზე]',\n lastDay: '[გუშინ] LT[-ზე]',\n nextWeek: '[შემდეგ] dddd LT[-ზე]',\n lastWeek: '[წინა] dddd LT-ზე',\n sameElse: 'L',\n },\n relativeTime: {\n future: function (s) {\n return s.replace(\n /(წამ|წუთ|საათ|წელ|დღ|თვ)(ი|ე)/,\n function ($0, $1, $2) {\n return $2 === 'ი' ? $1 + 'ში' : $1 + $2 + 'ში';\n }\n );\n },\n past: function (s) {\n if (/(წამი|წუთი|საათი|დღე|თვე)/.test(s)) {\n return s.replace(/(ი|ე)$/, 'ის წინ');\n }\n if (/წელი/.test(s)) {\n return s.replace(/წელი$/, 'წლის წინ');\n }\n return s;\n },\n s: 'რამდენიმე წამი',\n ss: '%d წამი',\n m: 'წუთი',\n mm: '%d წუთი',\n h: 'საათი',\n hh: '%d საათი',\n d: 'დღე',\n dd: '%d დღე',\n M: 'თვე',\n MM: '%d თვე',\n y: 'წელი',\n yy: '%d წელი',\n },\n dayOfMonthOrdinalParse: /0|1-ლი|მე-\\d{1,2}|\\d{1,2}-ე/,\n ordinal: function (number) {\n if (number === 0) {\n return number;\n }\n if (number === 1) {\n return number + '-ლი';\n }\n if (\n number < 20 ||\n (number <= 100 && number % 20 === 0) ||\n number % 100 === 0\n ) {\n return 'მე-' + number;\n }\n return number + '-ე';\n },\n week: {\n dow: 1,\n doy: 7,\n },\n });\n\n return ka;\n\n})));\n","//! moment.js locale configuration\n//! locale : Kazakh [kk]\n//! authors : Nurlan Rakhimzhanov : https://github.com/nurlan\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var suffixes = {\n 0: '-ші',\n 1: '-ші',\n 2: '-ші',\n 3: '-ші',\n 4: '-ші',\n 5: '-ші',\n 6: '-шы',\n 7: '-ші',\n 8: '-ші',\n 9: '-шы',\n 10: '-шы',\n 20: '-шы',\n 30: '-шы',\n 40: '-шы',\n 50: '-ші',\n 60: '-шы',\n 70: '-ші',\n 80: '-ші',\n 90: '-шы',\n 100: '-ші',\n };\n\n var kk = moment.defineLocale('kk', {\n months: 'қаңтар_ақпан_наурыз_сәуір_мамыр_маусым_шілде_тамыз_қыркүйек_қазан_қараша_желтоқсан'.split(\n '_'\n ),\n monthsShort: 'қаң_ақп_нау_сәу_мам_мау_шіл_там_қыр_қаз_қар_жел'.split('_'),\n weekdays: 'жексенбі_дүйсенбі_сейсенбі_сәрсенбі_бейсенбі_жұма_сенбі'.split(\n '_'\n ),\n weekdaysShort: 'жек_дүй_сей_сәр_бей_жұм_сен'.split('_'),\n weekdaysMin: 'жк_дй_сй_ср_бй_жм_сн'.split('_'),\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD.MM.YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n calendar: {\n sameDay: '[Бүгін сағат] LT',\n nextDay: '[Ертең сағат] LT',\n nextWeek: 'dddd [сағат] LT',\n lastDay: '[Кеше сағат] LT',\n lastWeek: '[Өткен аптаның] dddd [сағат] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s ішінде',\n past: '%s бұрын',\n s: 'бірнеше секунд',\n ss: '%d секунд',\n m: 'бір минут',\n mm: '%d минут',\n h: 'бір сағат',\n hh: '%d сағат',\n d: 'бір күн',\n dd: '%d күн',\n M: 'бір ай',\n MM: '%d ай',\n y: 'бір жыл',\n yy: '%d жыл',\n },\n dayOfMonthOrdinalParse: /\\d{1,2}-(ші|шы)/,\n ordinal: function (number) {\n var a = number % 10,\n b = number >= 100 ? 100 : null;\n return number + (suffixes[number] || suffixes[a] || suffixes[b]);\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 7, // The week that contains Jan 7th is the first week of the year.\n },\n });\n\n return kk;\n\n})));\n","//! moment.js locale configuration\n//! locale : Cambodian [km]\n//! author : Kruy Vanna : https://github.com/kruyvanna\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '១',\n 2: '២',\n 3: '៣',\n 4: '៤',\n 5: '៥',\n 6: '៦',\n 7: '៧',\n 8: '៨',\n 9: '៩',\n 0: '០',\n },\n numberMap = {\n '១': '1',\n '២': '2',\n '៣': '3',\n '៤': '4',\n '៥': '5',\n '៦': '6',\n '៧': '7',\n '៨': '8',\n '៩': '9',\n '០': '0',\n };\n\n var km = moment.defineLocale('km', {\n months: 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split(\n '_'\n ),\n monthsShort:\n 'មករា_កុម្ភៈ_មីនា_មេសា_ឧសភា_មិថុនា_កក្កដា_សីហា_កញ្ញា_តុលា_វិច្ឆិកា_ធ្នូ'.split(\n '_'\n ),\n weekdays: 'អាទិត្យ_ច័ន្ទ_អង្គារ_ពុធ_ព្រហស្បតិ៍_សុក្រ_សៅរ៍'.split('_'),\n weekdaysShort: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'),\n weekdaysMin: 'អា_ច_អ_ព_ព្រ_សុ_ស'.split('_'),\n weekdaysParseExact: true,\n longDateFormat: {\n LT: 'HH:mm',\n LTS: 'HH:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY HH:mm',\n LLLL: 'dddd, D MMMM YYYY HH:mm',\n },\n meridiemParse: /ព្រឹក|ល្ងាច/,\n isPM: function (input) {\n return input === 'ល្ងាច';\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 12) {\n return 'ព្រឹក';\n } else {\n return 'ល្ងាច';\n }\n },\n calendar: {\n sameDay: '[ថ្ងៃនេះ ម៉ោង] LT',\n nextDay: '[ស្អែក ម៉ោង] LT',\n nextWeek: 'dddd [ម៉ោង] LT',\n lastDay: '[ម្សិលមិញ ម៉ោង] LT',\n lastWeek: 'dddd [សប្តាហ៍មុន] [ម៉ោង] LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%sទៀត',\n past: '%sមុន',\n s: 'ប៉ុន្មានវិនាទី',\n ss: '%d វិនាទី',\n m: 'មួយនាទី',\n mm: '%d នាទី',\n h: 'មួយម៉ោង',\n hh: '%d ម៉ោង',\n d: 'មួយថ្ងៃ',\n dd: '%d ថ្ងៃ',\n M: 'មួយខែ',\n MM: '%d ខែ',\n y: 'មួយឆ្នាំ',\n yy: '%d ឆ្នាំ',\n },\n dayOfMonthOrdinalParse: /ទី\\d{1,2}/,\n ordinal: 'ទី%d',\n preparse: function (string) {\n return string.replace(/[១២៣៤៥៦៧៨៩០]/g, function (match) {\n return numberMap[match];\n });\n },\n postformat: function (string) {\n return string.replace(/\\d/g, function (match) {\n return symbolMap[match];\n });\n },\n week: {\n dow: 1, // Monday is the first day of the week.\n doy: 4, // The week that contains Jan 4th is the first week of the year.\n },\n });\n\n return km;\n\n})));\n","//! moment.js locale configuration\n//! locale : Kannada [kn]\n//! author : Rajeev Naik : https://github.com/rajeevnaikte\n\n;(function (global, factory) {\n typeof exports === 'object' && typeof module !== 'undefined'\n && typeof require === 'function' ? factory(require('../moment')) :\n typeof define === 'function' && define.amd ? define(['../moment'], factory) :\n factory(global.moment)\n}(this, (function (moment) { 'use strict';\n\n //! moment.js locale configuration\n\n var symbolMap = {\n 1: '೧',\n 2: '೨',\n 3: '೩',\n 4: '೪',\n 5: '೫',\n 6: '೬',\n 7: '೭',\n 8: '೮',\n 9: '೯',\n 0: '೦',\n },\n numberMap = {\n '೧': '1',\n '೨': '2',\n '೩': '3',\n '೪': '4',\n '೫': '5',\n '೬': '6',\n '೭': '7',\n '೮': '8',\n '೯': '9',\n '೦': '0',\n };\n\n var kn = moment.defineLocale('kn', {\n months: 'ಜನವರಿ_ಫೆಬ್ರವರಿ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂಬರ್_ಅಕ್ಟೋಬರ್_ನವೆಂಬರ್_ಡಿಸೆಂಬರ್'.split(\n '_'\n ),\n monthsShort:\n 'ಜನ_ಫೆಬ್ರ_ಮಾರ್ಚ್_ಏಪ್ರಿಲ್_ಮೇ_ಜೂನ್_ಜುಲೈ_ಆಗಸ್ಟ್_ಸೆಪ್ಟೆಂ_ಅಕ್ಟೋ_ನವೆಂ_ಡಿಸೆಂ'.split(\n '_'\n ),\n monthsParseExact: true,\n weekdays: 'ಭಾನುವಾರ_ಸೋಮವಾರ_ಮಂಗಳವಾರ_ಬುಧವಾರ_ಗುರುವಾರ_ಶುಕ್ರವಾರ_ಶನಿವಾರ'.split(\n '_'\n ),\n weekdaysShort: 'ಭಾನು_ಸೋಮ_ಮಂಗಳ_ಬುಧ_ಗುರು_ಶುಕ್ರ_ಶನಿ'.split('_'),\n weekdaysMin: 'ಭಾ_ಸೋ_ಮಂ_ಬು_ಗು_ಶು_ಶ'.split('_'),\n longDateFormat: {\n LT: 'A h:mm',\n LTS: 'A h:mm:ss',\n L: 'DD/MM/YYYY',\n LL: 'D MMMM YYYY',\n LLL: 'D MMMM YYYY, A h:mm',\n LLLL: 'dddd, D MMMM YYYY, A h:mm',\n },\n calendar: {\n sameDay: '[ಇಂದು] LT',\n nextDay: '[ನಾಳೆ] LT',\n nextWeek: 'dddd, LT',\n lastDay: '[ನಿನ್ನೆ] LT',\n lastWeek: '[ಕೊನೆಯ] dddd, LT',\n sameElse: 'L',\n },\n relativeTime: {\n future: '%s ನಂತರ',\n past: '%s ಹಿಂದೆ',\n s: 'ಕೆಲವು ಕ್ಷಣಗಳು',\n ss: '%d ಸೆಕೆಂಡುಗಳು',\n m: 'ಒಂದು ನಿಮಿಷ',\n mm: '%d ನಿಮಿಷ',\n h: 'ಒಂದು ಗಂಟೆ',\n hh: '%d ಗಂಟೆ',\n d: 'ಒಂದು ದಿನ',\n dd: '%d ದಿನ',\n M: 'ಒಂದು ತಿಂಗಳು',\n MM: '%d ತಿಂಗಳು',\n y: 'ಒಂದು ವರ್ಷ',\n yy: '%d ವರ್ಷ',\n },\n preparse: function (string) {\n return string.replace(/[೧೨೩೪೫೬೭೮೯೦]/g, function (match) {\n return numberMap[match];\n });\n },\n postformat: function (string) {\n return string.replace(/\\d/g, function (match) {\n return symbolMap[match];\n });\n },\n meridiemParse: /ರಾತ್ರಿ|ಬೆಳಿಗ್ಗೆ|ಮಧ್ಯಾಹ್ನ|ಸಂಜೆ/,\n meridiemHour: function (hour, meridiem) {\n if (hour === 12) {\n hour = 0;\n }\n if (meridiem === 'ರಾತ್ರಿ') {\n return hour < 4 ? hour : hour + 12;\n } else if (meridiem === 'ಬೆಳಿಗ್ಗೆ') {\n return hour;\n } else if (meridiem === 'ಮಧ್ಯಾಹ್ನ') {\n return hour >= 10 ? hour : hour + 12;\n } else if (meridiem === 'ಸಂಜೆ') {\n return hour + 12;\n }\n },\n meridiem: function (hour, minute, isLower) {\n if (hour < 4) {\n return 'ರಾತ್ರಿ';\n } else if (hour < 10) {\n return 'ಬೆಳಿಗ್ಗೆ';\n } else if (hour < 17) {\n return 'ಮಧ್ಯಾಹ್ನ';\n } else if (hour < 20) {\n return 'ಸಂಜೆ';\n } else {\n return 'ರಾತ್ರಿ';\n }\n },\n dayOfMonthOrdinalParse: /\\d{1,2}(ನೇ)/,\n ordinal: function (number) {\n return number + 'ನೇ';\n },\n week: {\n dow: 0, // Sunday is the first day of the week.\n doy: 6, // The week that contains Jan 6th is the first week of the year.\n },\n });\n\n return kn;\n\n})));\n","//! moment.js locale configuration\n//! locale : Korean [ko]\n//! author : Kyungwook, Park : https://github.com/kyungw00k\n//! author : Jeeeyul Lee Title
\n *
\n * [AnimationBuilder.build](api/animations/AnimationBuilder#build)()
method\n * to create a programmatic animation. The method returns an `AnimationFactory` instance.\n *\n * 2. Use the factory object to create an `AnimationPlayer` and attach it to a DOM element.\n *\n * 3. Use the player object to control the animation programmatically.\n *\n * For example:\n *\n * ```ts\n * // import the service from BrowserAnimationsModule\n * import {AnimationBuilder} from '@angular/animations';\n * // require the service as a dependency\n * class MyCmp {\n * constructor(private _builder: AnimationBuilder) {}\n *\n * makeAnimation(element: any) {\n * // first define a reusable animation\n * const myAnimation = this._builder.build([\n * style({ width: 0 }),\n * animate(1000, style({ width: '100px' }))\n * ]);\n *\n * // use the returned factory object to create a player\n * const player = myAnimation.create(element);\n *\n * player.play();\n * }\n * }\n * ```\n *\n * @publicApi\n */\nclass AnimationBuilder {\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: AnimationBuilder, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: AnimationBuilder, providedIn: 'root', useFactory: () => inject(BrowserAnimationBuilder) }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: AnimationBuilder, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root', useFactory: () => inject(BrowserAnimationBuilder) }]\n }] });\n/**\n * A factory object returned from the\n * [AnimationBuilder.build](api/animations/AnimationBuilder#build)()
\n * method.\n *\n * @publicApi\n */\nclass AnimationFactory {\n}\nclass BrowserAnimationBuilder extends AnimationBuilder {\n constructor(rootRenderer, doc) {\n super();\n this.animationModuleType = inject(ANIMATION_MODULE_TYPE, { optional: true });\n this._nextAnimationId = 0;\n const typeData = {\n id: '0',\n encapsulation: ViewEncapsulation.None,\n styles: [],\n data: { animation: [] },\n };\n this._renderer = rootRenderer.createRenderer(doc.body, typeData);\n if (this.animationModuleType === null && !isAnimationRenderer(this._renderer)) {\n // We only support AnimationRenderer & DynamicDelegationRenderer for this AnimationBuilder\n throw new ɵRuntimeError(3600 /* RuntimeErrorCode.BROWSER_ANIMATION_BUILDER_INJECTED_WITHOUT_ANIMATIONS */, (typeof ngDevMode === 'undefined' || ngDevMode) &&\n 'Angular detected that the `AnimationBuilder` was injected, but animation support was not enabled. ' +\n 'Please make sure that you enable animations in your application by calling `provideAnimations()` or `provideAnimationsAsync()` function.');\n }\n }\n build(animation) {\n const id = this._nextAnimationId;\n this._nextAnimationId++;\n const entry = Array.isArray(animation) ? sequence(animation) : animation;\n issueAnimationCommand(this._renderer, null, id, 'register', [entry]);\n return new BrowserAnimationFactory(id, this._renderer);\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: BrowserAnimationBuilder, deps: [{ token: i0.RendererFactory2 }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: BrowserAnimationBuilder, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: BrowserAnimationBuilder, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [{ type: i0.RendererFactory2 }, { type: Document, decorators: [{\n type: Inject,\n args: [DOCUMENT]\n }] }] });\nclass BrowserAnimationFactory extends AnimationFactory {\n constructor(_id, _renderer) {\n super();\n this._id = _id;\n this._renderer = _renderer;\n }\n create(element, options) {\n return new RendererAnimationPlayer(this._id, element, options || {}, this._renderer);\n }\n}\nclass RendererAnimationPlayer {\n constructor(id, element, options, _renderer) {\n this.id = id;\n this.element = element;\n this._renderer = _renderer;\n this.parentPlayer = null;\n this._started = false;\n this.totalTime = 0;\n this._command('create', options);\n }\n _listen(eventName, callback) {\n return this._renderer.listen(this.element, `@@${this.id}:${eventName}`, callback);\n }\n _command(command, ...args) {\n issueAnimationCommand(this._renderer, this.element, this.id, command, args);\n }\n onDone(fn) {\n this._listen('done', fn);\n }\n onStart(fn) {\n this._listen('start', fn);\n }\n onDestroy(fn) {\n this._listen('destroy', fn);\n }\n init() {\n this._command('init');\n }\n hasStarted() {\n return this._started;\n }\n play() {\n this._command('play');\n this._started = true;\n }\n pause() {\n this._command('pause');\n }\n restart() {\n this._command('restart');\n }\n finish() {\n this._command('finish');\n }\n destroy() {\n this._command('destroy');\n }\n reset() {\n this._command('reset');\n this._started = false;\n }\n setPosition(p) {\n this._command('setPosition', p);\n }\n getPosition() {\n return unwrapAnimationRenderer(this._renderer)?.engine?.players[this.id]?.getPosition() ?? 0;\n }\n}\nfunction issueAnimationCommand(renderer, element, id, command, args) {\n renderer.setProperty(element, `@@${id}:${command}`, args);\n}\n/**\n * The following 2 methods cannot reference their correct types (AnimationRenderer &\n * DynamicDelegationRenderer) since this would introduce a import cycle.\n */\nfunction unwrapAnimationRenderer(renderer) {\n const type = renderer.ɵtype;\n if (type === 0 /* AnimationRendererType.Regular */) {\n return renderer;\n }\n else if (type === 1 /* AnimationRendererType.Delegated */) {\n return renderer.animationRenderer;\n }\n return null;\n}\nfunction isAnimationRenderer(renderer) {\n const type = renderer.ɵtype;\n return type === 0 /* AnimationRendererType.Regular */ || type === 1 /* AnimationRendererType.Delegated */;\n}\n\n/**\n * An empty programmatic controller for reusable animations.\n * Used internally when animations are disabled, to avoid\n * checking for the null case when an animation player is expected.\n *\n * @see {@link animate}\n * @see {@link AnimationPlayer}\n * @see {@link ɵAnimationGroupPlayer AnimationGroupPlayer}\n *\n * @publicApi\n */\nclass NoopAnimationPlayer {\n constructor(duration = 0, delay = 0) {\n this._onDoneFns = [];\n this._onStartFns = [];\n this._onDestroyFns = [];\n this._originalOnDoneFns = [];\n this._originalOnStartFns = [];\n this._started = false;\n this._destroyed = false;\n this._finished = false;\n this._position = 0;\n this.parentPlayer = null;\n this.totalTime = duration + delay;\n }\n _onFinish() {\n if (!this._finished) {\n this._finished = true;\n this._onDoneFns.forEach((fn) => fn());\n this._onDoneFns = [];\n }\n }\n onStart(fn) {\n this._originalOnStartFns.push(fn);\n this._onStartFns.push(fn);\n }\n onDone(fn) {\n this._originalOnDoneFns.push(fn);\n this._onDoneFns.push(fn);\n }\n onDestroy(fn) {\n this._onDestroyFns.push(fn);\n }\n hasStarted() {\n return this._started;\n }\n init() { }\n play() {\n if (!this.hasStarted()) {\n this._onStart();\n this.triggerMicrotask();\n }\n this._started = true;\n }\n /** @internal */\n triggerMicrotask() {\n queueMicrotask(() => this._onFinish());\n }\n _onStart() {\n this._onStartFns.forEach((fn) => fn());\n this._onStartFns = [];\n }\n pause() { }\n restart() { }\n finish() {\n this._onFinish();\n }\n destroy() {\n if (!this._destroyed) {\n this._destroyed = true;\n if (!this.hasStarted()) {\n this._onStart();\n }\n this.finish();\n this._onDestroyFns.forEach((fn) => fn());\n this._onDestroyFns = [];\n }\n }\n reset() {\n this._started = false;\n this._finished = false;\n this._onStartFns = this._originalOnStartFns;\n this._onDoneFns = this._originalOnDoneFns;\n }\n setPosition(position) {\n this._position = this.totalTime ? position * this.totalTime : 1;\n }\n getPosition() {\n return this.totalTime ? this._position / this.totalTime : 1;\n }\n /** @internal */\n triggerCallback(phaseName) {\n const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns;\n methods.forEach((fn) => fn());\n methods.length = 0;\n }\n}\n\n/**\n * A programmatic controller for a group of reusable animations.\n * Used internally to control animations.\n *\n * @see {@link AnimationPlayer}\n * @see {@link animations/group group}\n *\n */\nclass AnimationGroupPlayer {\n constructor(_players) {\n this._onDoneFns = [];\n this._onStartFns = [];\n this._finished = false;\n this._started = false;\n this._destroyed = false;\n this._onDestroyFns = [];\n this.parentPlayer = null;\n this.totalTime = 0;\n this.players = _players;\n let doneCount = 0;\n let destroyCount = 0;\n let startCount = 0;\n const total = this.players.length;\n if (total == 0) {\n queueMicrotask(() => this._onFinish());\n }\n else {\n this.players.forEach((player) => {\n player.onDone(() => {\n if (++doneCount == total) {\n this._onFinish();\n }\n });\n player.onDestroy(() => {\n if (++destroyCount == total) {\n this._onDestroy();\n }\n });\n player.onStart(() => {\n if (++startCount == total) {\n this._onStart();\n }\n });\n });\n }\n this.totalTime = this.players.reduce((time, player) => Math.max(time, player.totalTime), 0);\n }\n _onFinish() {\n if (!this._finished) {\n this._finished = true;\n this._onDoneFns.forEach((fn) => fn());\n this._onDoneFns = [];\n }\n }\n init() {\n this.players.forEach((player) => player.init());\n }\n onStart(fn) {\n this._onStartFns.push(fn);\n }\n _onStart() {\n if (!this.hasStarted()) {\n this._started = true;\n this._onStartFns.forEach((fn) => fn());\n this._onStartFns = [];\n }\n }\n onDone(fn) {\n this._onDoneFns.push(fn);\n }\n onDestroy(fn) {\n this._onDestroyFns.push(fn);\n }\n hasStarted() {\n return this._started;\n }\n play() {\n if (!this.parentPlayer) {\n this.init();\n }\n this._onStart();\n this.players.forEach((player) => player.play());\n }\n pause() {\n this.players.forEach((player) => player.pause());\n }\n restart() {\n this.players.forEach((player) => player.restart());\n }\n finish() {\n this._onFinish();\n this.players.forEach((player) => player.finish());\n }\n destroy() {\n this._onDestroy();\n }\n _onDestroy() {\n if (!this._destroyed) {\n this._destroyed = true;\n this._onFinish();\n this.players.forEach((player) => player.destroy());\n this._onDestroyFns.forEach((fn) => fn());\n this._onDestroyFns = [];\n }\n }\n reset() {\n this.players.forEach((player) => player.reset());\n this._destroyed = false;\n this._finished = false;\n this._started = false;\n }\n setPosition(p) {\n const timeAtPosition = p * this.totalTime;\n this.players.forEach((player) => {\n const position = player.totalTime ? Math.min(1, timeAtPosition / player.totalTime) : 1;\n player.setPosition(position);\n });\n }\n getPosition() {\n const longestPlayer = this.players.reduce((longestSoFar, player) => {\n const newPlayerIsLongest = longestSoFar === null || player.totalTime > longestSoFar.totalTime;\n return newPlayerIsLongest ? player : longestSoFar;\n }, null);\n return longestPlayer != null ? longestPlayer.getPosition() : 0;\n }\n beforeDestroy() {\n this.players.forEach((player) => {\n if (player.beforeDestroy) {\n player.beforeDestroy();\n }\n });\n }\n /** @internal */\n triggerCallback(phaseName) {\n const methods = phaseName == 'start' ? this._onStartFns : this._onDoneFns;\n methods.forEach((fn) => fn());\n methods.length = 0;\n }\n}\n\nconst ɵPRE_STYLE = '!';\n\n/**\n * @module\n * @description\n * Entry point for all animation APIs of the animation package.\n */\n\n/**\n * @module\n * @description\n * Entry point for all public APIs of this package.\n */\n\n// This file is not used to build this module. It is only used during editing\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { AUTO_STYLE, AnimationBuilder, AnimationFactory, AnimationMetadataType, NoopAnimationPlayer, animate, animateChild, animation, group, keyframes, query, sequence, stagger, state, style, transition, trigger, useAnimation, AnimationGroupPlayer as ɵAnimationGroupPlayer, BrowserAnimationBuilder as ɵBrowserAnimationBuilder, ɵPRE_STYLE };\n","/**\n * @license Angular v17.3.10\n * (c) 2010-2024 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport { ɵAnimationGroupPlayer, NoopAnimationPlayer, AUTO_STYLE, ɵPRE_STYLE, sequence, AnimationMetadataType, style } from '@angular/animations';\nimport * as i0 from '@angular/core';\nimport { ɵRuntimeError, Injectable } from '@angular/core';\n\nconst LINE_START = '\\n - ';\nfunction invalidTimingValue(exp) {\n return new ɵRuntimeError(3000 /* RuntimeErrorCode.INVALID_TIMING_VALUE */, ngDevMode && `The provided timing value \"${exp}\" is invalid.`);\n}\nfunction negativeStepValue() {\n return new ɵRuntimeError(3100 /* RuntimeErrorCode.NEGATIVE_STEP_VALUE */, ngDevMode && 'Duration values below 0 are not allowed for this animation step.');\n}\nfunction negativeDelayValue() {\n return new ɵRuntimeError(3101 /* RuntimeErrorCode.NEGATIVE_DELAY_VALUE */, ngDevMode && 'Delay values below 0 are not allowed for this animation step.');\n}\nfunction invalidStyleParams(varName) {\n return new ɵRuntimeError(3001 /* RuntimeErrorCode.INVALID_STYLE_PARAMS */, ngDevMode &&\n `Unable to resolve the local animation param ${varName} in the given list of values`);\n}\nfunction invalidParamValue(varName) {\n return new ɵRuntimeError(3003 /* RuntimeErrorCode.INVALID_PARAM_VALUE */, ngDevMode && `Please provide a value for the animation param ${varName}`);\n}\nfunction invalidNodeType(nodeType) {\n return new ɵRuntimeError(3004 /* RuntimeErrorCode.INVALID_NODE_TYPE */, ngDevMode && `Unable to resolve animation metadata node #${nodeType}`);\n}\nfunction invalidCssUnitValue(userProvidedProperty, value) {\n return new ɵRuntimeError(3005 /* RuntimeErrorCode.INVALID_CSS_UNIT_VALUE */, ngDevMode && `Please provide a CSS unit value for ${userProvidedProperty}:${value}`);\n}\nfunction invalidTrigger() {\n return new ɵRuntimeError(3006 /* RuntimeErrorCode.INVALID_TRIGGER */, ngDevMode &&\n \"animation triggers cannot be prefixed with an `@` sign (e.g. trigger('@foo', [...]))\");\n}\nfunction invalidDefinition() {\n return new ɵRuntimeError(3007 /* RuntimeErrorCode.INVALID_DEFINITION */, ngDevMode && 'only state() and transition() definitions can sit inside of a trigger()');\n}\nfunction invalidState(metadataName, missingSubs) {\n return new ɵRuntimeError(3008 /* RuntimeErrorCode.INVALID_STATE */, ngDevMode &&\n `state(\"${metadataName}\", ...) must define default values for all the following style substitutions: ${missingSubs.join(', ')}`);\n}\nfunction invalidStyleValue(value) {\n return new ɵRuntimeError(3002 /* RuntimeErrorCode.INVALID_STYLE_VALUE */, ngDevMode && `The provided style string value ${value} is not allowed.`);\n}\nfunction invalidProperty(prop) {\n return new ɵRuntimeError(3009 /* RuntimeErrorCode.INVALID_PROPERTY */, ngDevMode &&\n `The provided animation property \"${prop}\" is not a supported CSS property for animations`);\n}\nfunction invalidParallelAnimation(prop, firstStart, firstEnd, secondStart, secondEnd) {\n return new ɵRuntimeError(3010 /* RuntimeErrorCode.INVALID_PARALLEL_ANIMATION */, ngDevMode &&\n `The CSS property \"${prop}\" that exists between the times of \"${firstStart}ms\" and \"${firstEnd}ms\" is also being animated in a parallel animation between the times of \"${secondStart}ms\" and \"${secondEnd}ms\"`);\n}\nfunction invalidKeyframes() {\n return new ɵRuntimeError(3011 /* RuntimeErrorCode.INVALID_KEYFRAMES */, ngDevMode && `keyframes() must be placed inside of a call to animate()`);\n}\nfunction invalidOffset() {\n return new ɵRuntimeError(3012 /* RuntimeErrorCode.INVALID_OFFSET */, ngDevMode && `Please ensure that all keyframe offsets are between 0 and 1`);\n}\nfunction keyframeOffsetsOutOfOrder() {\n return new ɵRuntimeError(3200 /* RuntimeErrorCode.KEYFRAME_OFFSETS_OUT_OF_ORDER */, ngDevMode && `Please ensure that all keyframe offsets are in order`);\n}\nfunction keyframesMissingOffsets() {\n return new ɵRuntimeError(3202 /* RuntimeErrorCode.KEYFRAMES_MISSING_OFFSETS */, ngDevMode && `Not all style() steps within the declared keyframes() contain offsets`);\n}\nfunction invalidStagger() {\n return new ɵRuntimeError(3013 /* RuntimeErrorCode.INVALID_STAGGER */, ngDevMode && `stagger() can only be used inside of query()`);\n}\nfunction invalidQuery(selector) {\n return new ɵRuntimeError(3014 /* RuntimeErrorCode.INVALID_QUERY */, ngDevMode &&\n `\\`query(\"${selector}\")\\` returned zero elements. (Use \\`query(\"${selector}\", { optional: true })\\` if you wish to allow this.)`);\n}\nfunction invalidExpression(expr) {\n return new ɵRuntimeError(3015 /* RuntimeErrorCode.INVALID_EXPRESSION */, ngDevMode && `The provided transition expression \"${expr}\" is not supported`);\n}\nfunction invalidTransitionAlias(alias) {\n return new ɵRuntimeError(3016 /* RuntimeErrorCode.INVALID_TRANSITION_ALIAS */, ngDevMode && `The transition alias value \"${alias}\" is not supported`);\n}\nfunction validationFailed(errors) {\n return new ɵRuntimeError(3500 /* RuntimeErrorCode.VALIDATION_FAILED */, ngDevMode && `animation validation failed:\\n${errors.map((err) => err.message).join('\\n')}`);\n}\nfunction buildingFailed(errors) {\n return new ɵRuntimeError(3501 /* RuntimeErrorCode.BUILDING_FAILED */, ngDevMode && `animation building failed:\\n${errors.map((err) => err.message).join('\\n')}`);\n}\nfunction triggerBuildFailed(name, errors) {\n return new ɵRuntimeError(3404 /* RuntimeErrorCode.TRIGGER_BUILD_FAILED */, ngDevMode &&\n `The animation trigger \"${name}\" has failed to build due to the following errors:\\n - ${errors\n .map((err) => err.message)\n .join('\\n - ')}`);\n}\nfunction animationFailed(errors) {\n return new ɵRuntimeError(3502 /* RuntimeErrorCode.ANIMATION_FAILED */, ngDevMode &&\n `Unable to animate due to the following errors:${LINE_START}${errors\n .map((err) => err.message)\n .join(LINE_START)}`);\n}\nfunction registerFailed(errors) {\n return new ɵRuntimeError(3503 /* RuntimeErrorCode.REGISTRATION_FAILED */, ngDevMode &&\n `Unable to build the animation due to the following errors: ${errors\n .map((err) => err.message)\n .join('\\n')}`);\n}\nfunction missingOrDestroyedAnimation() {\n return new ɵRuntimeError(3300 /* RuntimeErrorCode.MISSING_OR_DESTROYED_ANIMATION */, ngDevMode && \"The requested animation doesn't exist or has already been destroyed\");\n}\nfunction createAnimationFailed(errors) {\n return new ɵRuntimeError(3504 /* RuntimeErrorCode.CREATE_ANIMATION_FAILED */, ngDevMode &&\n `Unable to create the animation due to the following errors:${errors\n .map((err) => err.message)\n .join('\\n')}`);\n}\nfunction missingPlayer(id) {\n return new ɵRuntimeError(3301 /* RuntimeErrorCode.MISSING_PLAYER */, ngDevMode && `Unable to find the timeline player referenced by ${id}`);\n}\nfunction missingTrigger(phase, name) {\n return new ɵRuntimeError(3302 /* RuntimeErrorCode.MISSING_TRIGGER */, ngDevMode &&\n `Unable to listen on the animation trigger event \"${phase}\" because the animation trigger \"${name}\" doesn\\'t exist!`);\n}\nfunction missingEvent(name) {\n return new ɵRuntimeError(3303 /* RuntimeErrorCode.MISSING_EVENT */, ngDevMode &&\n `Unable to listen on the animation trigger \"${name}\" because the provided event is undefined!`);\n}\nfunction unsupportedTriggerEvent(phase, name) {\n return new ɵRuntimeError(3400 /* RuntimeErrorCode.UNSUPPORTED_TRIGGER_EVENT */, ngDevMode &&\n `The provided animation trigger event \"${phase}\" for the animation trigger \"${name}\" is not supported!`);\n}\nfunction unregisteredTrigger(name) {\n return new ɵRuntimeError(3401 /* RuntimeErrorCode.UNREGISTERED_TRIGGER */, ngDevMode && `The provided animation trigger \"${name}\" has not been registered!`);\n}\nfunction triggerTransitionsFailed(errors) {\n return new ɵRuntimeError(3402 /* RuntimeErrorCode.TRIGGER_TRANSITIONS_FAILED */, ngDevMode &&\n `Unable to process animations due to the following failed trigger transitions\\n ${errors\n .map((err) => err.message)\n .join('\\n')}`);\n}\nfunction triggerParsingFailed(name, errors) {\n return new ɵRuntimeError(3403 /* RuntimeErrorCode.TRIGGER_PARSING_FAILED */, ngDevMode &&\n `Animation parsing for the ${name} trigger have failed:${LINE_START}${errors\n .map((err) => err.message)\n .join(LINE_START)}`);\n}\nfunction transitionFailed(name, errors) {\n return new ɵRuntimeError(3505 /* RuntimeErrorCode.TRANSITION_FAILED */, ngDevMode && `@${name} has failed due to:\\n ${errors.map((err) => err.message).join('\\n- ')}`);\n}\n\n/**\n * Set of all animatable CSS properties\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties\n */\nconst ANIMATABLE_PROP_SET = new Set([\n '-moz-outline-radius',\n '-moz-outline-radius-bottomleft',\n '-moz-outline-radius-bottomright',\n '-moz-outline-radius-topleft',\n '-moz-outline-radius-topright',\n '-ms-grid-columns',\n '-ms-grid-rows',\n '-webkit-line-clamp',\n '-webkit-text-fill-color',\n '-webkit-text-stroke',\n '-webkit-text-stroke-color',\n 'accent-color',\n 'all',\n 'backdrop-filter',\n 'background',\n 'background-color',\n 'background-position',\n 'background-size',\n 'block-size',\n 'border',\n 'border-block-end',\n 'border-block-end-color',\n 'border-block-end-width',\n 'border-block-start',\n 'border-block-start-color',\n 'border-block-start-width',\n 'border-bottom',\n 'border-bottom-color',\n 'border-bottom-left-radius',\n 'border-bottom-right-radius',\n 'border-bottom-width',\n 'border-color',\n 'border-end-end-radius',\n 'border-end-start-radius',\n 'border-image-outset',\n 'border-image-slice',\n 'border-image-width',\n 'border-inline-end',\n 'border-inline-end-color',\n 'border-inline-end-width',\n 'border-inline-start',\n 'border-inline-start-color',\n 'border-inline-start-width',\n 'border-left',\n 'border-left-color',\n 'border-left-width',\n 'border-radius',\n 'border-right',\n 'border-right-color',\n 'border-right-width',\n 'border-start-end-radius',\n 'border-start-start-radius',\n 'border-top',\n 'border-top-color',\n 'border-top-left-radius',\n 'border-top-right-radius',\n 'border-top-width',\n 'border-width',\n 'bottom',\n 'box-shadow',\n 'caret-color',\n 'clip',\n 'clip-path',\n 'color',\n 'column-count',\n 'column-gap',\n 'column-rule',\n 'column-rule-color',\n 'column-rule-width',\n 'column-width',\n 'columns',\n 'filter',\n 'flex',\n 'flex-basis',\n 'flex-grow',\n 'flex-shrink',\n 'font',\n 'font-size',\n 'font-size-adjust',\n 'font-stretch',\n 'font-variation-settings',\n 'font-weight',\n 'gap',\n 'grid-column-gap',\n 'grid-gap',\n 'grid-row-gap',\n 'grid-template-columns',\n 'grid-template-rows',\n 'height',\n 'inline-size',\n 'input-security',\n 'inset',\n 'inset-block',\n 'inset-block-end',\n 'inset-block-start',\n 'inset-inline',\n 'inset-inline-end',\n 'inset-inline-start',\n 'left',\n 'letter-spacing',\n 'line-clamp',\n 'line-height',\n 'margin',\n 'margin-block-end',\n 'margin-block-start',\n 'margin-bottom',\n 'margin-inline-end',\n 'margin-inline-start',\n 'margin-left',\n 'margin-right',\n 'margin-top',\n 'mask',\n 'mask-border',\n 'mask-position',\n 'mask-size',\n 'max-block-size',\n 'max-height',\n 'max-inline-size',\n 'max-lines',\n 'max-width',\n 'min-block-size',\n 'min-height',\n 'min-inline-size',\n 'min-width',\n 'object-position',\n 'offset',\n 'offset-anchor',\n 'offset-distance',\n 'offset-path',\n 'offset-position',\n 'offset-rotate',\n 'opacity',\n 'order',\n 'outline',\n 'outline-color',\n 'outline-offset',\n 'outline-width',\n 'padding',\n 'padding-block-end',\n 'padding-block-start',\n 'padding-bottom',\n 'padding-inline-end',\n 'padding-inline-start',\n 'padding-left',\n 'padding-right',\n 'padding-top',\n 'perspective',\n 'perspective-origin',\n 'right',\n 'rotate',\n 'row-gap',\n 'scale',\n 'scroll-margin',\n 'scroll-margin-block',\n 'scroll-margin-block-end',\n 'scroll-margin-block-start',\n 'scroll-margin-bottom',\n 'scroll-margin-inline',\n 'scroll-margin-inline-end',\n 'scroll-margin-inline-start',\n 'scroll-margin-left',\n 'scroll-margin-right',\n 'scroll-margin-top',\n 'scroll-padding',\n 'scroll-padding-block',\n 'scroll-padding-block-end',\n 'scroll-padding-block-start',\n 'scroll-padding-bottom',\n 'scroll-padding-inline',\n 'scroll-padding-inline-end',\n 'scroll-padding-inline-start',\n 'scroll-padding-left',\n 'scroll-padding-right',\n 'scroll-padding-top',\n 'scroll-snap-coordinate',\n 'scroll-snap-destination',\n 'scrollbar-color',\n 'shape-image-threshold',\n 'shape-margin',\n 'shape-outside',\n 'tab-size',\n 'text-decoration',\n 'text-decoration-color',\n 'text-decoration-thickness',\n 'text-emphasis',\n 'text-emphasis-color',\n 'text-indent',\n 'text-shadow',\n 'text-underline-offset',\n 'top',\n 'transform',\n 'transform-origin',\n 'translate',\n 'vertical-align',\n 'visibility',\n 'width',\n 'word-spacing',\n 'z-index',\n 'zoom',\n]);\n\nfunction optimizeGroupPlayer(players) {\n switch (players.length) {\n case 0:\n return new NoopAnimationPlayer();\n case 1:\n return players[0];\n default:\n return new ɵAnimationGroupPlayer(players);\n }\n}\nfunction normalizeKeyframes$1(normalizer, keyframes, preStyles = new Map(), postStyles = new Map()) {\n const errors = [];\n const normalizedKeyframes = [];\n let previousOffset = -1;\n let previousKeyframe = null;\n keyframes.forEach((kf) => {\n const offset = kf.get('offset');\n const isSameOffset = offset == previousOffset;\n const normalizedKeyframe = (isSameOffset && previousKeyframe) || new Map();\n kf.forEach((val, prop) => {\n let normalizedProp = prop;\n let normalizedValue = val;\n if (prop !== 'offset') {\n normalizedProp = normalizer.normalizePropertyName(normalizedProp, errors);\n switch (normalizedValue) {\n case ɵPRE_STYLE:\n normalizedValue = preStyles.get(prop);\n break;\n case AUTO_STYLE:\n normalizedValue = postStyles.get(prop);\n break;\n default:\n normalizedValue = normalizer.normalizeStyleValue(prop, normalizedProp, normalizedValue, errors);\n break;\n }\n }\n normalizedKeyframe.set(normalizedProp, normalizedValue);\n });\n if (!isSameOffset) {\n normalizedKeyframes.push(normalizedKeyframe);\n }\n previousKeyframe = normalizedKeyframe;\n previousOffset = offset;\n });\n if (errors.length) {\n throw animationFailed(errors);\n }\n return normalizedKeyframes;\n}\nfunction listenOnPlayer(player, eventName, event, callback) {\n switch (eventName) {\n case 'start':\n player.onStart(() => callback(event && copyAnimationEvent(event, 'start', player)));\n break;\n case 'done':\n player.onDone(() => callback(event && copyAnimationEvent(event, 'done', player)));\n break;\n case 'destroy':\n player.onDestroy(() => callback(event && copyAnimationEvent(event, 'destroy', player)));\n break;\n }\n}\nfunction copyAnimationEvent(e, phaseName, player) {\n const totalTime = player.totalTime;\n const disabled = player.disabled ? true : false;\n const event = makeAnimationEvent(e.element, e.triggerName, e.fromState, e.toState, phaseName || e.phaseName, totalTime == undefined ? e.totalTime : totalTime, disabled);\n const data = e['_data'];\n if (data != null) {\n event['_data'] = data;\n }\n return event;\n}\nfunction makeAnimationEvent(element, triggerName, fromState, toState, phaseName = '', totalTime = 0, disabled) {\n return { element, triggerName, fromState, toState, phaseName, totalTime, disabled: !!disabled };\n}\nfunction getOrSetDefaultValue(map, key, defaultValue) {\n let value = map.get(key);\n if (!value) {\n map.set(key, (value = defaultValue));\n }\n return value;\n}\nfunction parseTimelineCommand(command) {\n const separatorPos = command.indexOf(':');\n const id = command.substring(1, separatorPos);\n const action = command.slice(separatorPos + 1);\n return [id, action];\n}\nconst documentElement = /* @__PURE__ */ (() => typeof document === 'undefined' ? null : document.documentElement)();\nfunction getParentElement(element) {\n const parent = element.parentNode || element.host || null; // consider host to support shadow DOM\n if (parent === documentElement) {\n return null;\n }\n return parent;\n}\nfunction containsVendorPrefix(prop) {\n // Webkit is the only real popular vendor prefix nowadays\n // cc: http://shouldiprefix.com/\n return prop.substring(1, 6) == 'ebkit'; // webkit or Webkit\n}\nlet _CACHED_BODY = null;\nlet _IS_WEBKIT = false;\nfunction validateStyleProperty(prop) {\n if (!_CACHED_BODY) {\n _CACHED_BODY = getBodyNode() || {};\n _IS_WEBKIT = _CACHED_BODY.style ? 'WebkitAppearance' in _CACHED_BODY.style : false;\n }\n let result = true;\n if (_CACHED_BODY.style && !containsVendorPrefix(prop)) {\n result = prop in _CACHED_BODY.style;\n if (!result && _IS_WEBKIT) {\n const camelProp = 'Webkit' + prop.charAt(0).toUpperCase() + prop.slice(1);\n result = camelProp in _CACHED_BODY.style;\n }\n }\n return result;\n}\nfunction validateWebAnimatableStyleProperty(prop) {\n return ANIMATABLE_PROP_SET.has(prop);\n}\nfunction getBodyNode() {\n if (typeof document != 'undefined') {\n return document.body;\n }\n return null;\n}\nfunction containsElement(elm1, elm2) {\n while (elm2) {\n if (elm2 === elm1) {\n return true;\n }\n elm2 = getParentElement(elm2);\n }\n return false;\n}\nfunction invokeQuery(element, selector, multi) {\n if (multi) {\n return Array.from(element.querySelectorAll(selector));\n }\n const elem = element.querySelector(selector);\n return elem ? [elem] : [];\n}\nfunction hypenatePropsKeys(original) {\n const newMap = new Map();\n original.forEach((val, prop) => {\n const newProp = prop.replace(/([a-z])([A-Z])/g, '$1-$2');\n newMap.set(newProp, val);\n });\n return newMap;\n}\n\n/**\n * @publicApi\n *\n * `AnimationDriver` implentation for Noop animations\n */\nclass NoopAnimationDriver {\n /**\n * @returns Whether `prop` is a valid CSS property\n */\n validateStyleProperty(prop) {\n return validateStyleProperty(prop);\n }\n /**\n * @deprecated unused\n */\n matchesElement(_element, _selector) {\n // This method is deprecated and no longer in use so we return false.\n return false;\n }\n /**\n *\n * @returns Whether elm1 contains elm2.\n */\n containsElement(elm1, elm2) {\n return containsElement(elm1, elm2);\n }\n /**\n * @returns Rhe parent of the given element or `null` if the element is the `document`\n */\n getParentElement(element) {\n return getParentElement(element);\n }\n /**\n * @returns The result of the query selector on the element. The array will contain up to 1 item\n * if `multi` is `false`.\n */\n query(element, selector, multi) {\n return invokeQuery(element, selector, multi);\n }\n /**\n * @returns The `defaultValue` or empty string\n */\n computeStyle(element, prop, defaultValue) {\n return defaultValue || '';\n }\n /**\n * @returns An `NoopAnimationPlayer`\n */\n animate(element, keyframes, duration, delay, easing, previousPlayers = [], scrubberAccessRequested) {\n return new NoopAnimationPlayer(duration, delay);\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: NoopAnimationDriver, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: NoopAnimationDriver }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: NoopAnimationDriver, decorators: [{\n type: Injectable\n }] });\n/**\n * @publicApi\n */\nclass AnimationDriver {\n /**\n * @deprecated Use the NoopAnimationDriver class.\n */\n static { this.NOOP = new NoopAnimationDriver(); }\n}\n\nclass AnimationStyleNormalizer {\n}\nclass NoopAnimationStyleNormalizer {\n normalizePropertyName(propertyName, errors) {\n return propertyName;\n }\n normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {\n return value;\n }\n}\n\nconst ONE_SECOND = 1000;\nconst SUBSTITUTION_EXPR_START = '{{';\nconst SUBSTITUTION_EXPR_END = '}}';\nconst ENTER_CLASSNAME = 'ng-enter';\nconst LEAVE_CLASSNAME = 'ng-leave';\nconst NG_TRIGGER_CLASSNAME = 'ng-trigger';\nconst NG_TRIGGER_SELECTOR = '.ng-trigger';\nconst NG_ANIMATING_CLASSNAME = 'ng-animating';\nconst NG_ANIMATING_SELECTOR = '.ng-animating';\nfunction resolveTimingValue(value) {\n if (typeof value == 'number')\n return value;\n const matches = value.match(/^(-?[\\.\\d]+)(m?s)/);\n if (!matches || matches.length < 2)\n return 0;\n return _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);\n}\nfunction _convertTimeValueToMS(value, unit) {\n switch (unit) {\n case 's':\n return value * ONE_SECOND;\n default: // ms or something else\n return value;\n }\n}\nfunction resolveTiming(timings, errors, allowNegativeValues) {\n return timings.hasOwnProperty('duration')\n ? timings\n : parseTimeExpression(timings, errors, allowNegativeValues);\n}\nfunction parseTimeExpression(exp, errors, allowNegativeValues) {\n const regex = /^(-?[\\.\\d]+)(m?s)(?:\\s+(-?[\\.\\d]+)(m?s))?(?:\\s+([-a-z]+(?:\\(.+?\\))?))?$/i;\n let duration;\n let delay = 0;\n let easing = '';\n if (typeof exp === 'string') {\n const matches = exp.match(regex);\n if (matches === null) {\n errors.push(invalidTimingValue(exp));\n return { duration: 0, delay: 0, easing: '' };\n }\n duration = _convertTimeValueToMS(parseFloat(matches[1]), matches[2]);\n const delayMatch = matches[3];\n if (delayMatch != null) {\n delay = _convertTimeValueToMS(parseFloat(delayMatch), matches[4]);\n }\n const easingVal = matches[5];\n if (easingVal) {\n easing = easingVal;\n }\n }\n else {\n duration = exp;\n }\n if (!allowNegativeValues) {\n let containsErrors = false;\n let startIndex = errors.length;\n if (duration < 0) {\n errors.push(negativeStepValue());\n containsErrors = true;\n }\n if (delay < 0) {\n errors.push(negativeDelayValue());\n containsErrors = true;\n }\n if (containsErrors) {\n errors.splice(startIndex, 0, invalidTimingValue(exp));\n }\n }\n return { duration, delay, easing };\n}\nfunction normalizeKeyframes(keyframes) {\n if (!keyframes.length) {\n return [];\n }\n if (keyframes[0] instanceof Map) {\n return keyframes;\n }\n return keyframes.map((kf) => new Map(Object.entries(kf)));\n}\nfunction normalizeStyles(styles) {\n return Array.isArray(styles) ? new Map(...styles) : new Map(styles);\n}\nfunction setStyles(element, styles, formerStyles) {\n styles.forEach((val, prop) => {\n const camelProp = dashCaseToCamelCase(prop);\n if (formerStyles && !formerStyles.has(prop)) {\n formerStyles.set(prop, element.style[camelProp]);\n }\n element.style[camelProp] = val;\n });\n}\nfunction eraseStyles(element, styles) {\n styles.forEach((_, prop) => {\n const camelProp = dashCaseToCamelCase(prop);\n element.style[camelProp] = '';\n });\n}\nfunction normalizeAnimationEntry(steps) {\n if (Array.isArray(steps)) {\n if (steps.length == 1)\n return steps[0];\n return sequence(steps);\n }\n return steps;\n}\nfunction validateStyleParams(value, options, errors) {\n const params = options.params || {};\n const matches = extractStyleParams(value);\n if (matches.length) {\n matches.forEach((varName) => {\n if (!params.hasOwnProperty(varName)) {\n errors.push(invalidStyleParams(varName));\n }\n });\n }\n}\nconst PARAM_REGEX = new RegExp(`${SUBSTITUTION_EXPR_START}\\\\s*(.+?)\\\\s*${SUBSTITUTION_EXPR_END}`, 'g');\nfunction extractStyleParams(value) {\n let params = [];\n if (typeof value === 'string') {\n let match;\n while ((match = PARAM_REGEX.exec(value))) {\n params.push(match[1]);\n }\n PARAM_REGEX.lastIndex = 0;\n }\n return params;\n}\nfunction interpolateParams(value, params, errors) {\n const original = `${value}`;\n const str = original.replace(PARAM_REGEX, (_, varName) => {\n let localVal = params[varName];\n // this means that the value was never overridden by the data passed in by the user\n if (localVal == null) {\n errors.push(invalidParamValue(varName));\n localVal = '';\n }\n return localVal.toString();\n });\n // we do this to assert that numeric values stay as they are\n return str == original ? value : str;\n}\nconst DASH_CASE_REGEXP = /-+([a-z0-9])/g;\nfunction dashCaseToCamelCase(input) {\n return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());\n}\nfunction camelCaseToDashCase(input) {\n return input.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();\n}\nfunction allowPreviousPlayerStylesMerge(duration, delay) {\n return duration === 0 || delay === 0;\n}\nfunction balancePreviousStylesIntoKeyframes(element, keyframes, previousStyles) {\n if (previousStyles.size && keyframes.length) {\n let startingKeyframe = keyframes[0];\n let missingStyleProps = [];\n previousStyles.forEach((val, prop) => {\n if (!startingKeyframe.has(prop)) {\n missingStyleProps.push(prop);\n }\n startingKeyframe.set(prop, val);\n });\n if (missingStyleProps.length) {\n for (let i = 1; i < keyframes.length; i++) {\n let kf = keyframes[i];\n missingStyleProps.forEach((prop) => kf.set(prop, computeStyle(element, prop)));\n }\n }\n }\n return keyframes;\n}\nfunction visitDslNode(visitor, node, context) {\n switch (node.type) {\n case AnimationMetadataType.Trigger:\n return visitor.visitTrigger(node, context);\n case AnimationMetadataType.State:\n return visitor.visitState(node, context);\n case AnimationMetadataType.Transition:\n return visitor.visitTransition(node, context);\n case AnimationMetadataType.Sequence:\n return visitor.visitSequence(node, context);\n case AnimationMetadataType.Group:\n return visitor.visitGroup(node, context);\n case AnimationMetadataType.Animate:\n return visitor.visitAnimate(node, context);\n case AnimationMetadataType.Keyframes:\n return visitor.visitKeyframes(node, context);\n case AnimationMetadataType.Style:\n return visitor.visitStyle(node, context);\n case AnimationMetadataType.Reference:\n return visitor.visitReference(node, context);\n case AnimationMetadataType.AnimateChild:\n return visitor.visitAnimateChild(node, context);\n case AnimationMetadataType.AnimateRef:\n return visitor.visitAnimateRef(node, context);\n case AnimationMetadataType.Query:\n return visitor.visitQuery(node, context);\n case AnimationMetadataType.Stagger:\n return visitor.visitStagger(node, context);\n default:\n throw invalidNodeType(node.type);\n }\n}\nfunction computeStyle(element, prop) {\n return window.getComputedStyle(element)[prop];\n}\n\nconst DIMENSIONAL_PROP_SET = new Set([\n 'width',\n 'height',\n 'minWidth',\n 'minHeight',\n 'maxWidth',\n 'maxHeight',\n 'left',\n 'top',\n 'bottom',\n 'right',\n 'fontSize',\n 'outlineWidth',\n 'outlineOffset',\n 'paddingTop',\n 'paddingLeft',\n 'paddingBottom',\n 'paddingRight',\n 'marginTop',\n 'marginLeft',\n 'marginBottom',\n 'marginRight',\n 'borderRadius',\n 'borderWidth',\n 'borderTopWidth',\n 'borderLeftWidth',\n 'borderRightWidth',\n 'borderBottomWidth',\n 'textIndent',\n 'perspective',\n]);\nclass WebAnimationsStyleNormalizer extends AnimationStyleNormalizer {\n normalizePropertyName(propertyName, errors) {\n return dashCaseToCamelCase(propertyName);\n }\n normalizeStyleValue(userProvidedProperty, normalizedProperty, value, errors) {\n let unit = '';\n const strVal = value.toString().trim();\n if (DIMENSIONAL_PROP_SET.has(normalizedProperty) && value !== 0 && value !== '0') {\n if (typeof value === 'number') {\n unit = 'px';\n }\n else {\n const valAndSuffixMatch = value.match(/^[+-]?[\\d\\.]+([a-z]*)$/);\n if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {\n errors.push(invalidCssUnitValue(userProvidedProperty, value));\n }\n }\n }\n return strVal + unit;\n }\n}\n\nfunction createListOfWarnings(warnings) {\n const LINE_START = '\\n - ';\n return `${LINE_START}${warnings\n .filter(Boolean)\n .map((warning) => warning)\n .join(LINE_START)}`;\n}\nfunction warnValidation(warnings) {\n (typeof ngDevMode === 'undefined' || ngDevMode) &&\n console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);\n}\nfunction warnTriggerBuild(name, warnings) {\n (typeof ngDevMode === 'undefined' || ngDevMode) &&\n console.warn(`The animation trigger \"${name}\" has built with the following warnings:${createListOfWarnings(warnings)}`);\n}\nfunction warnRegister(warnings) {\n (typeof ngDevMode === 'undefined' || ngDevMode) &&\n console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);\n}\nfunction triggerParsingWarnings(name, warnings) {\n (typeof ngDevMode === 'undefined' || ngDevMode) &&\n console.warn(`Animation parsing for the ${name} trigger presents the following warnings:${createListOfWarnings(warnings)}`);\n}\nfunction pushUnrecognizedPropertiesWarning(warnings, props) {\n if (props.length) {\n warnings.push(`The following provided properties are not recognized: ${props.join(', ')}`);\n }\n}\n\nconst ANY_STATE = '*';\nfunction parseTransitionExpr(transitionValue, errors) {\n const expressions = [];\n if (typeof transitionValue == 'string') {\n transitionValue\n .split(/\\s*,\\s*/)\n .forEach((str) => parseInnerTransitionStr(str, expressions, errors));\n }\n else {\n expressions.push(transitionValue);\n }\n return expressions;\n}\nfunction parseInnerTransitionStr(eventStr, expressions, errors) {\n if (eventStr[0] == ':') {\n const result = parseAnimationAlias(eventStr, errors);\n if (typeof result == 'function') {\n expressions.push(result);\n return;\n }\n eventStr = result;\n }\n const match = eventStr.match(/^(\\*|[-\\w]+)\\s*([=-]>)\\s*(\\*|[-\\w]+)$/);\n if (match == null || match.length < 4) {\n errors.push(invalidExpression(eventStr));\n return expressions;\n }\n const fromState = match[1];\n const separator = match[2];\n const toState = match[3];\n expressions.push(makeLambdaFromStates(fromState, toState));\n const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;\n if (separator[0] == '<' && !isFullAnyStateExpr) {\n expressions.push(makeLambdaFromStates(toState, fromState));\n }\n return;\n}\nfunction parseAnimationAlias(alias, errors) {\n switch (alias) {\n case ':enter':\n return 'void => *';\n case ':leave':\n return '* => void';\n case ':increment':\n return (fromState, toState) => parseFloat(toState) > parseFloat(fromState);\n case ':decrement':\n return (fromState, toState) => parseFloat(toState) < parseFloat(fromState);\n default:\n errors.push(invalidTransitionAlias(alias));\n return '* => *';\n }\n}\n// DO NOT REFACTOR ... keep the follow set instantiations\n// with the values intact (closure compiler for some reason\n// removes follow-up lines that add the values outside of\n// the constructor...\nconst TRUE_BOOLEAN_VALUES = new Set(['true', '1']);\nconst FALSE_BOOLEAN_VALUES = new Set(['false', '0']);\nfunction makeLambdaFromStates(lhs, rhs) {\n const LHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(lhs) || FALSE_BOOLEAN_VALUES.has(lhs);\n const RHS_MATCH_BOOLEAN = TRUE_BOOLEAN_VALUES.has(rhs) || FALSE_BOOLEAN_VALUES.has(rhs);\n return (fromState, toState) => {\n let lhsMatch = lhs == ANY_STATE || lhs == fromState;\n let rhsMatch = rhs == ANY_STATE || rhs == toState;\n if (!lhsMatch && LHS_MATCH_BOOLEAN && typeof fromState === 'boolean') {\n lhsMatch = fromState ? TRUE_BOOLEAN_VALUES.has(lhs) : FALSE_BOOLEAN_VALUES.has(lhs);\n }\n if (!rhsMatch && RHS_MATCH_BOOLEAN && typeof toState === 'boolean') {\n rhsMatch = toState ? TRUE_BOOLEAN_VALUES.has(rhs) : FALSE_BOOLEAN_VALUES.has(rhs);\n }\n return lhsMatch && rhsMatch;\n };\n}\n\nconst SELF_TOKEN = ':self';\nconst SELF_TOKEN_REGEX = new RegExp(`s*${SELF_TOKEN}s*,?`, 'g');\n/*\n * [Validation]\n * The visitor code below will traverse the animation AST generated by the animation verb functions\n * (the output is a tree of objects) and attempt to perform a series of validations on the data. The\n * following corner-cases will be validated:\n *\n * 1. Overlap of animations\n * Given that a CSS property cannot be animated in more than one place at the same time, it's\n * important that this behavior is detected and validated. The way in which this occurs is that\n * each time a style property is examined, a string-map containing the property will be updated with\n * the start and end times for when the property is used within an animation step.\n *\n * If there are two or more parallel animations that are currently running (these are invoked by the\n * group()) on the same element then the validator will throw an error. Since the start/end timing\n * values are collected for each property then if the current animation step is animating the same\n * property and its timing values fall anywhere into the window of time that the property is\n * currently being animated within then this is what causes an error.\n *\n * 2. Timing values\n * The validator will validate to see if a timing value of `duration delay easing` or\n * `durationNumber` is valid or not.\n *\n * (note that upon validation the code below will replace the timing data with an object containing\n * {duration,delay,easing}.\n *\n * 3. Offset Validation\n * Each of the style() calls are allowed to have an offset value when placed inside of keyframes().\n * Offsets within keyframes() are considered valid when:\n *\n * - No offsets are used at all\n * - Each style() entry contains an offset value\n * - Each offset is between 0 and 1\n * - Each offset is greater to or equal than the previous one\n *\n * Otherwise an error will be thrown.\n */\nfunction buildAnimationAst(driver, metadata, errors, warnings) {\n return new AnimationAstBuilderVisitor(driver).build(metadata, errors, warnings);\n}\nconst ROOT_SELECTOR = '';\nclass AnimationAstBuilderVisitor {\n constructor(_driver) {\n this._driver = _driver;\n }\n build(metadata, errors, warnings) {\n const context = new AnimationAstBuilderContext(errors);\n this._resetContextStyleTimingState(context);\n const ast = (visitDslNode(this, normalizeAnimationEntry(metadata), context));\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (context.unsupportedCSSPropertiesFound.size) {\n pushUnrecognizedPropertiesWarning(warnings, [\n ...context.unsupportedCSSPropertiesFound.keys(),\n ]);\n }\n }\n return ast;\n }\n _resetContextStyleTimingState(context) {\n context.currentQuerySelector = ROOT_SELECTOR;\n context.collectedStyles = new Map();\n context.collectedStyles.set(ROOT_SELECTOR, new Map());\n context.currentTime = 0;\n }\n visitTrigger(metadata, context) {\n let queryCount = (context.queryCount = 0);\n let depCount = (context.depCount = 0);\n const states = [];\n const transitions = [];\n if (metadata.name.charAt(0) == '@') {\n context.errors.push(invalidTrigger());\n }\n metadata.definitions.forEach((def) => {\n this._resetContextStyleTimingState(context);\n if (def.type == AnimationMetadataType.State) {\n const stateDef = def;\n const name = stateDef.name;\n name\n .toString()\n .split(/\\s*,\\s*/)\n .forEach((n) => {\n stateDef.name = n;\n states.push(this.visitState(stateDef, context));\n });\n stateDef.name = name;\n }\n else if (def.type == AnimationMetadataType.Transition) {\n const transition = this.visitTransition(def, context);\n queryCount += transition.queryCount;\n depCount += transition.depCount;\n transitions.push(transition);\n }\n else {\n context.errors.push(invalidDefinition());\n }\n });\n return {\n type: AnimationMetadataType.Trigger,\n name: metadata.name,\n states,\n transitions,\n queryCount,\n depCount,\n options: null,\n };\n }\n visitState(metadata, context) {\n const styleAst = this.visitStyle(metadata.styles, context);\n const astParams = (metadata.options && metadata.options.params) || null;\n if (styleAst.containsDynamicStyles) {\n const missingSubs = new Set();\n const params = astParams || {};\n styleAst.styles.forEach((style) => {\n if (style instanceof Map) {\n style.forEach((value) => {\n extractStyleParams(value).forEach((sub) => {\n if (!params.hasOwnProperty(sub)) {\n missingSubs.add(sub);\n }\n });\n });\n }\n });\n if (missingSubs.size) {\n context.errors.push(invalidState(metadata.name, [...missingSubs.values()]));\n }\n }\n return {\n type: AnimationMetadataType.State,\n name: metadata.name,\n style: styleAst,\n options: astParams ? { params: astParams } : null,\n };\n }\n visitTransition(metadata, context) {\n context.queryCount = 0;\n context.depCount = 0;\n const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);\n const matchers = parseTransitionExpr(metadata.expr, context.errors);\n return {\n type: AnimationMetadataType.Transition,\n matchers,\n animation,\n queryCount: context.queryCount,\n depCount: context.depCount,\n options: normalizeAnimationOptions(metadata.options),\n };\n }\n visitSequence(metadata, context) {\n return {\n type: AnimationMetadataType.Sequence,\n steps: metadata.steps.map((s) => visitDslNode(this, s, context)),\n options: normalizeAnimationOptions(metadata.options),\n };\n }\n visitGroup(metadata, context) {\n const currentTime = context.currentTime;\n let furthestTime = 0;\n const steps = metadata.steps.map((step) => {\n context.currentTime = currentTime;\n const innerAst = visitDslNode(this, step, context);\n furthestTime = Math.max(furthestTime, context.currentTime);\n return innerAst;\n });\n context.currentTime = furthestTime;\n return {\n type: AnimationMetadataType.Group,\n steps,\n options: normalizeAnimationOptions(metadata.options),\n };\n }\n visitAnimate(metadata, context) {\n const timingAst = constructTimingAst(metadata.timings, context.errors);\n context.currentAnimateTimings = timingAst;\n let styleAst;\n let styleMetadata = metadata.styles\n ? metadata.styles\n : style({});\n if (styleMetadata.type == AnimationMetadataType.Keyframes) {\n styleAst = this.visitKeyframes(styleMetadata, context);\n }\n else {\n let styleMetadata = metadata.styles;\n let isEmpty = false;\n if (!styleMetadata) {\n isEmpty = true;\n const newStyleData = {};\n if (timingAst.easing) {\n newStyleData['easing'] = timingAst.easing;\n }\n styleMetadata = style(newStyleData);\n }\n context.currentTime += timingAst.duration + timingAst.delay;\n const _styleAst = this.visitStyle(styleMetadata, context);\n _styleAst.isEmptyStep = isEmpty;\n styleAst = _styleAst;\n }\n context.currentAnimateTimings = null;\n return {\n type: AnimationMetadataType.Animate,\n timings: timingAst,\n style: styleAst,\n options: null,\n };\n }\n visitStyle(metadata, context) {\n const ast = this._makeStyleAst(metadata, context);\n this._validateStyleAst(ast, context);\n return ast;\n }\n _makeStyleAst(metadata, context) {\n const styles = [];\n const metadataStyles = Array.isArray(metadata.styles) ? metadata.styles : [metadata.styles];\n for (let styleTuple of metadataStyles) {\n if (typeof styleTuple === 'string') {\n if (styleTuple === AUTO_STYLE) {\n styles.push(styleTuple);\n }\n else {\n context.errors.push(invalidStyleValue(styleTuple));\n }\n }\n else {\n styles.push(new Map(Object.entries(styleTuple)));\n }\n }\n let containsDynamicStyles = false;\n let collectedEasing = null;\n styles.forEach((styleData) => {\n if (styleData instanceof Map) {\n if (styleData.has('easing')) {\n collectedEasing = styleData.get('easing');\n styleData.delete('easing');\n }\n if (!containsDynamicStyles) {\n for (let value of styleData.values()) {\n if (value.toString().indexOf(SUBSTITUTION_EXPR_START) >= 0) {\n containsDynamicStyles = true;\n break;\n }\n }\n }\n }\n });\n return {\n type: AnimationMetadataType.Style,\n styles,\n easing: collectedEasing,\n offset: metadata.offset,\n containsDynamicStyles,\n options: null,\n };\n }\n _validateStyleAst(ast, context) {\n const timings = context.currentAnimateTimings;\n let endTime = context.currentTime;\n let startTime = context.currentTime;\n if (timings && startTime > 0) {\n startTime -= timings.duration + timings.delay;\n }\n ast.styles.forEach((tuple) => {\n if (typeof tuple === 'string')\n return;\n tuple.forEach((value, prop) => {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n if (!this._driver.validateStyleProperty(prop)) {\n tuple.delete(prop);\n context.unsupportedCSSPropertiesFound.add(prop);\n return;\n }\n }\n // This is guaranteed to have a defined Map at this querySelector location making it\n // safe to add the assertion here. It is set as a default empty map in prior methods.\n const collectedStyles = context.collectedStyles.get(context.currentQuerySelector);\n const collectedEntry = collectedStyles.get(prop);\n let updateCollectedStyle = true;\n if (collectedEntry) {\n if (startTime != endTime &&\n startTime >= collectedEntry.startTime &&\n endTime <= collectedEntry.endTime) {\n context.errors.push(invalidParallelAnimation(prop, collectedEntry.startTime, collectedEntry.endTime, startTime, endTime));\n updateCollectedStyle = false;\n }\n // we always choose the smaller start time value since we\n // want to have a record of the entire animation window where\n // the style property is being animated in between\n startTime = collectedEntry.startTime;\n }\n if (updateCollectedStyle) {\n collectedStyles.set(prop, { startTime, endTime });\n }\n if (context.options) {\n validateStyleParams(value, context.options, context.errors);\n }\n });\n });\n }\n visitKeyframes(metadata, context) {\n const ast = { type: AnimationMetadataType.Keyframes, styles: [], options: null };\n if (!context.currentAnimateTimings) {\n context.errors.push(invalidKeyframes());\n return ast;\n }\n const MAX_KEYFRAME_OFFSET = 1;\n let totalKeyframesWithOffsets = 0;\n const offsets = [];\n let offsetsOutOfOrder = false;\n let keyframesOutOfRange = false;\n let previousOffset = 0;\n const keyframes = metadata.steps.map((styles) => {\n const style = this._makeStyleAst(styles, context);\n let offsetVal = style.offset != null ? style.offset : consumeOffset(style.styles);\n let offset = 0;\n if (offsetVal != null) {\n totalKeyframesWithOffsets++;\n offset = style.offset = offsetVal;\n }\n keyframesOutOfRange = keyframesOutOfRange || offset < 0 || offset > 1;\n offsetsOutOfOrder = offsetsOutOfOrder || offset < previousOffset;\n previousOffset = offset;\n offsets.push(offset);\n return style;\n });\n if (keyframesOutOfRange) {\n context.errors.push(invalidOffset());\n }\n if (offsetsOutOfOrder) {\n context.errors.push(keyframeOffsetsOutOfOrder());\n }\n const length = metadata.steps.length;\n let generatedOffset = 0;\n if (totalKeyframesWithOffsets > 0 && totalKeyframesWithOffsets < length) {\n context.errors.push(keyframesMissingOffsets());\n }\n else if (totalKeyframesWithOffsets == 0) {\n generatedOffset = MAX_KEYFRAME_OFFSET / (length - 1);\n }\n const limit = length - 1;\n const currentTime = context.currentTime;\n const currentAnimateTimings = context.currentAnimateTimings;\n const animateDuration = currentAnimateTimings.duration;\n keyframes.forEach((kf, i) => {\n const offset = generatedOffset > 0 ? (i == limit ? 1 : generatedOffset * i) : offsets[i];\n const durationUpToThisFrame = offset * animateDuration;\n context.currentTime = currentTime + currentAnimateTimings.delay + durationUpToThisFrame;\n currentAnimateTimings.duration = durationUpToThisFrame;\n this._validateStyleAst(kf, context);\n kf.offset = offset;\n ast.styles.push(kf);\n });\n return ast;\n }\n visitReference(metadata, context) {\n return {\n type: AnimationMetadataType.Reference,\n animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),\n options: normalizeAnimationOptions(metadata.options),\n };\n }\n visitAnimateChild(metadata, context) {\n context.depCount++;\n return {\n type: AnimationMetadataType.AnimateChild,\n options: normalizeAnimationOptions(metadata.options),\n };\n }\n visitAnimateRef(metadata, context) {\n return {\n type: AnimationMetadataType.AnimateRef,\n animation: this.visitReference(metadata.animation, context),\n options: normalizeAnimationOptions(metadata.options),\n };\n }\n visitQuery(metadata, context) {\n const parentSelector = context.currentQuerySelector;\n const options = (metadata.options || {});\n context.queryCount++;\n context.currentQuery = metadata;\n const [selector, includeSelf] = normalizeSelector(metadata.selector);\n context.currentQuerySelector = parentSelector.length\n ? parentSelector + ' ' + selector\n : selector;\n getOrSetDefaultValue(context.collectedStyles, context.currentQuerySelector, new Map());\n const animation = visitDslNode(this, normalizeAnimationEntry(metadata.animation), context);\n context.currentQuery = null;\n context.currentQuerySelector = parentSelector;\n return {\n type: AnimationMetadataType.Query,\n selector,\n limit: options.limit || 0,\n optional: !!options.optional,\n includeSelf,\n animation,\n originalSelector: metadata.selector,\n options: normalizeAnimationOptions(metadata.options),\n };\n }\n visitStagger(metadata, context) {\n if (!context.currentQuery) {\n context.errors.push(invalidStagger());\n }\n const timings = metadata.timings === 'full'\n ? { duration: 0, delay: 0, easing: 'full' }\n : resolveTiming(metadata.timings, context.errors, true);\n return {\n type: AnimationMetadataType.Stagger,\n animation: visitDslNode(this, normalizeAnimationEntry(metadata.animation), context),\n timings,\n options: null,\n };\n }\n}\nfunction normalizeSelector(selector) {\n const hasAmpersand = selector.split(/\\s*,\\s*/).find((token) => token == SELF_TOKEN)\n ? true\n : false;\n if (hasAmpersand) {\n selector = selector.replace(SELF_TOKEN_REGEX, '');\n }\n // Note: the :enter and :leave aren't normalized here since those\n // selectors are filled in at runtime during timeline building\n selector = selector\n .replace(/@\\*/g, NG_TRIGGER_SELECTOR)\n .replace(/@\\w+/g, (match) => NG_TRIGGER_SELECTOR + '-' + match.slice(1))\n .replace(/:animating/g, NG_ANIMATING_SELECTOR);\n return [selector, hasAmpersand];\n}\nfunction normalizeParams(obj) {\n return obj ? { ...obj } : null;\n}\nclass AnimationAstBuilderContext {\n constructor(errors) {\n this.errors = errors;\n this.queryCount = 0;\n this.depCount = 0;\n this.currentTransition = null;\n this.currentQuery = null;\n this.currentQuerySelector = null;\n this.currentAnimateTimings = null;\n this.currentTime = 0;\n this.collectedStyles = new Map();\n this.options = null;\n this.unsupportedCSSPropertiesFound = new Set();\n }\n}\nfunction consumeOffset(styles) {\n if (typeof styles == 'string')\n return null;\n let offset = null;\n if (Array.isArray(styles)) {\n styles.forEach((styleTuple) => {\n if (styleTuple instanceof Map && styleTuple.has('offset')) {\n const obj = styleTuple;\n offset = parseFloat(obj.get('offset'));\n obj.delete('offset');\n }\n });\n }\n else if (styles instanceof Map && styles.has('offset')) {\n const obj = styles;\n offset = parseFloat(obj.get('offset'));\n obj.delete('offset');\n }\n return offset;\n}\nfunction constructTimingAst(value, errors) {\n if (value.hasOwnProperty('duration')) {\n return value;\n }\n if (typeof value == 'number') {\n const duration = resolveTiming(value, errors).duration;\n return makeTimingAst(duration, 0, '');\n }\n const strValue = value;\n const isDynamic = strValue.split(/\\s+/).some((v) => v.charAt(0) == '{' && v.charAt(1) == '{');\n if (isDynamic) {\n const ast = makeTimingAst(0, 0, '');\n ast.dynamic = true;\n ast.strValue = strValue;\n return ast;\n }\n const timings = resolveTiming(strValue, errors);\n return makeTimingAst(timings.duration, timings.delay, timings.easing);\n}\nfunction normalizeAnimationOptions(options) {\n if (options) {\n options = { ...options };\n if (options['params']) {\n options['params'] = normalizeParams(options['params']);\n }\n }\n else {\n options = {};\n }\n return options;\n}\nfunction makeTimingAst(duration, delay, easing) {\n return { duration, delay, easing };\n}\n\nfunction createTimelineInstruction(element, keyframes, preStyleProps, postStyleProps, duration, delay, easing = null, subTimeline = false) {\n return {\n type: 1 /* AnimationTransitionInstructionType.TimelineAnimation */,\n element,\n keyframes,\n preStyleProps,\n postStyleProps,\n duration,\n delay,\n totalTime: duration + delay,\n easing,\n subTimeline,\n };\n}\n\nclass ElementInstructionMap {\n constructor() {\n this._map = new Map();\n }\n get(element) {\n return this._map.get(element) || [];\n }\n append(element, instructions) {\n let existingInstructions = this._map.get(element);\n if (!existingInstructions) {\n this._map.set(element, (existingInstructions = []));\n }\n existingInstructions.push(...instructions);\n }\n has(element) {\n return this._map.has(element);\n }\n clear() {\n this._map.clear();\n }\n}\n\nconst ONE_FRAME_IN_MILLISECONDS = 1;\nconst ENTER_TOKEN = ':enter';\nconst ENTER_TOKEN_REGEX = new RegExp(ENTER_TOKEN, 'g');\nconst LEAVE_TOKEN = ':leave';\nconst LEAVE_TOKEN_REGEX = new RegExp(LEAVE_TOKEN, 'g');\n/*\n * The code within this file aims to generate web-animations-compatible keyframes from Angular's\n * animation DSL code.\n *\n * The code below will be converted from:\n *\n * ```\n * sequence([\n * style({ opacity: 0 }),\n * animate(1000, style({ opacity: 0 }))\n * ])\n * ```\n *\n * To:\n * ```\n * keyframes = [{ opacity: 0, offset: 0 }, { opacity: 1, offset: 1 }]\n * duration = 1000\n * delay = 0\n * easing = ''\n * ```\n *\n * For this operation to cover the combination of animation verbs (style, animate, group, etc...) a\n * combination of AST traversal and merge-sort-like algorithms are used.\n *\n * [AST Traversal]\n * Each of the animation verbs, when executed, will return an string-map object representing what\n * type of action it is (style, animate, group, etc...) and the data associated with it. This means\n * that when functional composition mix of these functions is evaluated (like in the example above)\n * then it will end up producing a tree of objects representing the animation itself.\n *\n * When this animation object tree is processed by the visitor code below it will visit each of the\n * verb statements within the visitor. And during each visit it will build the context of the\n * animation keyframes by interacting with the `TimelineBuilder`.\n *\n * [TimelineBuilder]\n * This class is responsible for tracking the styles and building a series of keyframe objects for a\n * timeline between a start and end time. The builder starts off with an initial timeline and each\n * time the AST comes across a `group()`, `keyframes()` or a combination of the two within a\n * `sequence()` then it will generate a sub timeline for each step as well as a new one after\n * they are complete.\n *\n * As the AST is traversed, the timing state on each of the timelines will be incremented. If a sub\n * timeline was created (based on one of the cases above) then the parent timeline will attempt to\n * merge the styles used within the sub timelines into itself (only with group() this will happen).\n * This happens with a merge operation (much like how the merge works in mergeSort) and it will only\n * copy the most recently used styles from the sub timelines into the parent timeline. This ensures\n * that if the styles are used later on in another phase of the animation then they will be the most\n * up-to-date values.\n *\n * [How Missing Styles Are Updated]\n * Each timeline has a `backFill` property which is responsible for filling in new styles into\n * already processed keyframes if a new style shows up later within the animation sequence.\n *\n * ```\n * sequence([\n * style({ width: 0 }),\n * animate(1000, style({ width: 100 })),\n * animate(1000, style({ width: 200 })),\n * animate(1000, style({ width: 300 }))\n * animate(1000, style({ width: 400, height: 400 })) // notice how `height` doesn't exist anywhere\n * else\n * ])\n * ```\n *\n * What is happening here is that the `height` value is added later in the sequence, but is missing\n * from all previous animation steps. Therefore when a keyframe is created it would also be missing\n * from all previous keyframes up until where it is first used. For the timeline keyframe generation\n * to properly fill in the style it will place the previous value (the value from the parent\n * timeline) or a default value of `*` into the backFill map.\n *\n * When a sub-timeline is created it will have its own backFill property. This is done so that\n * styles present within the sub-timeline do not accidentally seep into the previous/future timeline\n * keyframes\n *\n * [Validation]\n * The code in this file is not responsible for validation. That functionality happens with within\n * the `AnimationValidatorVisitor` code.\n */\nfunction buildAnimationTimelines(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles = new Map(), finalStyles = new Map(), options, subInstructions, errors = []) {\n return new AnimationTimelineBuilderVisitor().buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors);\n}\nclass AnimationTimelineBuilderVisitor {\n buildKeyframes(driver, rootElement, ast, enterClassName, leaveClassName, startingStyles, finalStyles, options, subInstructions, errors = []) {\n subInstructions = subInstructions || new ElementInstructionMap();\n const context = new AnimationTimelineContext(driver, rootElement, subInstructions, enterClassName, leaveClassName, errors, []);\n context.options = options;\n const delay = options.delay ? resolveTimingValue(options.delay) : 0;\n context.currentTimeline.delayNextStep(delay);\n context.currentTimeline.setStyles([startingStyles], null, context.errors, options);\n visitDslNode(this, ast, context);\n // this checks to see if an actual animation happened\n const timelines = context.timelines.filter((timeline) => timeline.containsAnimation());\n // note: we just want to apply the final styles for the rootElement, so we do not\n // just apply the styles to the last timeline but the last timeline which\n // element is the root one (basically `*`-styles are replaced with the actual\n // state style values only for the root element)\n if (timelines.length && finalStyles.size) {\n let lastRootTimeline;\n for (let i = timelines.length - 1; i >= 0; i--) {\n const timeline = timelines[i];\n if (timeline.element === rootElement) {\n lastRootTimeline = timeline;\n break;\n }\n }\n if (lastRootTimeline && !lastRootTimeline.allowOnlyTimelineStyles()) {\n lastRootTimeline.setStyles([finalStyles], null, context.errors, options);\n }\n }\n return timelines.length\n ? timelines.map((timeline) => timeline.buildKeyframes())\n : [createTimelineInstruction(rootElement, [], [], [], 0, delay, '', false)];\n }\n visitTrigger(ast, context) {\n // these values are not visited in this AST\n }\n visitState(ast, context) {\n // these values are not visited in this AST\n }\n visitTransition(ast, context) {\n // these values are not visited in this AST\n }\n visitAnimateChild(ast, context) {\n const elementInstructions = context.subInstructions.get(context.element);\n if (elementInstructions) {\n const innerContext = context.createSubContext(ast.options);\n const startTime = context.currentTimeline.currentTime;\n const endTime = this._visitSubInstructions(elementInstructions, innerContext, innerContext.options);\n if (startTime != endTime) {\n // we do this on the upper context because we created a sub context for\n // the sub child animations\n context.transformIntoNewTimeline(endTime);\n }\n }\n context.previousNode = ast;\n }\n visitAnimateRef(ast, context) {\n const innerContext = context.createSubContext(ast.options);\n innerContext.transformIntoNewTimeline();\n this._applyAnimationRefDelays([ast.options, ast.animation.options], context, innerContext);\n this.visitReference(ast.animation, innerContext);\n context.transformIntoNewTimeline(innerContext.currentTimeline.currentTime);\n context.previousNode = ast;\n }\n _applyAnimationRefDelays(animationsRefsOptions, context, innerContext) {\n for (const animationRefOptions of animationsRefsOptions) {\n const animationDelay = animationRefOptions?.delay;\n if (animationDelay) {\n const animationDelayValue = typeof animationDelay === 'number'\n ? animationDelay\n : resolveTimingValue(interpolateParams(animationDelay, animationRefOptions?.params ?? {}, context.errors));\n innerContext.delayNextStep(animationDelayValue);\n }\n }\n }\n _visitSubInstructions(instructions, context, options) {\n const startTime = context.currentTimeline.currentTime;\n let furthestTime = startTime;\n // this is a special-case for when a user wants to skip a sub\n // animation from being fired entirely.\n const duration = options.duration != null ? resolveTimingValue(options.duration) : null;\n const delay = options.delay != null ? resolveTimingValue(options.delay) : null;\n if (duration !== 0) {\n instructions.forEach((instruction) => {\n const instructionTimings = context.appendInstructionToTimeline(instruction, duration, delay);\n furthestTime = Math.max(furthestTime, instructionTimings.duration + instructionTimings.delay);\n });\n }\n return furthestTime;\n }\n visitReference(ast, context) {\n context.updateOptions(ast.options, true);\n visitDslNode(this, ast.animation, context);\n context.previousNode = ast;\n }\n visitSequence(ast, context) {\n const subContextCount = context.subContextCount;\n let ctx = context;\n const options = ast.options;\n if (options && (options.params || options.delay)) {\n ctx = context.createSubContext(options);\n ctx.transformIntoNewTimeline();\n if (options.delay != null) {\n if (ctx.previousNode.type == AnimationMetadataType.Style) {\n ctx.currentTimeline.snapshotCurrentStyles();\n ctx.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n }\n const delay = resolveTimingValue(options.delay);\n ctx.delayNextStep(delay);\n }\n }\n if (ast.steps.length) {\n ast.steps.forEach((s) => visitDslNode(this, s, ctx));\n // this is here just in case the inner steps only contain or end with a style() call\n ctx.currentTimeline.applyStylesToKeyframe();\n // this means that some animation function within the sequence\n // ended up creating a sub timeline (which means the current\n // timeline cannot overlap with the contents of the sequence)\n if (ctx.subContextCount > subContextCount) {\n ctx.transformIntoNewTimeline();\n }\n }\n context.previousNode = ast;\n }\n visitGroup(ast, context) {\n const innerTimelines = [];\n let furthestTime = context.currentTimeline.currentTime;\n const delay = ast.options && ast.options.delay ? resolveTimingValue(ast.options.delay) : 0;\n ast.steps.forEach((s) => {\n const innerContext = context.createSubContext(ast.options);\n if (delay) {\n innerContext.delayNextStep(delay);\n }\n visitDslNode(this, s, innerContext);\n furthestTime = Math.max(furthestTime, innerContext.currentTimeline.currentTime);\n innerTimelines.push(innerContext.currentTimeline);\n });\n // this operation is run after the AST loop because otherwise\n // if the parent timeline's collected styles were updated then\n // it would pass in invalid data into the new-to-be forked items\n innerTimelines.forEach((timeline) => context.currentTimeline.mergeTimelineCollectedStyles(timeline));\n context.transformIntoNewTimeline(furthestTime);\n context.previousNode = ast;\n }\n _visitTiming(ast, context) {\n if (ast.dynamic) {\n const strValue = ast.strValue;\n const timingValue = context.params\n ? interpolateParams(strValue, context.params, context.errors)\n : strValue;\n return resolveTiming(timingValue, context.errors);\n }\n else {\n return { duration: ast.duration, delay: ast.delay, easing: ast.easing };\n }\n }\n visitAnimate(ast, context) {\n const timings = (context.currentAnimateTimings = this._visitTiming(ast.timings, context));\n const timeline = context.currentTimeline;\n if (timings.delay) {\n context.incrementTime(timings.delay);\n timeline.snapshotCurrentStyles();\n }\n const style = ast.style;\n if (style.type == AnimationMetadataType.Keyframes) {\n this.visitKeyframes(style, context);\n }\n else {\n context.incrementTime(timings.duration);\n this.visitStyle(style, context);\n timeline.applyStylesToKeyframe();\n }\n context.currentAnimateTimings = null;\n context.previousNode = ast;\n }\n visitStyle(ast, context) {\n const timeline = context.currentTimeline;\n const timings = context.currentAnimateTimings;\n // this is a special case for when a style() call\n // directly follows an animate() call (but not inside of an animate() call)\n if (!timings && timeline.hasCurrentStyleProperties()) {\n timeline.forwardFrame();\n }\n const easing = (timings && timings.easing) || ast.easing;\n if (ast.isEmptyStep) {\n timeline.applyEmptyStep(easing);\n }\n else {\n timeline.setStyles(ast.styles, easing, context.errors, context.options);\n }\n context.previousNode = ast;\n }\n visitKeyframes(ast, context) {\n const currentAnimateTimings = context.currentAnimateTimings;\n const startTime = context.currentTimeline.duration;\n const duration = currentAnimateTimings.duration;\n const innerContext = context.createSubContext();\n const innerTimeline = innerContext.currentTimeline;\n innerTimeline.easing = currentAnimateTimings.easing;\n ast.styles.forEach((step) => {\n const offset = step.offset || 0;\n innerTimeline.forwardTime(offset * duration);\n innerTimeline.setStyles(step.styles, step.easing, context.errors, context.options);\n innerTimeline.applyStylesToKeyframe();\n });\n // this will ensure that the parent timeline gets all the styles from\n // the child even if the new timeline below is not used\n context.currentTimeline.mergeTimelineCollectedStyles(innerTimeline);\n // we do this because the window between this timeline and the sub timeline\n // should ensure that the styles within are exactly the same as they were before\n context.transformIntoNewTimeline(startTime + duration);\n context.previousNode = ast;\n }\n visitQuery(ast, context) {\n // in the event that the first step before this is a style step we need\n // to ensure the styles are applied before the children are animated\n const startTime = context.currentTimeline.currentTime;\n const options = (ast.options || {});\n const delay = options.delay ? resolveTimingValue(options.delay) : 0;\n if (delay &&\n (context.previousNode.type === AnimationMetadataType.Style ||\n (startTime == 0 && context.currentTimeline.hasCurrentStyleProperties()))) {\n context.currentTimeline.snapshotCurrentStyles();\n context.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n }\n let furthestTime = startTime;\n const elms = context.invokeQuery(ast.selector, ast.originalSelector, ast.limit, ast.includeSelf, options.optional ? true : false, context.errors);\n context.currentQueryTotal = elms.length;\n let sameElementTimeline = null;\n elms.forEach((element, i) => {\n context.currentQueryIndex = i;\n const innerContext = context.createSubContext(ast.options, element);\n if (delay) {\n innerContext.delayNextStep(delay);\n }\n if (element === context.element) {\n sameElementTimeline = innerContext.currentTimeline;\n }\n visitDslNode(this, ast.animation, innerContext);\n // this is here just incase the inner steps only contain or end\n // with a style() call (which is here to signal that this is a preparatory\n // call to style an element before it is animated again)\n innerContext.currentTimeline.applyStylesToKeyframe();\n const endTime = innerContext.currentTimeline.currentTime;\n furthestTime = Math.max(furthestTime, endTime);\n });\n context.currentQueryIndex = 0;\n context.currentQueryTotal = 0;\n context.transformIntoNewTimeline(furthestTime);\n if (sameElementTimeline) {\n context.currentTimeline.mergeTimelineCollectedStyles(sameElementTimeline);\n context.currentTimeline.snapshotCurrentStyles();\n }\n context.previousNode = ast;\n }\n visitStagger(ast, context) {\n const parentContext = context.parentContext;\n const tl = context.currentTimeline;\n const timings = ast.timings;\n const duration = Math.abs(timings.duration);\n const maxTime = duration * (context.currentQueryTotal - 1);\n let delay = duration * context.currentQueryIndex;\n let staggerTransformer = timings.duration < 0 ? 'reverse' : timings.easing;\n switch (staggerTransformer) {\n case 'reverse':\n delay = maxTime - delay;\n break;\n case 'full':\n delay = parentContext.currentStaggerTime;\n break;\n }\n const timeline = context.currentTimeline;\n if (delay) {\n timeline.delayNextStep(delay);\n }\n const startingTime = timeline.currentTime;\n visitDslNode(this, ast.animation, context);\n context.previousNode = ast;\n // time = duration + delay\n // the reason why this computation is so complex is because\n // the inner timeline may either have a delay value or a stretched\n // keyframe depending on if a subtimeline is not used or is used.\n parentContext.currentStaggerTime =\n tl.currentTime - startingTime + (tl.startTime - parentContext.currentTimeline.startTime);\n }\n}\nconst DEFAULT_NOOP_PREVIOUS_NODE = {};\nclass AnimationTimelineContext {\n constructor(_driver, element, subInstructions, _enterClassName, _leaveClassName, errors, timelines, initialTimeline) {\n this._driver = _driver;\n this.element = element;\n this.subInstructions = subInstructions;\n this._enterClassName = _enterClassName;\n this._leaveClassName = _leaveClassName;\n this.errors = errors;\n this.timelines = timelines;\n this.parentContext = null;\n this.currentAnimateTimings = null;\n this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n this.subContextCount = 0;\n this.options = {};\n this.currentQueryIndex = 0;\n this.currentQueryTotal = 0;\n this.currentStaggerTime = 0;\n this.currentTimeline = initialTimeline || new TimelineBuilder(this._driver, element, 0);\n timelines.push(this.currentTimeline);\n }\n get params() {\n return this.options.params;\n }\n updateOptions(options, skipIfExists) {\n if (!options)\n return;\n const newOptions = options;\n let optionsToUpdate = this.options;\n // NOTE: this will get patched up when other animation methods support duration overrides\n if (newOptions.duration != null) {\n optionsToUpdate.duration = resolveTimingValue(newOptions.duration);\n }\n if (newOptions.delay != null) {\n optionsToUpdate.delay = resolveTimingValue(newOptions.delay);\n }\n const newParams = newOptions.params;\n if (newParams) {\n let paramsToUpdate = optionsToUpdate.params;\n if (!paramsToUpdate) {\n paramsToUpdate = this.options.params = {};\n }\n Object.keys(newParams).forEach((name) => {\n if (!skipIfExists || !paramsToUpdate.hasOwnProperty(name)) {\n paramsToUpdate[name] = interpolateParams(newParams[name], paramsToUpdate, this.errors);\n }\n });\n }\n }\n _copyOptions() {\n const options = {};\n if (this.options) {\n const oldParams = this.options.params;\n if (oldParams) {\n const params = (options['params'] = {});\n Object.keys(oldParams).forEach((name) => {\n params[name] = oldParams[name];\n });\n }\n }\n return options;\n }\n createSubContext(options = null, element, newTime) {\n const target = element || this.element;\n const context = new AnimationTimelineContext(this._driver, target, this.subInstructions, this._enterClassName, this._leaveClassName, this.errors, this.timelines, this.currentTimeline.fork(target, newTime || 0));\n context.previousNode = this.previousNode;\n context.currentAnimateTimings = this.currentAnimateTimings;\n context.options = this._copyOptions();\n context.updateOptions(options);\n context.currentQueryIndex = this.currentQueryIndex;\n context.currentQueryTotal = this.currentQueryTotal;\n context.parentContext = this;\n this.subContextCount++;\n return context;\n }\n transformIntoNewTimeline(newTime) {\n this.previousNode = DEFAULT_NOOP_PREVIOUS_NODE;\n this.currentTimeline = this.currentTimeline.fork(this.element, newTime);\n this.timelines.push(this.currentTimeline);\n return this.currentTimeline;\n }\n appendInstructionToTimeline(instruction, duration, delay) {\n const updatedTimings = {\n duration: duration != null ? duration : instruction.duration,\n delay: this.currentTimeline.currentTime + (delay != null ? delay : 0) + instruction.delay,\n easing: '',\n };\n const builder = new SubTimelineBuilder(this._driver, instruction.element, instruction.keyframes, instruction.preStyleProps, instruction.postStyleProps, updatedTimings, instruction.stretchStartingKeyframe);\n this.timelines.push(builder);\n return updatedTimings;\n }\n incrementTime(time) {\n this.currentTimeline.forwardTime(this.currentTimeline.duration + time);\n }\n delayNextStep(delay) {\n // negative delays are not yet supported\n if (delay > 0) {\n this.currentTimeline.delayNextStep(delay);\n }\n }\n invokeQuery(selector, originalSelector, limit, includeSelf, optional, errors) {\n let results = [];\n if (includeSelf) {\n results.push(this.element);\n }\n if (selector.length > 0) {\n // only if :self is used then the selector can be empty\n selector = selector.replace(ENTER_TOKEN_REGEX, '.' + this._enterClassName);\n selector = selector.replace(LEAVE_TOKEN_REGEX, '.' + this._leaveClassName);\n const multi = limit != 1;\n let elements = this._driver.query(this.element, selector, multi);\n if (limit !== 0) {\n elements =\n limit < 0\n ? elements.slice(elements.length + limit, elements.length)\n : elements.slice(0, limit);\n }\n results.push(...elements);\n }\n if (!optional && results.length == 0) {\n errors.push(invalidQuery(originalSelector));\n }\n return results;\n }\n}\nclass TimelineBuilder {\n constructor(_driver, element, startTime, _elementTimelineStylesLookup) {\n this._driver = _driver;\n this.element = element;\n this.startTime = startTime;\n this._elementTimelineStylesLookup = _elementTimelineStylesLookup;\n this.duration = 0;\n this.easing = null;\n this._previousKeyframe = new Map();\n this._currentKeyframe = new Map();\n this._keyframes = new Map();\n this._styleSummary = new Map();\n this._localTimelineStyles = new Map();\n this._pendingStyles = new Map();\n this._backFill = new Map();\n this._currentEmptyStepKeyframe = null;\n if (!this._elementTimelineStylesLookup) {\n this._elementTimelineStylesLookup = new Map();\n }\n this._globalTimelineStyles = this._elementTimelineStylesLookup.get(element);\n if (!this._globalTimelineStyles) {\n this._globalTimelineStyles = this._localTimelineStyles;\n this._elementTimelineStylesLookup.set(element, this._localTimelineStyles);\n }\n this._loadKeyframe();\n }\n containsAnimation() {\n switch (this._keyframes.size) {\n case 0:\n return false;\n case 1:\n return this.hasCurrentStyleProperties();\n default:\n return true;\n }\n }\n hasCurrentStyleProperties() {\n return this._currentKeyframe.size > 0;\n }\n get currentTime() {\n return this.startTime + this.duration;\n }\n delayNextStep(delay) {\n // in the event that a style() step is placed right before a stagger()\n // and that style() step is the very first style() value in the animation\n // then we need to make a copy of the keyframe [0, copy, 1] so that the delay\n // properly applies the style() values to work with the stagger...\n const hasPreStyleStep = this._keyframes.size === 1 && this._pendingStyles.size;\n if (this.duration || hasPreStyleStep) {\n this.forwardTime(this.currentTime + delay);\n if (hasPreStyleStep) {\n this.snapshotCurrentStyles();\n }\n }\n else {\n this.startTime += delay;\n }\n }\n fork(element, currentTime) {\n this.applyStylesToKeyframe();\n return new TimelineBuilder(this._driver, element, currentTime || this.currentTime, this._elementTimelineStylesLookup);\n }\n _loadKeyframe() {\n if (this._currentKeyframe) {\n this._previousKeyframe = this._currentKeyframe;\n }\n this._currentKeyframe = this._keyframes.get(this.duration);\n if (!this._currentKeyframe) {\n this._currentKeyframe = new Map();\n this._keyframes.set(this.duration, this._currentKeyframe);\n }\n }\n forwardFrame() {\n this.duration += ONE_FRAME_IN_MILLISECONDS;\n this._loadKeyframe();\n }\n forwardTime(time) {\n this.applyStylesToKeyframe();\n this.duration = time;\n this._loadKeyframe();\n }\n _updateStyle(prop, value) {\n this._localTimelineStyles.set(prop, value);\n this._globalTimelineStyles.set(prop, value);\n this._styleSummary.set(prop, { time: this.currentTime, value });\n }\n allowOnlyTimelineStyles() {\n return this._currentEmptyStepKeyframe !== this._currentKeyframe;\n }\n applyEmptyStep(easing) {\n if (easing) {\n this._previousKeyframe.set('easing', easing);\n }\n // special case for animate(duration):\n // all missing styles are filled with a `*` value then\n // if any destination styles are filled in later on the same\n // keyframe then they will override the overridden styles\n // We use `_globalTimelineStyles` here because there may be\n // styles in previous keyframes that are not present in this timeline\n for (let [prop, value] of this._globalTimelineStyles) {\n this._backFill.set(prop, value || AUTO_STYLE);\n this._currentKeyframe.set(prop, AUTO_STYLE);\n }\n this._currentEmptyStepKeyframe = this._currentKeyframe;\n }\n setStyles(input, easing, errors, options) {\n if (easing) {\n this._previousKeyframe.set('easing', easing);\n }\n const params = (options && options.params) || {};\n const styles = flattenStyles(input, this._globalTimelineStyles);\n for (let [prop, value] of styles) {\n const val = interpolateParams(value, params, errors);\n this._pendingStyles.set(prop, val);\n if (!this._localTimelineStyles.has(prop)) {\n this._backFill.set(prop, this._globalTimelineStyles.get(prop) ?? AUTO_STYLE);\n }\n this._updateStyle(prop, val);\n }\n }\n applyStylesToKeyframe() {\n if (this._pendingStyles.size == 0)\n return;\n this._pendingStyles.forEach((val, prop) => {\n this._currentKeyframe.set(prop, val);\n });\n this._pendingStyles.clear();\n this._localTimelineStyles.forEach((val, prop) => {\n if (!this._currentKeyframe.has(prop)) {\n this._currentKeyframe.set(prop, val);\n }\n });\n }\n snapshotCurrentStyles() {\n for (let [prop, val] of this._localTimelineStyles) {\n this._pendingStyles.set(prop, val);\n this._updateStyle(prop, val);\n }\n }\n getFinalKeyframe() {\n return this._keyframes.get(this.duration);\n }\n get properties() {\n const properties = [];\n for (let prop in this._currentKeyframe) {\n properties.push(prop);\n }\n return properties;\n }\n mergeTimelineCollectedStyles(timeline) {\n timeline._styleSummary.forEach((details1, prop) => {\n const details0 = this._styleSummary.get(prop);\n if (!details0 || details1.time > details0.time) {\n this._updateStyle(prop, details1.value);\n }\n });\n }\n buildKeyframes() {\n this.applyStylesToKeyframe();\n const preStyleProps = new Set();\n const postStyleProps = new Set();\n const isEmpty = this._keyframes.size === 1 && this.duration === 0;\n let finalKeyframes = [];\n this._keyframes.forEach((keyframe, time) => {\n const finalKeyframe = new Map([...this._backFill, ...keyframe]);\n finalKeyframe.forEach((value, prop) => {\n if (value === ɵPRE_STYLE) {\n preStyleProps.add(prop);\n }\n else if (value === AUTO_STYLE) {\n postStyleProps.add(prop);\n }\n });\n if (!isEmpty) {\n finalKeyframe.set('offset', time / this.duration);\n }\n finalKeyframes.push(finalKeyframe);\n });\n const preProps = [...preStyleProps.values()];\n const postProps = [...postStyleProps.values()];\n // special case for a 0-second animation (which is designed just to place styles onscreen)\n if (isEmpty) {\n const kf0 = finalKeyframes[0];\n const kf1 = new Map(kf0);\n kf0.set('offset', 0);\n kf1.set('offset', 1);\n finalKeyframes = [kf0, kf1];\n }\n return createTimelineInstruction(this.element, finalKeyframes, preProps, postProps, this.duration, this.startTime, this.easing, false);\n }\n}\nclass SubTimelineBuilder extends TimelineBuilder {\n constructor(driver, element, keyframes, preStyleProps, postStyleProps, timings, _stretchStartingKeyframe = false) {\n super(driver, element, timings.delay);\n this.keyframes = keyframes;\n this.preStyleProps = preStyleProps;\n this.postStyleProps = postStyleProps;\n this._stretchStartingKeyframe = _stretchStartingKeyframe;\n this.timings = { duration: timings.duration, delay: timings.delay, easing: timings.easing };\n }\n containsAnimation() {\n return this.keyframes.length > 1;\n }\n buildKeyframes() {\n let keyframes = this.keyframes;\n let { delay, duration, easing } = this.timings;\n if (this._stretchStartingKeyframe && delay) {\n const newKeyframes = [];\n const totalTime = duration + delay;\n const startingGap = delay / totalTime;\n // the original starting keyframe now starts once the delay is done\n const newFirstKeyframe = new Map(keyframes[0]);\n newFirstKeyframe.set('offset', 0);\n newKeyframes.push(newFirstKeyframe);\n const oldFirstKeyframe = new Map(keyframes[0]);\n oldFirstKeyframe.set('offset', roundOffset(startingGap));\n newKeyframes.push(oldFirstKeyframe);\n /*\n When the keyframe is stretched then it means that the delay before the animation\n starts is gone. Instead the first keyframe is placed at the start of the animation\n and it is then copied to where it starts when the original delay is over. This basically\n means nothing animates during that delay, but the styles are still rendered. For this\n to work the original offset values that exist in the original keyframes must be \"warped\"\n so that they can take the new keyframe + delay into account.\n \n delay=1000, duration=1000, keyframes = 0 .5 1\n \n turns into\n \n delay=0, duration=2000, keyframes = 0 .33 .66 1\n */\n // offsets between 1 ... n -1 are all warped by the keyframe stretch\n const limit = keyframes.length - 1;\n for (let i = 1; i <= limit; i++) {\n let kf = new Map(keyframes[i]);\n const oldOffset = kf.get('offset');\n const timeAtKeyframe = delay + oldOffset * duration;\n kf.set('offset', roundOffset(timeAtKeyframe / totalTime));\n newKeyframes.push(kf);\n }\n // the new starting keyframe should be added at the start\n duration = totalTime;\n delay = 0;\n easing = '';\n keyframes = newKeyframes;\n }\n return createTimelineInstruction(this.element, keyframes, this.preStyleProps, this.postStyleProps, duration, delay, easing, true);\n }\n}\nfunction roundOffset(offset, decimalPoints = 3) {\n const mult = Math.pow(10, decimalPoints - 1);\n return Math.round(offset * mult) / mult;\n}\nfunction flattenStyles(input, allStyles) {\n const styles = new Map();\n let allProperties;\n input.forEach((token) => {\n if (token === '*') {\n allProperties ??= allStyles.keys();\n for (let prop of allProperties) {\n styles.set(prop, AUTO_STYLE);\n }\n }\n else {\n for (let [prop, val] of token) {\n styles.set(prop, val);\n }\n }\n });\n return styles;\n}\n\nfunction createTransitionInstruction(element, triggerName, fromState, toState, isRemovalTransition, fromStyles, toStyles, timelines, queriedElements, preStyleProps, postStyleProps, totalTime, errors) {\n return {\n type: 0 /* AnimationTransitionInstructionType.TransitionAnimation */,\n element,\n triggerName,\n isRemovalTransition,\n fromState,\n fromStyles,\n toState,\n toStyles,\n timelines,\n queriedElements,\n preStyleProps,\n postStyleProps,\n totalTime,\n errors,\n };\n}\n\nconst EMPTY_OBJECT = {};\nclass AnimationTransitionFactory {\n constructor(_triggerName, ast, _stateStyles) {\n this._triggerName = _triggerName;\n this.ast = ast;\n this._stateStyles = _stateStyles;\n }\n match(currentState, nextState, element, params) {\n return oneOrMoreTransitionsMatch(this.ast.matchers, currentState, nextState, element, params);\n }\n buildStyles(stateName, params, errors) {\n let styler = this._stateStyles.get('*');\n if (stateName !== undefined) {\n styler = this._stateStyles.get(stateName?.toString()) || styler;\n }\n return styler ? styler.buildStyles(params, errors) : new Map();\n }\n build(driver, element, currentState, nextState, enterClassName, leaveClassName, currentOptions, nextOptions, subInstructions, skipAstBuild) {\n const errors = [];\n const transitionAnimationParams = (this.ast.options && this.ast.options.params) || EMPTY_OBJECT;\n const currentAnimationParams = (currentOptions && currentOptions.params) || EMPTY_OBJECT;\n const currentStateStyles = this.buildStyles(currentState, currentAnimationParams, errors);\n const nextAnimationParams = (nextOptions && nextOptions.params) || EMPTY_OBJECT;\n const nextStateStyles = this.buildStyles(nextState, nextAnimationParams, errors);\n const queriedElements = new Set();\n const preStyleMap = new Map();\n const postStyleMap = new Map();\n const isRemoval = nextState === 'void';\n const animationOptions = {\n params: applyParamDefaults(nextAnimationParams, transitionAnimationParams),\n delay: this.ast.options?.delay,\n };\n const timelines = skipAstBuild\n ? []\n : buildAnimationTimelines(driver, element, this.ast.animation, enterClassName, leaveClassName, currentStateStyles, nextStateStyles, animationOptions, subInstructions, errors);\n let totalTime = 0;\n timelines.forEach((tl) => {\n totalTime = Math.max(tl.duration + tl.delay, totalTime);\n });\n if (errors.length) {\n return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, [], [], preStyleMap, postStyleMap, totalTime, errors);\n }\n timelines.forEach((tl) => {\n const elm = tl.element;\n const preProps = getOrSetDefaultValue(preStyleMap, elm, new Set());\n tl.preStyleProps.forEach((prop) => preProps.add(prop));\n const postProps = getOrSetDefaultValue(postStyleMap, elm, new Set());\n tl.postStyleProps.forEach((prop) => postProps.add(prop));\n if (elm !== element) {\n queriedElements.add(elm);\n }\n });\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n checkNonAnimatableInTimelines(timelines, this._triggerName, driver);\n }\n return createTransitionInstruction(element, this._triggerName, currentState, nextState, isRemoval, currentStateStyles, nextStateStyles, timelines, [...queriedElements.values()], preStyleMap, postStyleMap, totalTime);\n }\n}\n/**\n * Checks inside a set of timelines if they try to animate a css property which is not considered\n * animatable, in that case it prints a warning on the console.\n * Besides that the function doesn't have any other effect.\n *\n * Note: this check is done here after the timelines are built instead of doing on a lower level so\n * that we can make sure that the warning appears only once per instruction (we can aggregate here\n * all the issues instead of finding them separately).\n *\n * @param timelines The built timelines for the current instruction.\n * @param triggerName The name of the trigger for the current instruction.\n * @param driver Animation driver used to perform the check.\n *\n */\nfunction checkNonAnimatableInTimelines(timelines, triggerName, driver) {\n if (!driver.validateAnimatableStyleProperty) {\n return;\n }\n const allowedNonAnimatableProps = new Set([\n // 'easing' is a utility/synthetic prop we use to represent\n // easing functions, it represents a property of the animation\n // which is not animatable but different values can be used\n // in different steps\n 'easing',\n ]);\n const invalidNonAnimatableProps = new Set();\n timelines.forEach(({ keyframes }) => {\n const nonAnimatablePropsInitialValues = new Map();\n keyframes.forEach((keyframe) => {\n const entriesToCheck = Array.from(keyframe.entries()).filter(([prop]) => !allowedNonAnimatableProps.has(prop));\n for (const [prop, value] of entriesToCheck) {\n if (!driver.validateAnimatableStyleProperty(prop)) {\n if (nonAnimatablePropsInitialValues.has(prop) && !invalidNonAnimatableProps.has(prop)) {\n const propInitialValue = nonAnimatablePropsInitialValues.get(prop);\n if (propInitialValue !== value) {\n invalidNonAnimatableProps.add(prop);\n }\n }\n else {\n nonAnimatablePropsInitialValues.set(prop, value);\n }\n }\n }\n });\n });\n if (invalidNonAnimatableProps.size > 0) {\n console.warn(`Warning: The animation trigger \"${triggerName}\" is attempting to animate the following` +\n ' not animatable properties: ' +\n Array.from(invalidNonAnimatableProps).join(', ') +\n '\\n' +\n '(to check the list of all animatable properties visit https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties)');\n }\n}\nfunction oneOrMoreTransitionsMatch(matchFns, currentState, nextState, element, params) {\n return matchFns.some((fn) => fn(currentState, nextState, element, params));\n}\nfunction applyParamDefaults(userParams, defaults) {\n const result = { ...defaults };\n Object.entries(userParams).forEach(([key, value]) => {\n if (value != null) {\n result[key] = value;\n }\n });\n return result;\n}\nclass AnimationStateStyles {\n constructor(styles, defaultParams, normalizer) {\n this.styles = styles;\n this.defaultParams = defaultParams;\n this.normalizer = normalizer;\n }\n buildStyles(params, errors) {\n const finalStyles = new Map();\n const combinedParams = applyParamDefaults(params, this.defaultParams);\n this.styles.styles.forEach((value) => {\n if (typeof value !== 'string') {\n value.forEach((val, prop) => {\n if (val) {\n val = interpolateParams(val, combinedParams, errors);\n }\n const normalizedProp = this.normalizer.normalizePropertyName(prop, errors);\n val = this.normalizer.normalizeStyleValue(prop, normalizedProp, val, errors);\n finalStyles.set(prop, val);\n });\n }\n });\n return finalStyles;\n }\n}\n\nfunction buildTrigger(name, ast, normalizer) {\n return new AnimationTrigger(name, ast, normalizer);\n}\nclass AnimationTrigger {\n constructor(name, ast, _normalizer) {\n this.name = name;\n this.ast = ast;\n this._normalizer = _normalizer;\n this.transitionFactories = [];\n this.states = new Map();\n ast.states.forEach((ast) => {\n const defaultParams = (ast.options && ast.options.params) || {};\n this.states.set(ast.name, new AnimationStateStyles(ast.style, defaultParams, _normalizer));\n });\n balanceProperties(this.states, 'true', '1');\n balanceProperties(this.states, 'false', '0');\n ast.transitions.forEach((ast) => {\n this.transitionFactories.push(new AnimationTransitionFactory(name, ast, this.states));\n });\n this.fallbackTransition = createFallbackTransition(name, this.states, this._normalizer);\n }\n get containsQueries() {\n return this.ast.queryCount > 0;\n }\n matchTransition(currentState, nextState, element, params) {\n const entry = this.transitionFactories.find((f) => f.match(currentState, nextState, element, params));\n return entry || null;\n }\n matchStyles(currentState, params, errors) {\n return this.fallbackTransition.buildStyles(currentState, params, errors);\n }\n}\nfunction createFallbackTransition(triggerName, states, normalizer) {\n const matchers = [(fromState, toState) => true];\n const animation = { type: AnimationMetadataType.Sequence, steps: [], options: null };\n const transition = {\n type: AnimationMetadataType.Transition,\n animation,\n matchers,\n options: null,\n queryCount: 0,\n depCount: 0,\n };\n return new AnimationTransitionFactory(triggerName, transition, states);\n}\nfunction balanceProperties(stateMap, key1, key2) {\n if (stateMap.has(key1)) {\n if (!stateMap.has(key2)) {\n stateMap.set(key2, stateMap.get(key1));\n }\n }\n else if (stateMap.has(key2)) {\n stateMap.set(key1, stateMap.get(key2));\n }\n}\n\nconst EMPTY_INSTRUCTION_MAP = new ElementInstructionMap();\nclass TimelineAnimationEngine {\n constructor(bodyNode, _driver, _normalizer) {\n this.bodyNode = bodyNode;\n this._driver = _driver;\n this._normalizer = _normalizer;\n this._animations = new Map();\n this._playersById = new Map();\n this.players = [];\n }\n register(id, metadata) {\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(this._driver, metadata, errors, warnings);\n if (errors.length) {\n throw registerFailed(errors);\n }\n else {\n if (warnings.length) {\n warnRegister(warnings);\n }\n this._animations.set(id, ast);\n }\n }\n _buildPlayer(i, preStyles, postStyles) {\n const element = i.element;\n const keyframes = normalizeKeyframes$1(this._normalizer, i.keyframes, preStyles, postStyles);\n return this._driver.animate(element, keyframes, i.duration, i.delay, i.easing, [], true);\n }\n create(id, element, options = {}) {\n const errors = [];\n const ast = this._animations.get(id);\n let instructions;\n const autoStylesMap = new Map();\n if (ast) {\n instructions = buildAnimationTimelines(this._driver, element, ast, ENTER_CLASSNAME, LEAVE_CLASSNAME, new Map(), new Map(), options, EMPTY_INSTRUCTION_MAP, errors);\n instructions.forEach((inst) => {\n const styles = getOrSetDefaultValue(autoStylesMap, inst.element, new Map());\n inst.postStyleProps.forEach((prop) => styles.set(prop, null));\n });\n }\n else {\n errors.push(missingOrDestroyedAnimation());\n instructions = [];\n }\n if (errors.length) {\n throw createAnimationFailed(errors);\n }\n autoStylesMap.forEach((styles, element) => {\n styles.forEach((_, prop) => {\n styles.set(prop, this._driver.computeStyle(element, prop, AUTO_STYLE));\n });\n });\n const players = instructions.map((i) => {\n const styles = autoStylesMap.get(i.element);\n return this._buildPlayer(i, new Map(), styles);\n });\n const player = optimizeGroupPlayer(players);\n this._playersById.set(id, player);\n player.onDestroy(() => this.destroy(id));\n this.players.push(player);\n return player;\n }\n destroy(id) {\n const player = this._getPlayer(id);\n player.destroy();\n this._playersById.delete(id);\n const index = this.players.indexOf(player);\n if (index >= 0) {\n this.players.splice(index, 1);\n }\n }\n _getPlayer(id) {\n const player = this._playersById.get(id);\n if (!player) {\n throw missingPlayer(id);\n }\n return player;\n }\n listen(id, element, eventName, callback) {\n // triggerName, fromState, toState are all ignored for timeline animations\n const baseEvent = makeAnimationEvent(element, '', '', '');\n listenOnPlayer(this._getPlayer(id), eventName, baseEvent, callback);\n return () => { };\n }\n command(id, element, command, args) {\n if (command == 'register') {\n this.register(id, args[0]);\n return;\n }\n if (command == 'create') {\n const options = (args[0] || {});\n this.create(id, element, options);\n return;\n }\n const player = this._getPlayer(id);\n switch (command) {\n case 'play':\n player.play();\n break;\n case 'pause':\n player.pause();\n break;\n case 'reset':\n player.reset();\n break;\n case 'restart':\n player.restart();\n break;\n case 'finish':\n player.finish();\n break;\n case 'init':\n player.init();\n break;\n case 'setPosition':\n player.setPosition(parseFloat(args[0]));\n break;\n case 'destroy':\n this.destroy(id);\n break;\n }\n }\n}\n\nconst QUEUED_CLASSNAME = 'ng-animate-queued';\nconst QUEUED_SELECTOR = '.ng-animate-queued';\nconst DISABLED_CLASSNAME = 'ng-animate-disabled';\nconst DISABLED_SELECTOR = '.ng-animate-disabled';\nconst STAR_CLASSNAME = 'ng-star-inserted';\nconst STAR_SELECTOR = '.ng-star-inserted';\nconst EMPTY_PLAYER_ARRAY = [];\nconst NULL_REMOVAL_STATE = {\n namespaceId: '',\n setForRemoval: false,\n setForMove: false,\n hasAnimation: false,\n removedBeforeQueried: false,\n};\nconst NULL_REMOVED_QUERIED_STATE = {\n namespaceId: '',\n setForMove: false,\n setForRemoval: false,\n hasAnimation: false,\n removedBeforeQueried: true,\n};\nconst REMOVAL_FLAG = '__ng_removed';\nclass StateValue {\n get params() {\n return this.options.params;\n }\n constructor(input, namespaceId = '') {\n this.namespaceId = namespaceId;\n const isObj = input && input.hasOwnProperty('value');\n const value = isObj ? input['value'] : input;\n this.value = normalizeTriggerValue(value);\n if (isObj) {\n // we drop the value property from options.\n const { value, ...options } = input;\n this.options = options;\n }\n else {\n this.options = {};\n }\n if (!this.options.params) {\n this.options.params = {};\n }\n }\n absorbOptions(options) {\n const newParams = options.params;\n if (newParams) {\n const oldParams = this.options.params;\n Object.keys(newParams).forEach((prop) => {\n if (oldParams[prop] == null) {\n oldParams[prop] = newParams[prop];\n }\n });\n }\n }\n}\nconst VOID_VALUE = 'void';\nconst DEFAULT_STATE_VALUE = new StateValue(VOID_VALUE);\nclass AnimationTransitionNamespace {\n constructor(id, hostElement, _engine) {\n this.id = id;\n this.hostElement = hostElement;\n this._engine = _engine;\n this.players = [];\n this._triggers = new Map();\n this._queue = [];\n this._elementListeners = new Map();\n this._hostClassName = 'ng-tns-' + id;\n addClass(hostElement, this._hostClassName);\n }\n listen(element, name, phase, callback) {\n if (!this._triggers.has(name)) {\n throw missingTrigger(phase, name);\n }\n if (phase == null || phase.length == 0) {\n throw missingEvent(name);\n }\n if (!isTriggerEventValid(phase)) {\n throw unsupportedTriggerEvent(phase, name);\n }\n const listeners = getOrSetDefaultValue(this._elementListeners, element, []);\n const data = { name, phase, callback };\n listeners.push(data);\n const triggersWithStates = getOrSetDefaultValue(this._engine.statesByElement, element, new Map());\n if (!triggersWithStates.has(name)) {\n addClass(element, NG_TRIGGER_CLASSNAME);\n addClass(element, NG_TRIGGER_CLASSNAME + '-' + name);\n triggersWithStates.set(name, DEFAULT_STATE_VALUE);\n }\n return () => {\n // the event listener is removed AFTER the flush has occurred such\n // that leave animations callbacks can fire (otherwise if the node\n // is removed in between then the listeners would be deregistered)\n this._engine.afterFlush(() => {\n const index = listeners.indexOf(data);\n if (index >= 0) {\n listeners.splice(index, 1);\n }\n if (!this._triggers.has(name)) {\n triggersWithStates.delete(name);\n }\n });\n };\n }\n register(name, ast) {\n if (this._triggers.has(name)) {\n // throw\n return false;\n }\n else {\n this._triggers.set(name, ast);\n return true;\n }\n }\n _getTrigger(name) {\n const trigger = this._triggers.get(name);\n if (!trigger) {\n throw unregisteredTrigger(name);\n }\n return trigger;\n }\n trigger(element, triggerName, value, defaultToFallback = true) {\n const trigger = this._getTrigger(triggerName);\n const player = new TransitionAnimationPlayer(this.id, triggerName, element);\n let triggersWithStates = this._engine.statesByElement.get(element);\n if (!triggersWithStates) {\n addClass(element, NG_TRIGGER_CLASSNAME);\n addClass(element, NG_TRIGGER_CLASSNAME + '-' + triggerName);\n this._engine.statesByElement.set(element, (triggersWithStates = new Map()));\n }\n let fromState = triggersWithStates.get(triggerName);\n const toState = new StateValue(value, this.id);\n const isObj = value && value.hasOwnProperty('value');\n if (!isObj && fromState) {\n toState.absorbOptions(fromState.options);\n }\n triggersWithStates.set(triggerName, toState);\n if (!fromState) {\n fromState = DEFAULT_STATE_VALUE;\n }\n const isRemoval = toState.value === VOID_VALUE;\n // normally this isn't reached by here, however, if an object expression\n // is passed in then it may be a new object each time. Comparing the value\n // is important since that will stay the same despite there being a new object.\n // The removal arc here is special cased because the same element is triggered\n // twice in the event that it contains animations on the outer/inner portions\n // of the host container\n if (!isRemoval && fromState.value === toState.value) {\n // this means that despite the value not changing, some inner params\n // have changed which means that the animation final styles need to be applied\n if (!objEquals(fromState.params, toState.params)) {\n const errors = [];\n const fromStyles = trigger.matchStyles(fromState.value, fromState.params, errors);\n const toStyles = trigger.matchStyles(toState.value, toState.params, errors);\n if (errors.length) {\n this._engine.reportError(errors);\n }\n else {\n this._engine.afterFlush(() => {\n eraseStyles(element, fromStyles);\n setStyles(element, toStyles);\n });\n }\n }\n return;\n }\n const playersOnElement = getOrSetDefaultValue(this._engine.playersByElement, element, []);\n playersOnElement.forEach((player) => {\n // only remove the player if it is queued on the EXACT same trigger/namespace\n // we only also deal with queued players here because if the animation has\n // started then we want to keep the player alive until the flush happens\n // (which is where the previousPlayers are passed into the new player)\n if (player.namespaceId == this.id && player.triggerName == triggerName && player.queued) {\n player.destroy();\n }\n });\n let transition = trigger.matchTransition(fromState.value, toState.value, element, toState.params);\n let isFallbackTransition = false;\n if (!transition) {\n if (!defaultToFallback)\n return;\n transition = trigger.fallbackTransition;\n isFallbackTransition = true;\n }\n this._engine.totalQueuedPlayers++;\n this._queue.push({\n element,\n triggerName,\n transition,\n fromState,\n toState,\n player,\n isFallbackTransition,\n });\n if (!isFallbackTransition) {\n addClass(element, QUEUED_CLASSNAME);\n player.onStart(() => {\n removeClass(element, QUEUED_CLASSNAME);\n });\n }\n player.onDone(() => {\n let index = this.players.indexOf(player);\n if (index >= 0) {\n this.players.splice(index, 1);\n }\n const players = this._engine.playersByElement.get(element);\n if (players) {\n let index = players.indexOf(player);\n if (index >= 0) {\n players.splice(index, 1);\n }\n }\n });\n this.players.push(player);\n playersOnElement.push(player);\n return player;\n }\n deregister(name) {\n this._triggers.delete(name);\n this._engine.statesByElement.forEach((stateMap) => stateMap.delete(name));\n this._elementListeners.forEach((listeners, element) => {\n this._elementListeners.set(element, listeners.filter((entry) => {\n return entry.name != name;\n }));\n });\n }\n clearElementCache(element) {\n this._engine.statesByElement.delete(element);\n this._elementListeners.delete(element);\n const elementPlayers = this._engine.playersByElement.get(element);\n if (elementPlayers) {\n elementPlayers.forEach((player) => player.destroy());\n this._engine.playersByElement.delete(element);\n }\n }\n _signalRemovalForInnerTriggers(rootElement, context) {\n const elements = this._engine.driver.query(rootElement, NG_TRIGGER_SELECTOR, true);\n // emulate a leave animation for all inner nodes within this node.\n // If there are no animations found for any of the nodes then clear the cache\n // for the element.\n elements.forEach((elm) => {\n // this means that an inner remove() operation has already kicked off\n // the animation on this element...\n if (elm[REMOVAL_FLAG])\n return;\n const namespaces = this._engine.fetchNamespacesByElement(elm);\n if (namespaces.size) {\n namespaces.forEach((ns) => ns.triggerLeaveAnimation(elm, context, false, true));\n }\n else {\n this.clearElementCache(elm);\n }\n });\n // If the child elements were removed along with the parent, their animations might not\n // have completed. Clear all the elements from the cache so we don't end up with a memory leak.\n this._engine.afterFlushAnimationsDone(() => elements.forEach((elm) => this.clearElementCache(elm)));\n }\n triggerLeaveAnimation(element, context, destroyAfterComplete, defaultToFallback) {\n const triggerStates = this._engine.statesByElement.get(element);\n const previousTriggersValues = new Map();\n if (triggerStates) {\n const players = [];\n triggerStates.forEach((state, triggerName) => {\n previousTriggersValues.set(triggerName, state.value);\n // this check is here in the event that an element is removed\n // twice (both on the host level and the component level)\n if (this._triggers.has(triggerName)) {\n const player = this.trigger(element, triggerName, VOID_VALUE, defaultToFallback);\n if (player) {\n players.push(player);\n }\n }\n });\n if (players.length) {\n this._engine.markElementAsRemoved(this.id, element, true, context, previousTriggersValues);\n if (destroyAfterComplete) {\n optimizeGroupPlayer(players).onDone(() => this._engine.processLeaveNode(element));\n }\n return true;\n }\n }\n return false;\n }\n prepareLeaveAnimationListeners(element) {\n const listeners = this._elementListeners.get(element);\n const elementStates = this._engine.statesByElement.get(element);\n // if this statement fails then it means that the element was picked up\n // by an earlier flush (or there are no listeners at all to track the leave).\n if (listeners && elementStates) {\n const visitedTriggers = new Set();\n listeners.forEach((listener) => {\n const triggerName = listener.name;\n if (visitedTriggers.has(triggerName))\n return;\n visitedTriggers.add(triggerName);\n const trigger = this._triggers.get(triggerName);\n const transition = trigger.fallbackTransition;\n const fromState = elementStates.get(triggerName) || DEFAULT_STATE_VALUE;\n const toState = new StateValue(VOID_VALUE);\n const player = new TransitionAnimationPlayer(this.id, triggerName, element);\n this._engine.totalQueuedPlayers++;\n this._queue.push({\n element,\n triggerName,\n transition,\n fromState,\n toState,\n player,\n isFallbackTransition: true,\n });\n });\n }\n }\n removeNode(element, context) {\n const engine = this._engine;\n if (element.childElementCount) {\n this._signalRemovalForInnerTriggers(element, context);\n }\n // this means that a * => VOID animation was detected and kicked off\n if (this.triggerLeaveAnimation(element, context, true))\n return;\n // find the player that is animating and make sure that the\n // removal is delayed until that player has completed\n let containsPotentialParentTransition = false;\n if (engine.totalAnimations) {\n const currentPlayers = engine.players.length\n ? engine.playersByQueriedElement.get(element)\n : [];\n // when this `if statement` does not continue forward it means that\n // a previous animation query has selected the current element and\n // is animating it. In this situation want to continue forwards and\n // allow the element to be queued up for animation later.\n if (currentPlayers && currentPlayers.length) {\n containsPotentialParentTransition = true;\n }\n else {\n let parent = element;\n while ((parent = parent.parentNode)) {\n const triggers = engine.statesByElement.get(parent);\n if (triggers) {\n containsPotentialParentTransition = true;\n break;\n }\n }\n }\n }\n // at this stage we know that the element will either get removed\n // during flush or will be picked up by a parent query. Either way\n // we need to fire the listeners for this element when it DOES get\n // removed (once the query parent animation is done or after flush)\n this.prepareLeaveAnimationListeners(element);\n // whether or not a parent has an animation we need to delay the deferral of the leave\n // operation until we have more information (which we do after flush() has been called)\n if (containsPotentialParentTransition) {\n engine.markElementAsRemoved(this.id, element, false, context);\n }\n else {\n const removalFlag = element[REMOVAL_FLAG];\n if (!removalFlag || removalFlag === NULL_REMOVAL_STATE) {\n // we do this after the flush has occurred such\n // that the callbacks can be fired\n engine.afterFlush(() => this.clearElementCache(element));\n engine.destroyInnerAnimations(element);\n engine._onRemovalComplete(element, context);\n }\n }\n }\n insertNode(element, parent) {\n addClass(element, this._hostClassName);\n }\n drainQueuedTransitions(microtaskId) {\n const instructions = [];\n this._queue.forEach((entry) => {\n const player = entry.player;\n if (player.destroyed)\n return;\n const element = entry.element;\n const listeners = this._elementListeners.get(element);\n if (listeners) {\n listeners.forEach((listener) => {\n if (listener.name == entry.triggerName) {\n const baseEvent = makeAnimationEvent(element, entry.triggerName, entry.fromState.value, entry.toState.value);\n baseEvent['_data'] = microtaskId;\n listenOnPlayer(entry.player, listener.phase, baseEvent, listener.callback);\n }\n });\n }\n if (player.markedForDestroy) {\n this._engine.afterFlush(() => {\n // now we can destroy the element properly since the event listeners have\n // been bound to the player\n player.destroy();\n });\n }\n else {\n instructions.push(entry);\n }\n });\n this._queue = [];\n return instructions.sort((a, b) => {\n // if depCount == 0 them move to front\n // otherwise if a contains b then move back\n const d0 = a.transition.ast.depCount;\n const d1 = b.transition.ast.depCount;\n if (d0 == 0 || d1 == 0) {\n return d0 - d1;\n }\n return this._engine.driver.containsElement(a.element, b.element) ? 1 : -1;\n });\n }\n destroy(context) {\n this.players.forEach((p) => p.destroy());\n this._signalRemovalForInnerTriggers(this.hostElement, context);\n }\n}\nclass TransitionAnimationEngine {\n /** @internal */\n _onRemovalComplete(element, context) {\n this.onRemovalComplete(element, context);\n }\n constructor(bodyNode, driver, _normalizer, scheduler) {\n this.bodyNode = bodyNode;\n this.driver = driver;\n this._normalizer = _normalizer;\n this.scheduler = scheduler;\n this.players = [];\n this.newHostElements = new Map();\n this.playersByElement = new Map();\n this.playersByQueriedElement = new Map();\n this.statesByElement = new Map();\n this.disabledNodes = new Set();\n this.totalAnimations = 0;\n this.totalQueuedPlayers = 0;\n this._namespaceLookup = {};\n this._namespaceList = [];\n this._flushFns = [];\n this._whenQuietFns = [];\n this.namespacesByHostElement = new Map();\n this.collectedEnterElements = [];\n this.collectedLeaveElements = [];\n // this method is designed to be overridden by the code that uses this engine\n this.onRemovalComplete = (element, context) => { };\n }\n get queuedPlayers() {\n const players = [];\n this._namespaceList.forEach((ns) => {\n ns.players.forEach((player) => {\n if (player.queued) {\n players.push(player);\n }\n });\n });\n return players;\n }\n createNamespace(namespaceId, hostElement) {\n const ns = new AnimationTransitionNamespace(namespaceId, hostElement, this);\n if (this.bodyNode && this.driver.containsElement(this.bodyNode, hostElement)) {\n this._balanceNamespaceList(ns, hostElement);\n }\n else {\n // defer this later until flush during when the host element has\n // been inserted so that we know exactly where to place it in\n // the namespace list\n this.newHostElements.set(hostElement, ns);\n // given that this host element is a part of the animation code, it\n // may or may not be inserted by a parent node that is of an\n // animation renderer type. If this happens then we can still have\n // access to this item when we query for :enter nodes. If the parent\n // is a renderer then the set data-structure will normalize the entry\n this.collectEnterElement(hostElement);\n }\n return (this._namespaceLookup[namespaceId] = ns);\n }\n _balanceNamespaceList(ns, hostElement) {\n const namespaceList = this._namespaceList;\n const namespacesByHostElement = this.namespacesByHostElement;\n const limit = namespaceList.length - 1;\n if (limit >= 0) {\n let found = false;\n // Find the closest ancestor with an existing namespace so we can then insert `ns` after it,\n // establishing a top-down ordering of namespaces in `this._namespaceList`.\n let ancestor = this.driver.getParentElement(hostElement);\n while (ancestor) {\n const ancestorNs = namespacesByHostElement.get(ancestor);\n if (ancestorNs) {\n // An animation namespace has been registered for this ancestor, so we insert `ns`\n // right after it to establish top-down ordering of animation namespaces.\n const index = namespaceList.indexOf(ancestorNs);\n namespaceList.splice(index + 1, 0, ns);\n found = true;\n break;\n }\n ancestor = this.driver.getParentElement(ancestor);\n }\n if (!found) {\n // No namespace exists that is an ancestor of `ns`, so `ns` is inserted at the front to\n // ensure that any existing descendants are ordered after `ns`, retaining the desired\n // top-down ordering.\n namespaceList.unshift(ns);\n }\n }\n else {\n namespaceList.push(ns);\n }\n namespacesByHostElement.set(hostElement, ns);\n return ns;\n }\n register(namespaceId, hostElement) {\n let ns = this._namespaceLookup[namespaceId];\n if (!ns) {\n ns = this.createNamespace(namespaceId, hostElement);\n }\n return ns;\n }\n registerTrigger(namespaceId, name, trigger) {\n let ns = this._namespaceLookup[namespaceId];\n if (ns && ns.register(name, trigger)) {\n this.totalAnimations++;\n }\n }\n destroy(namespaceId, context) {\n if (!namespaceId)\n return;\n this.afterFlush(() => { });\n this.afterFlushAnimationsDone(() => {\n const ns = this._fetchNamespace(namespaceId);\n this.namespacesByHostElement.delete(ns.hostElement);\n const index = this._namespaceList.indexOf(ns);\n if (index >= 0) {\n this._namespaceList.splice(index, 1);\n }\n ns.destroy(context);\n delete this._namespaceLookup[namespaceId];\n });\n }\n _fetchNamespace(id) {\n return this._namespaceLookup[id];\n }\n fetchNamespacesByElement(element) {\n // normally there should only be one namespace per element, however\n // if @triggers are placed on both the component element and then\n // its host element (within the component code) then there will be\n // two namespaces returned. We use a set here to simply deduplicate\n // the namespaces in case (for the reason described above) there are multiple triggers\n const namespaces = new Set();\n const elementStates = this.statesByElement.get(element);\n if (elementStates) {\n for (let stateValue of elementStates.values()) {\n if (stateValue.namespaceId) {\n const ns = this._fetchNamespace(stateValue.namespaceId);\n if (ns) {\n namespaces.add(ns);\n }\n }\n }\n }\n return namespaces;\n }\n trigger(namespaceId, element, name, value) {\n if (isElementNode(element)) {\n const ns = this._fetchNamespace(namespaceId);\n if (ns) {\n ns.trigger(element, name, value);\n return true;\n }\n }\n return false;\n }\n insertNode(namespaceId, element, parent, insertBefore) {\n if (!isElementNode(element))\n return;\n // special case for when an element is removed and reinserted (move operation)\n // when this occurs we do not want to use the element for deletion later\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n details.setForRemoval = false;\n details.setForMove = true;\n const index = this.collectedLeaveElements.indexOf(element);\n if (index >= 0) {\n this.collectedLeaveElements.splice(index, 1);\n }\n }\n // in the event that the namespaceId is blank then the caller\n // code does not contain any animation code in it, but it is\n // just being called so that the node is marked as being inserted\n if (namespaceId) {\n const ns = this._fetchNamespace(namespaceId);\n // This if-statement is a workaround for router issue #21947.\n // The router sometimes hits a race condition where while a route\n // is being instantiated a new navigation arrives, triggering leave\n // animation of DOM that has not been fully initialized, until this\n // is resolved, we need to handle the scenario when DOM is not in a\n // consistent state during the animation.\n if (ns) {\n ns.insertNode(element, parent);\n }\n }\n // only *directives and host elements are inserted before\n if (insertBefore) {\n this.collectEnterElement(element);\n }\n }\n collectEnterElement(element) {\n this.collectedEnterElements.push(element);\n }\n markElementAsDisabled(element, value) {\n if (value) {\n if (!this.disabledNodes.has(element)) {\n this.disabledNodes.add(element);\n addClass(element, DISABLED_CLASSNAME);\n }\n }\n else if (this.disabledNodes.has(element)) {\n this.disabledNodes.delete(element);\n removeClass(element, DISABLED_CLASSNAME);\n }\n }\n removeNode(namespaceId, element, context) {\n if (isElementNode(element)) {\n this.scheduler?.notify();\n const ns = namespaceId ? this._fetchNamespace(namespaceId) : null;\n if (ns) {\n ns.removeNode(element, context);\n }\n else {\n this.markElementAsRemoved(namespaceId, element, false, context);\n }\n const hostNS = this.namespacesByHostElement.get(element);\n if (hostNS && hostNS.id !== namespaceId) {\n hostNS.removeNode(element, context);\n }\n }\n else {\n this._onRemovalComplete(element, context);\n }\n }\n markElementAsRemoved(namespaceId, element, hasAnimation, context, previousTriggersValues) {\n this.collectedLeaveElements.push(element);\n element[REMOVAL_FLAG] = {\n namespaceId,\n setForRemoval: context,\n hasAnimation,\n removedBeforeQueried: false,\n previousTriggersValues,\n };\n }\n listen(namespaceId, element, name, phase, callback) {\n if (isElementNode(element)) {\n return this._fetchNamespace(namespaceId).listen(element, name, phase, callback);\n }\n return () => { };\n }\n _buildInstruction(entry, subTimelines, enterClassName, leaveClassName, skipBuildAst) {\n return entry.transition.build(this.driver, entry.element, entry.fromState.value, entry.toState.value, enterClassName, leaveClassName, entry.fromState.options, entry.toState.options, subTimelines, skipBuildAst);\n }\n destroyInnerAnimations(containerElement) {\n let elements = this.driver.query(containerElement, NG_TRIGGER_SELECTOR, true);\n elements.forEach((element) => this.destroyActiveAnimationsForElement(element));\n if (this.playersByQueriedElement.size == 0)\n return;\n elements = this.driver.query(containerElement, NG_ANIMATING_SELECTOR, true);\n elements.forEach((element) => this.finishActiveQueriedAnimationOnElement(element));\n }\n destroyActiveAnimationsForElement(element) {\n const players = this.playersByElement.get(element);\n if (players) {\n players.forEach((player) => {\n // special case for when an element is set for destruction, but hasn't started.\n // in this situation we want to delay the destruction until the flush occurs\n // so that any event listeners attached to the player are triggered.\n if (player.queued) {\n player.markedForDestroy = true;\n }\n else {\n player.destroy();\n }\n });\n }\n }\n finishActiveQueriedAnimationOnElement(element) {\n const players = this.playersByQueriedElement.get(element);\n if (players) {\n players.forEach((player) => player.finish());\n }\n }\n whenRenderingDone() {\n return new Promise((resolve) => {\n if (this.players.length) {\n return optimizeGroupPlayer(this.players).onDone(() => resolve());\n }\n else {\n resolve();\n }\n });\n }\n processLeaveNode(element) {\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n // this will prevent it from removing it twice\n element[REMOVAL_FLAG] = NULL_REMOVAL_STATE;\n if (details.namespaceId) {\n this.destroyInnerAnimations(element);\n const ns = this._fetchNamespace(details.namespaceId);\n if (ns) {\n ns.clearElementCache(element);\n }\n }\n this._onRemovalComplete(element, details.setForRemoval);\n }\n if (element.classList?.contains(DISABLED_CLASSNAME)) {\n this.markElementAsDisabled(element, false);\n }\n this.driver.query(element, DISABLED_SELECTOR, true).forEach((node) => {\n this.markElementAsDisabled(node, false);\n });\n }\n flush(microtaskId = -1) {\n let players = [];\n if (this.newHostElements.size) {\n this.newHostElements.forEach((ns, element) => this._balanceNamespaceList(ns, element));\n this.newHostElements.clear();\n }\n if (this.totalAnimations && this.collectedEnterElements.length) {\n for (let i = 0; i < this.collectedEnterElements.length; i++) {\n const elm = this.collectedEnterElements[i];\n addClass(elm, STAR_CLASSNAME);\n }\n }\n if (this._namespaceList.length &&\n (this.totalQueuedPlayers || this.collectedLeaveElements.length)) {\n const cleanupFns = [];\n try {\n players = this._flushAnimations(cleanupFns, microtaskId);\n }\n finally {\n for (let i = 0; i < cleanupFns.length; i++) {\n cleanupFns[i]();\n }\n }\n }\n else {\n for (let i = 0; i < this.collectedLeaveElements.length; i++) {\n const element = this.collectedLeaveElements[i];\n this.processLeaveNode(element);\n }\n }\n this.totalQueuedPlayers = 0;\n this.collectedEnterElements.length = 0;\n this.collectedLeaveElements.length = 0;\n this._flushFns.forEach((fn) => fn());\n this._flushFns = [];\n if (this._whenQuietFns.length) {\n // we move these over to a variable so that\n // if any new callbacks are registered in another\n // flush they do not populate the existing set\n const quietFns = this._whenQuietFns;\n this._whenQuietFns = [];\n if (players.length) {\n optimizeGroupPlayer(players).onDone(() => {\n quietFns.forEach((fn) => fn());\n });\n }\n else {\n quietFns.forEach((fn) => fn());\n }\n }\n }\n reportError(errors) {\n throw triggerTransitionsFailed(errors);\n }\n _flushAnimations(cleanupFns, microtaskId) {\n const subTimelines = new ElementInstructionMap();\n const skippedPlayers = [];\n const skippedPlayersMap = new Map();\n const queuedInstructions = [];\n const queriedElements = new Map();\n const allPreStyleElements = new Map();\n const allPostStyleElements = new Map();\n const disabledElementsSet = new Set();\n this.disabledNodes.forEach((node) => {\n disabledElementsSet.add(node);\n const nodesThatAreDisabled = this.driver.query(node, QUEUED_SELECTOR, true);\n for (let i = 0; i < nodesThatAreDisabled.length; i++) {\n disabledElementsSet.add(nodesThatAreDisabled[i]);\n }\n });\n const bodyNode = this.bodyNode;\n const allTriggerElements = Array.from(this.statesByElement.keys());\n const enterNodeMap = buildRootMap(allTriggerElements, this.collectedEnterElements);\n // this must occur before the instructions are built below such that\n // the :enter queries match the elements (since the timeline queries\n // are fired during instruction building).\n const enterNodeMapIds = new Map();\n let i = 0;\n enterNodeMap.forEach((nodes, root) => {\n const className = ENTER_CLASSNAME + i++;\n enterNodeMapIds.set(root, className);\n nodes.forEach((node) => addClass(node, className));\n });\n const allLeaveNodes = [];\n const mergedLeaveNodes = new Set();\n const leaveNodesWithoutAnimations = new Set();\n for (let i = 0; i < this.collectedLeaveElements.length; i++) {\n const element = this.collectedLeaveElements[i];\n const details = element[REMOVAL_FLAG];\n if (details && details.setForRemoval) {\n allLeaveNodes.push(element);\n mergedLeaveNodes.add(element);\n if (details.hasAnimation) {\n this.driver\n .query(element, STAR_SELECTOR, true)\n .forEach((elm) => mergedLeaveNodes.add(elm));\n }\n else {\n leaveNodesWithoutAnimations.add(element);\n }\n }\n }\n const leaveNodeMapIds = new Map();\n const leaveNodeMap = buildRootMap(allTriggerElements, Array.from(mergedLeaveNodes));\n leaveNodeMap.forEach((nodes, root) => {\n const className = LEAVE_CLASSNAME + i++;\n leaveNodeMapIds.set(root, className);\n nodes.forEach((node) => addClass(node, className));\n });\n cleanupFns.push(() => {\n enterNodeMap.forEach((nodes, root) => {\n const className = enterNodeMapIds.get(root);\n nodes.forEach((node) => removeClass(node, className));\n });\n leaveNodeMap.forEach((nodes, root) => {\n const className = leaveNodeMapIds.get(root);\n nodes.forEach((node) => removeClass(node, className));\n });\n allLeaveNodes.forEach((element) => {\n this.processLeaveNode(element);\n });\n });\n const allPlayers = [];\n const erroneousTransitions = [];\n for (let i = this._namespaceList.length - 1; i >= 0; i--) {\n const ns = this._namespaceList[i];\n ns.drainQueuedTransitions(microtaskId).forEach((entry) => {\n const player = entry.player;\n const element = entry.element;\n allPlayers.push(player);\n if (this.collectedEnterElements.length) {\n const details = element[REMOVAL_FLAG];\n // animations for move operations (elements being removed and reinserted,\n // e.g. when the order of an *ngFor list changes) are currently not supported\n if (details && details.setForMove) {\n if (details.previousTriggersValues &&\n details.previousTriggersValues.has(entry.triggerName)) {\n const previousValue = details.previousTriggersValues.get(entry.triggerName);\n // we need to restore the previous trigger value since the element has\n // only been moved and hasn't actually left the DOM\n const triggersWithStates = this.statesByElement.get(entry.element);\n if (triggersWithStates && triggersWithStates.has(entry.triggerName)) {\n const state = triggersWithStates.get(entry.triggerName);\n state.value = previousValue;\n triggersWithStates.set(entry.triggerName, state);\n }\n }\n player.destroy();\n return;\n }\n }\n const nodeIsOrphaned = !bodyNode || !this.driver.containsElement(bodyNode, element);\n const leaveClassName = leaveNodeMapIds.get(element);\n const enterClassName = enterNodeMapIds.get(element);\n const instruction = this._buildInstruction(entry, subTimelines, enterClassName, leaveClassName, nodeIsOrphaned);\n if (instruction.errors && instruction.errors.length) {\n erroneousTransitions.push(instruction);\n return;\n }\n // even though the element may not be in the DOM, it may still\n // be added at a later point (due to the mechanics of content\n // projection and/or dynamic component insertion) therefore it's\n // important to still style the element.\n if (nodeIsOrphaned) {\n player.onStart(() => eraseStyles(element, instruction.fromStyles));\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n skippedPlayers.push(player);\n return;\n }\n // if an unmatched transition is queued and ready to go\n // then it SHOULD NOT render an animation and cancel the\n // previously running animations.\n if (entry.isFallbackTransition) {\n player.onStart(() => eraseStyles(element, instruction.fromStyles));\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n skippedPlayers.push(player);\n return;\n }\n // this means that if a parent animation uses this animation as a sub-trigger\n // then it will instruct the timeline builder not to add a player delay, but\n // instead stretch the first keyframe gap until the animation starts. This is\n // important in order to prevent extra initialization styles from being\n // required by the user for the animation.\n const timelines = [];\n instruction.timelines.forEach((tl) => {\n tl.stretchStartingKeyframe = true;\n if (!this.disabledNodes.has(tl.element)) {\n timelines.push(tl);\n }\n });\n instruction.timelines = timelines;\n subTimelines.append(element, instruction.timelines);\n const tuple = { instruction, player, element };\n queuedInstructions.push(tuple);\n instruction.queriedElements.forEach((element) => getOrSetDefaultValue(queriedElements, element, []).push(player));\n instruction.preStyleProps.forEach((stringMap, element) => {\n if (stringMap.size) {\n let setVal = allPreStyleElements.get(element);\n if (!setVal) {\n allPreStyleElements.set(element, (setVal = new Set()));\n }\n stringMap.forEach((_, prop) => setVal.add(prop));\n }\n });\n instruction.postStyleProps.forEach((stringMap, element) => {\n let setVal = allPostStyleElements.get(element);\n if (!setVal) {\n allPostStyleElements.set(element, (setVal = new Set()));\n }\n stringMap.forEach((_, prop) => setVal.add(prop));\n });\n });\n }\n if (erroneousTransitions.length) {\n const errors = [];\n erroneousTransitions.forEach((instruction) => {\n errors.push(transitionFailed(instruction.triggerName, instruction.errors));\n });\n allPlayers.forEach((player) => player.destroy());\n this.reportError(errors);\n }\n const allPreviousPlayersMap = new Map();\n // this map tells us which element in the DOM tree is contained by\n // which animation. Further down this map will get populated once\n // the players are built and in doing so we can use it to efficiently\n // figure out if a sub player is skipped due to a parent player having priority.\n const animationElementMap = new Map();\n queuedInstructions.forEach((entry) => {\n const element = entry.element;\n if (subTimelines.has(element)) {\n animationElementMap.set(element, element);\n this._beforeAnimationBuild(entry.player.namespaceId, entry.instruction, allPreviousPlayersMap);\n }\n });\n skippedPlayers.forEach((player) => {\n const element = player.element;\n const previousPlayers = this._getPreviousPlayers(element, false, player.namespaceId, player.triggerName, null);\n previousPlayers.forEach((prevPlayer) => {\n getOrSetDefaultValue(allPreviousPlayersMap, element, []).push(prevPlayer);\n prevPlayer.destroy();\n });\n });\n // this is a special case for nodes that will be removed either by\n // having their own leave animations or by being queried in a container\n // that will be removed once a parent animation is complete. The idea\n // here is that * styles must be identical to ! styles because of\n // backwards compatibility (* is also filled in by default in many places).\n // Otherwise * styles will return an empty value or \"auto\" since the element\n // passed to getComputedStyle will not be visible (since * === destination)\n const replaceNodes = allLeaveNodes.filter((node) => {\n return replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements);\n });\n // POST STAGE: fill the * styles\n const postStylesMap = new Map();\n const allLeaveQueriedNodes = cloakAndComputeStyles(postStylesMap, this.driver, leaveNodesWithoutAnimations, allPostStyleElements, AUTO_STYLE);\n allLeaveQueriedNodes.forEach((node) => {\n if (replacePostStylesAsPre(node, allPreStyleElements, allPostStyleElements)) {\n replaceNodes.push(node);\n }\n });\n // PRE STAGE: fill the ! styles\n const preStylesMap = new Map();\n enterNodeMap.forEach((nodes, root) => {\n cloakAndComputeStyles(preStylesMap, this.driver, new Set(nodes), allPreStyleElements, ɵPRE_STYLE);\n });\n replaceNodes.forEach((node) => {\n const post = postStylesMap.get(node);\n const pre = preStylesMap.get(node);\n postStylesMap.set(node, new Map([...(post?.entries() ?? []), ...(pre?.entries() ?? [])]));\n });\n const rootPlayers = [];\n const subPlayers = [];\n const NO_PARENT_ANIMATION_ELEMENT_DETECTED = {};\n queuedInstructions.forEach((entry) => {\n const { element, player, instruction } = entry;\n // this means that it was never consumed by a parent animation which\n // means that it is independent and therefore should be set for animation\n if (subTimelines.has(element)) {\n if (disabledElementsSet.has(element)) {\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n player.disabled = true;\n player.overrideTotalTime(instruction.totalTime);\n skippedPlayers.push(player);\n return;\n }\n // this will flow up the DOM and query the map to figure out\n // if a parent animation has priority over it. In the situation\n // that a parent is detected then it will cancel the loop. If\n // nothing is detected, or it takes a few hops to find a parent,\n // then it will fill in the missing nodes and signal them as having\n // a detected parent (or a NO_PARENT value via a special constant).\n let parentWithAnimation = NO_PARENT_ANIMATION_ELEMENT_DETECTED;\n if (animationElementMap.size > 1) {\n let elm = element;\n const parentsToAdd = [];\n while ((elm = elm.parentNode)) {\n const detectedParent = animationElementMap.get(elm);\n if (detectedParent) {\n parentWithAnimation = detectedParent;\n break;\n }\n parentsToAdd.push(elm);\n }\n parentsToAdd.forEach((parent) => animationElementMap.set(parent, parentWithAnimation));\n }\n const innerPlayer = this._buildAnimation(player.namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap);\n player.setRealPlayer(innerPlayer);\n if (parentWithAnimation === NO_PARENT_ANIMATION_ELEMENT_DETECTED) {\n rootPlayers.push(player);\n }\n else {\n const parentPlayers = this.playersByElement.get(parentWithAnimation);\n if (parentPlayers && parentPlayers.length) {\n player.parentPlayer = optimizeGroupPlayer(parentPlayers);\n }\n skippedPlayers.push(player);\n }\n }\n else {\n eraseStyles(element, instruction.fromStyles);\n player.onDestroy(() => setStyles(element, instruction.toStyles));\n // there still might be a ancestor player animating this\n // element therefore we will still add it as a sub player\n // even if its animation may be disabled\n subPlayers.push(player);\n if (disabledElementsSet.has(element)) {\n skippedPlayers.push(player);\n }\n }\n });\n // find all of the sub players' corresponding inner animation players\n subPlayers.forEach((player) => {\n // even if no players are found for a sub animation it\n // will still complete itself after the next tick since it's Noop\n const playersForElement = skippedPlayersMap.get(player.element);\n if (playersForElement && playersForElement.length) {\n const innerPlayer = optimizeGroupPlayer(playersForElement);\n player.setRealPlayer(innerPlayer);\n }\n });\n // the reason why we don't actually play the animation is\n // because all that a skipped player is designed to do is to\n // fire the start/done transition callback events\n skippedPlayers.forEach((player) => {\n if (player.parentPlayer) {\n player.syncPlayerEvents(player.parentPlayer);\n }\n else {\n player.destroy();\n }\n });\n // run through all of the queued removals and see if they\n // were picked up by a query. If not then perform the removal\n // operation right away unless a parent animation is ongoing.\n for (let i = 0; i < allLeaveNodes.length; i++) {\n const element = allLeaveNodes[i];\n const details = element[REMOVAL_FLAG];\n removeClass(element, LEAVE_CLASSNAME);\n // this means the element has a removal animation that is being\n // taken care of and therefore the inner elements will hang around\n // until that animation is over (or the parent queried animation)\n if (details && details.hasAnimation)\n continue;\n let players = [];\n // if this element is queried or if it contains queried children\n // then we want for the element not to be removed from the page\n // until the queried animations have finished\n if (queriedElements.size) {\n let queriedPlayerResults = queriedElements.get(element);\n if (queriedPlayerResults && queriedPlayerResults.length) {\n players.push(...queriedPlayerResults);\n }\n let queriedInnerElements = this.driver.query(element, NG_ANIMATING_SELECTOR, true);\n for (let j = 0; j < queriedInnerElements.length; j++) {\n let queriedPlayers = queriedElements.get(queriedInnerElements[j]);\n if (queriedPlayers && queriedPlayers.length) {\n players.push(...queriedPlayers);\n }\n }\n }\n const activePlayers = players.filter((p) => !p.destroyed);\n if (activePlayers.length) {\n removeNodesAfterAnimationDone(this, element, activePlayers);\n }\n else {\n this.processLeaveNode(element);\n }\n }\n // this is required so the cleanup method doesn't remove them\n allLeaveNodes.length = 0;\n rootPlayers.forEach((player) => {\n this.players.push(player);\n player.onDone(() => {\n player.destroy();\n const index = this.players.indexOf(player);\n this.players.splice(index, 1);\n });\n player.play();\n });\n return rootPlayers;\n }\n afterFlush(callback) {\n this._flushFns.push(callback);\n }\n afterFlushAnimationsDone(callback) {\n this._whenQuietFns.push(callback);\n }\n _getPreviousPlayers(element, isQueriedElement, namespaceId, triggerName, toStateValue) {\n let players = [];\n if (isQueriedElement) {\n const queriedElementPlayers = this.playersByQueriedElement.get(element);\n if (queriedElementPlayers) {\n players = queriedElementPlayers;\n }\n }\n else {\n const elementPlayers = this.playersByElement.get(element);\n if (elementPlayers) {\n const isRemovalAnimation = !toStateValue || toStateValue == VOID_VALUE;\n elementPlayers.forEach((player) => {\n if (player.queued)\n return;\n if (!isRemovalAnimation && player.triggerName != triggerName)\n return;\n players.push(player);\n });\n }\n }\n if (namespaceId || triggerName) {\n players = players.filter((player) => {\n if (namespaceId && namespaceId != player.namespaceId)\n return false;\n if (triggerName && triggerName != player.triggerName)\n return false;\n return true;\n });\n }\n return players;\n }\n _beforeAnimationBuild(namespaceId, instruction, allPreviousPlayersMap) {\n const triggerName = instruction.triggerName;\n const rootElement = instruction.element;\n // when a removal animation occurs, ALL previous players are collected\n // and destroyed (even if they are outside of the current namespace)\n const targetNameSpaceId = instruction.isRemovalTransition\n ? undefined\n : namespaceId;\n const targetTriggerName = instruction.isRemovalTransition\n ? undefined\n : triggerName;\n for (const timelineInstruction of instruction.timelines) {\n const element = timelineInstruction.element;\n const isQueriedElement = element !== rootElement;\n const players = getOrSetDefaultValue(allPreviousPlayersMap, element, []);\n const previousPlayers = this._getPreviousPlayers(element, isQueriedElement, targetNameSpaceId, targetTriggerName, instruction.toState);\n previousPlayers.forEach((player) => {\n const realPlayer = player.getRealPlayer();\n if (realPlayer.beforeDestroy) {\n realPlayer.beforeDestroy();\n }\n player.destroy();\n players.push(player);\n });\n }\n // this needs to be done so that the PRE/POST styles can be\n // computed properly without interfering with the previous animation\n eraseStyles(rootElement, instruction.fromStyles);\n }\n _buildAnimation(namespaceId, instruction, allPreviousPlayersMap, skippedPlayersMap, preStylesMap, postStylesMap) {\n const triggerName = instruction.triggerName;\n const rootElement = instruction.element;\n // we first run this so that the previous animation player\n // data can be passed into the successive animation players\n const allQueriedPlayers = [];\n const allConsumedElements = new Set();\n const allSubElements = new Set();\n const allNewPlayers = instruction.timelines.map((timelineInstruction) => {\n const element = timelineInstruction.element;\n allConsumedElements.add(element);\n // FIXME (matsko): make sure to-be-removed animations are removed properly\n const details = element[REMOVAL_FLAG];\n if (details && details.removedBeforeQueried)\n return new NoopAnimationPlayer(timelineInstruction.duration, timelineInstruction.delay);\n const isQueriedElement = element !== rootElement;\n const previousPlayers = flattenGroupPlayers((allPreviousPlayersMap.get(element) || EMPTY_PLAYER_ARRAY).map((p) => p.getRealPlayer())).filter((p) => {\n // the `element` is not apart of the AnimationPlayer definition, but\n // Mock/WebAnimations\n // use the element within their implementation. This will be added in Angular5 to\n // AnimationPlayer\n const pp = p;\n return pp.element ? pp.element === element : false;\n });\n const preStyles = preStylesMap.get(element);\n const postStyles = postStylesMap.get(element);\n const keyframes = normalizeKeyframes$1(this._normalizer, timelineInstruction.keyframes, preStyles, postStyles);\n const player = this._buildPlayer(timelineInstruction, keyframes, previousPlayers);\n // this means that this particular player belongs to a sub trigger. It is\n // important that we match this player up with the corresponding (@trigger.listener)\n if (timelineInstruction.subTimeline && skippedPlayersMap) {\n allSubElements.add(element);\n }\n if (isQueriedElement) {\n const wrappedPlayer = new TransitionAnimationPlayer(namespaceId, triggerName, element);\n wrappedPlayer.setRealPlayer(player);\n allQueriedPlayers.push(wrappedPlayer);\n }\n return player;\n });\n allQueriedPlayers.forEach((player) => {\n getOrSetDefaultValue(this.playersByQueriedElement, player.element, []).push(player);\n player.onDone(() => deleteOrUnsetInMap(this.playersByQueriedElement, player.element, player));\n });\n allConsumedElements.forEach((element) => addClass(element, NG_ANIMATING_CLASSNAME));\n const player = optimizeGroupPlayer(allNewPlayers);\n player.onDestroy(() => {\n allConsumedElements.forEach((element) => removeClass(element, NG_ANIMATING_CLASSNAME));\n setStyles(rootElement, instruction.toStyles);\n });\n // this basically makes all of the callbacks for sub element animations\n // be dependent on the upper players for when they finish\n allSubElements.forEach((element) => {\n getOrSetDefaultValue(skippedPlayersMap, element, []).push(player);\n });\n return player;\n }\n _buildPlayer(instruction, keyframes, previousPlayers) {\n if (keyframes.length > 0) {\n return this.driver.animate(instruction.element, keyframes, instruction.duration, instruction.delay, instruction.easing, previousPlayers);\n }\n // special case for when an empty transition|definition is provided\n // ... there is no point in rendering an empty animation\n return new NoopAnimationPlayer(instruction.duration, instruction.delay);\n }\n}\nclass TransitionAnimationPlayer {\n constructor(namespaceId, triggerName, element) {\n this.namespaceId = namespaceId;\n this.triggerName = triggerName;\n this.element = element;\n this._player = new NoopAnimationPlayer();\n this._containsRealPlayer = false;\n this._queuedCallbacks = new Map();\n this.destroyed = false;\n this.parentPlayer = null;\n this.markedForDestroy = false;\n this.disabled = false;\n this.queued = true;\n this.totalTime = 0;\n }\n setRealPlayer(player) {\n if (this._containsRealPlayer)\n return;\n this._player = player;\n this._queuedCallbacks.forEach((callbacks, phase) => {\n callbacks.forEach((callback) => listenOnPlayer(player, phase, undefined, callback));\n });\n this._queuedCallbacks.clear();\n this._containsRealPlayer = true;\n this.overrideTotalTime(player.totalTime);\n this.queued = false;\n }\n getRealPlayer() {\n return this._player;\n }\n overrideTotalTime(totalTime) {\n this.totalTime = totalTime;\n }\n syncPlayerEvents(player) {\n const p = this._player;\n if (p.triggerCallback) {\n player.onStart(() => p.triggerCallback('start'));\n }\n player.onDone(() => this.finish());\n player.onDestroy(() => this.destroy());\n }\n _queueEvent(name, callback) {\n getOrSetDefaultValue(this._queuedCallbacks, name, []).push(callback);\n }\n onDone(fn) {\n if (this.queued) {\n this._queueEvent('done', fn);\n }\n this._player.onDone(fn);\n }\n onStart(fn) {\n if (this.queued) {\n this._queueEvent('start', fn);\n }\n this._player.onStart(fn);\n }\n onDestroy(fn) {\n if (this.queued) {\n this._queueEvent('destroy', fn);\n }\n this._player.onDestroy(fn);\n }\n init() {\n this._player.init();\n }\n hasStarted() {\n return this.queued ? false : this._player.hasStarted();\n }\n play() {\n !this.queued && this._player.play();\n }\n pause() {\n !this.queued && this._player.pause();\n }\n restart() {\n !this.queued && this._player.restart();\n }\n finish() {\n this._player.finish();\n }\n destroy() {\n this.destroyed = true;\n this._player.destroy();\n }\n reset() {\n !this.queued && this._player.reset();\n }\n setPosition(p) {\n if (!this.queued) {\n this._player.setPosition(p);\n }\n }\n getPosition() {\n return this.queued ? 0 : this._player.getPosition();\n }\n /** @internal */\n triggerCallback(phaseName) {\n const p = this._player;\n if (p.triggerCallback) {\n p.triggerCallback(phaseName);\n }\n }\n}\nfunction deleteOrUnsetInMap(map, key, value) {\n let currentValues = map.get(key);\n if (currentValues) {\n if (currentValues.length) {\n const index = currentValues.indexOf(value);\n currentValues.splice(index, 1);\n }\n if (currentValues.length == 0) {\n map.delete(key);\n }\n }\n return currentValues;\n}\nfunction normalizeTriggerValue(value) {\n // we use `!= null` here because it's the most simple\n // way to test against a \"falsy\" value without mixing\n // in empty strings or a zero value. DO NOT OPTIMIZE.\n return value != null ? value : null;\n}\nfunction isElementNode(node) {\n return node && node['nodeType'] === 1;\n}\nfunction isTriggerEventValid(eventName) {\n return eventName == 'start' || eventName == 'done';\n}\nfunction cloakElement(element, value) {\n const oldValue = element.style.display;\n element.style.display = value != null ? value : 'none';\n return oldValue;\n}\nfunction cloakAndComputeStyles(valuesMap, driver, elements, elementPropsMap, defaultStyle) {\n const cloakVals = [];\n elements.forEach((element) => cloakVals.push(cloakElement(element)));\n const failedElements = [];\n elementPropsMap.forEach((props, element) => {\n const styles = new Map();\n props.forEach((prop) => {\n const value = driver.computeStyle(element, prop, defaultStyle);\n styles.set(prop, value);\n // there is no easy way to detect this because a sub element could be removed\n // by a parent animation element being detached.\n if (!value || value.length == 0) {\n element[REMOVAL_FLAG] = NULL_REMOVED_QUERIED_STATE;\n failedElements.push(element);\n }\n });\n valuesMap.set(element, styles);\n });\n // we use a index variable here since Set.forEach(a, i) does not return\n // an index value for the closure (but instead just the value)\n let i = 0;\n elements.forEach((element) => cloakElement(element, cloakVals[i++]));\n return failedElements;\n}\n/*\nSince the Angular renderer code will return a collection of inserted\nnodes in all areas of a DOM tree, it's up to this algorithm to figure\nout which nodes are roots for each animation @trigger.\n\nBy placing each inserted node into a Set and traversing upwards, it\nis possible to find the @trigger elements and well any direct *star\ninsertion nodes, if a @trigger root is found then the enter element\nis placed into the Map[@trigger] spot.\n */\nfunction buildRootMap(roots, nodes) {\n const rootMap = new Map();\n roots.forEach((root) => rootMap.set(root, []));\n if (nodes.length == 0)\n return rootMap;\n const NULL_NODE = 1;\n const nodeSet = new Set(nodes);\n const localRootMap = new Map();\n function getRoot(node) {\n if (!node)\n return NULL_NODE;\n let root = localRootMap.get(node);\n if (root)\n return root;\n const parent = node.parentNode;\n if (rootMap.has(parent)) {\n // ngIf inside @trigger\n root = parent;\n }\n else if (nodeSet.has(parent)) {\n // ngIf inside ngIf\n root = NULL_NODE;\n }\n else {\n // recurse upwards\n root = getRoot(parent);\n }\n localRootMap.set(node, root);\n return root;\n }\n nodes.forEach((node) => {\n const root = getRoot(node);\n if (root !== NULL_NODE) {\n rootMap.get(root).push(node);\n }\n });\n return rootMap;\n}\nfunction addClass(element, className) {\n element.classList?.add(className);\n}\nfunction removeClass(element, className) {\n element.classList?.remove(className);\n}\nfunction removeNodesAfterAnimationDone(engine, element, players) {\n optimizeGroupPlayer(players).onDone(() => engine.processLeaveNode(element));\n}\nfunction flattenGroupPlayers(players) {\n const finalPlayers = [];\n _flattenGroupPlayersRecur(players, finalPlayers);\n return finalPlayers;\n}\nfunction _flattenGroupPlayersRecur(players, finalPlayers) {\n for (let i = 0; i < players.length; i++) {\n const player = players[i];\n if (player instanceof ɵAnimationGroupPlayer) {\n _flattenGroupPlayersRecur(player.players, finalPlayers);\n }\n else {\n finalPlayers.push(player);\n }\n }\n}\nfunction objEquals(a, b) {\n const k1 = Object.keys(a);\n const k2 = Object.keys(b);\n if (k1.length != k2.length)\n return false;\n for (let i = 0; i < k1.length; i++) {\n const prop = k1[i];\n if (!b.hasOwnProperty(prop) || a[prop] !== b[prop])\n return false;\n }\n return true;\n}\nfunction replacePostStylesAsPre(element, allPreStyleElements, allPostStyleElements) {\n const postEntry = allPostStyleElements.get(element);\n if (!postEntry)\n return false;\n let preEntry = allPreStyleElements.get(element);\n if (preEntry) {\n postEntry.forEach((data) => preEntry.add(data));\n }\n else {\n allPreStyleElements.set(element, postEntry);\n }\n allPostStyleElements.delete(element);\n return true;\n}\n\nclass AnimationEngine {\n constructor(doc, _driver, _normalizer, scheduler) {\n this._driver = _driver;\n this._normalizer = _normalizer;\n this._triggerCache = {};\n // this method is designed to be overridden by the code that uses this engine\n this.onRemovalComplete = (element, context) => { };\n this._transitionEngine = new TransitionAnimationEngine(doc.body, _driver, _normalizer, scheduler);\n this._timelineEngine = new TimelineAnimationEngine(doc.body, _driver, _normalizer);\n this._transitionEngine.onRemovalComplete = (element, context) => this.onRemovalComplete(element, context);\n }\n registerTrigger(componentId, namespaceId, hostElement, name, metadata) {\n const cacheKey = componentId + '-' + name;\n let trigger = this._triggerCache[cacheKey];\n if (!trigger) {\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(this._driver, metadata, errors, warnings);\n if (errors.length) {\n throw triggerBuildFailed(name, errors);\n }\n if (warnings.length) {\n warnTriggerBuild(name, warnings);\n }\n trigger = buildTrigger(name, ast, this._normalizer);\n this._triggerCache[cacheKey] = trigger;\n }\n this._transitionEngine.registerTrigger(namespaceId, name, trigger);\n }\n register(namespaceId, hostElement) {\n this._transitionEngine.register(namespaceId, hostElement);\n }\n destroy(namespaceId, context) {\n this._transitionEngine.destroy(namespaceId, context);\n }\n onInsert(namespaceId, element, parent, insertBefore) {\n this._transitionEngine.insertNode(namespaceId, element, parent, insertBefore);\n }\n onRemove(namespaceId, element, context) {\n this._transitionEngine.removeNode(namespaceId, element, context);\n }\n disableAnimations(element, disable) {\n this._transitionEngine.markElementAsDisabled(element, disable);\n }\n process(namespaceId, element, property, value) {\n if (property.charAt(0) == '@') {\n const [id, action] = parseTimelineCommand(property);\n const args = value;\n this._timelineEngine.command(id, element, action, args);\n }\n else {\n this._transitionEngine.trigger(namespaceId, element, property, value);\n }\n }\n listen(namespaceId, element, eventName, eventPhase, callback) {\n // @@listen\n if (eventName.charAt(0) == '@') {\n const [id, action] = parseTimelineCommand(eventName);\n return this._timelineEngine.listen(id, element, action, callback);\n }\n return this._transitionEngine.listen(namespaceId, element, eventName, eventPhase, callback);\n }\n flush(microtaskId = -1) {\n this._transitionEngine.flush(microtaskId);\n }\n get players() {\n return [...this._transitionEngine.players, ...this._timelineEngine.players];\n }\n whenRenderingDone() {\n return this._transitionEngine.whenRenderingDone();\n }\n afterFlushAnimationsDone(cb) {\n this._transitionEngine.afterFlushAnimationsDone(cb);\n }\n}\n\n/**\n * Returns an instance of `SpecialCasedStyles` if and when any special (non animateable) styles are\n * detected.\n *\n * In CSS there exist properties that cannot be animated within a keyframe animation\n * (whether it be via CSS keyframes or web-animations) and the animation implementation\n * will ignore them. This function is designed to detect those special cased styles and\n * return a container that will be executed at the start and end of the animation.\n *\n * @returns an instance of `SpecialCasedStyles` if any special styles are detected otherwise `null`\n */\nfunction packageNonAnimatableStyles(element, styles) {\n let startStyles = null;\n let endStyles = null;\n if (Array.isArray(styles) && styles.length) {\n startStyles = filterNonAnimatableStyles(styles[0]);\n if (styles.length > 1) {\n endStyles = filterNonAnimatableStyles(styles[styles.length - 1]);\n }\n }\n else if (styles instanceof Map) {\n startStyles = filterNonAnimatableStyles(styles);\n }\n return startStyles || endStyles ? new SpecialCasedStyles(element, startStyles, endStyles) : null;\n}\n/**\n * Designed to be executed during a keyframe-based animation to apply any special-cased styles.\n *\n * When started (when the `start()` method is run) then the provided `startStyles`\n * will be applied. When finished (when the `finish()` method is called) the\n * `endStyles` will be applied as well any any starting styles. Finally when\n * `destroy()` is called then all styles will be removed.\n */\nclass SpecialCasedStyles {\n static { this.initialStylesByElement = new WeakMap(); }\n constructor(_element, _startStyles, _endStyles) {\n this._element = _element;\n this._startStyles = _startStyles;\n this._endStyles = _endStyles;\n this._state = 0 /* SpecialCasedStylesState.Pending */;\n let initialStyles = SpecialCasedStyles.initialStylesByElement.get(_element);\n if (!initialStyles) {\n SpecialCasedStyles.initialStylesByElement.set(_element, (initialStyles = new Map()));\n }\n this._initialStyles = initialStyles;\n }\n start() {\n if (this._state < 1 /* SpecialCasedStylesState.Started */) {\n if (this._startStyles) {\n setStyles(this._element, this._startStyles, this._initialStyles);\n }\n this._state = 1 /* SpecialCasedStylesState.Started */;\n }\n }\n finish() {\n this.start();\n if (this._state < 2 /* SpecialCasedStylesState.Finished */) {\n setStyles(this._element, this._initialStyles);\n if (this._endStyles) {\n setStyles(this._element, this._endStyles);\n this._endStyles = null;\n }\n this._state = 1 /* SpecialCasedStylesState.Started */;\n }\n }\n destroy() {\n this.finish();\n if (this._state < 3 /* SpecialCasedStylesState.Destroyed */) {\n SpecialCasedStyles.initialStylesByElement.delete(this._element);\n if (this._startStyles) {\n eraseStyles(this._element, this._startStyles);\n this._endStyles = null;\n }\n if (this._endStyles) {\n eraseStyles(this._element, this._endStyles);\n this._endStyles = null;\n }\n setStyles(this._element, this._initialStyles);\n this._state = 3 /* SpecialCasedStylesState.Destroyed */;\n }\n }\n}\nfunction filterNonAnimatableStyles(styles) {\n let result = null;\n styles.forEach((val, prop) => {\n if (isNonAnimatableStyle(prop)) {\n result = result || new Map();\n result.set(prop, val);\n }\n });\n return result;\n}\nfunction isNonAnimatableStyle(prop) {\n return prop === 'display' || prop === 'position';\n}\n\nclass WebAnimationsPlayer {\n constructor(element, keyframes, options, _specialStyles) {\n this.element = element;\n this.keyframes = keyframes;\n this.options = options;\n this._specialStyles = _specialStyles;\n this._onDoneFns = [];\n this._onStartFns = [];\n this._onDestroyFns = [];\n this._initialized = false;\n this._finished = false;\n this._started = false;\n this._destroyed = false;\n // the following original fns are persistent copies of the _onStartFns and _onDoneFns\n // and are used to reset the fns to their original values upon reset()\n // (since the _onStartFns and _onDoneFns get deleted after they are called)\n this._originalOnDoneFns = [];\n this._originalOnStartFns = [];\n this.time = 0;\n this.parentPlayer = null;\n this.currentSnapshot = new Map();\n this._duration = options['duration'];\n this._delay = options['delay'] || 0;\n this.time = this._duration + this._delay;\n }\n _onFinish() {\n if (!this._finished) {\n this._finished = true;\n this._onDoneFns.forEach((fn) => fn());\n this._onDoneFns = [];\n }\n }\n init() {\n this._buildPlayer();\n this._preparePlayerBeforeStart();\n }\n _buildPlayer() {\n if (this._initialized)\n return;\n this._initialized = true;\n const keyframes = this.keyframes;\n // @ts-expect-error overwriting a readonly property\n this.domPlayer = this._triggerWebAnimation(this.element, keyframes, this.options);\n this._finalKeyframe = keyframes.length ? keyframes[keyframes.length - 1] : new Map();\n const onFinish = () => this._onFinish();\n this.domPlayer.addEventListener('finish', onFinish);\n this.onDestroy(() => {\n // We must remove the `finish` event listener once an animation has completed all its\n // iterations. This action is necessary to prevent a memory leak since the listener captures\n // `this`, creating a closure that prevents `this` from being garbage collected.\n this.domPlayer.removeEventListener('finish', onFinish);\n });\n }\n _preparePlayerBeforeStart() {\n // this is required so that the player doesn't start to animate right away\n if (this._delay) {\n this._resetDomPlayerState();\n }\n else {\n this.domPlayer.pause();\n }\n }\n _convertKeyframesToObject(keyframes) {\n const kfs = [];\n keyframes.forEach((frame) => {\n kfs.push(Object.fromEntries(frame));\n });\n return kfs;\n }\n /** @internal */\n _triggerWebAnimation(element, keyframes, options) {\n return element.animate(this._convertKeyframesToObject(keyframes), options);\n }\n onStart(fn) {\n this._originalOnStartFns.push(fn);\n this._onStartFns.push(fn);\n }\n onDone(fn) {\n this._originalOnDoneFns.push(fn);\n this._onDoneFns.push(fn);\n }\n onDestroy(fn) {\n this._onDestroyFns.push(fn);\n }\n play() {\n this._buildPlayer();\n if (!this.hasStarted()) {\n this._onStartFns.forEach((fn) => fn());\n this._onStartFns = [];\n this._started = true;\n if (this._specialStyles) {\n this._specialStyles.start();\n }\n }\n this.domPlayer.play();\n }\n pause() {\n this.init();\n this.domPlayer.pause();\n }\n finish() {\n this.init();\n if (this._specialStyles) {\n this._specialStyles.finish();\n }\n this._onFinish();\n this.domPlayer.finish();\n }\n reset() {\n this._resetDomPlayerState();\n this._destroyed = false;\n this._finished = false;\n this._started = false;\n this._onStartFns = this._originalOnStartFns;\n this._onDoneFns = this._originalOnDoneFns;\n }\n _resetDomPlayerState() {\n if (this.domPlayer) {\n this.domPlayer.cancel();\n }\n }\n restart() {\n this.reset();\n this.play();\n }\n hasStarted() {\n return this._started;\n }\n destroy() {\n if (!this._destroyed) {\n this._destroyed = true;\n this._resetDomPlayerState();\n this._onFinish();\n if (this._specialStyles) {\n this._specialStyles.destroy();\n }\n this._onDestroyFns.forEach((fn) => fn());\n this._onDestroyFns = [];\n }\n }\n setPosition(p) {\n if (this.domPlayer === undefined) {\n this.init();\n }\n this.domPlayer.currentTime = p * this.time;\n }\n getPosition() {\n // tsc is complaining with TS2362 without the conversion to number\n return +(this.domPlayer.currentTime ?? 0) / this.time;\n }\n get totalTime() {\n return this._delay + this._duration;\n }\n beforeDestroy() {\n const styles = new Map();\n if (this.hasStarted()) {\n // note: this code is invoked only when the `play` function was called prior to this\n // (thus `hasStarted` returns true), this implies that the code that initializes\n // `_finalKeyframe` has also been executed and the non-null assertion can be safely used here\n const finalKeyframe = this._finalKeyframe;\n finalKeyframe.forEach((val, prop) => {\n if (prop !== 'offset') {\n styles.set(prop, this._finished ? val : computeStyle(this.element, prop));\n }\n });\n }\n this.currentSnapshot = styles;\n }\n /** @internal */\n triggerCallback(phaseName) {\n const methods = phaseName === 'start' ? this._onStartFns : this._onDoneFns;\n methods.forEach((fn) => fn());\n methods.length = 0;\n }\n}\n\nclass WebAnimationsDriver {\n validateStyleProperty(prop) {\n // Perform actual validation in dev mode only, in prod mode this check is a noop.\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n return validateStyleProperty(prop);\n }\n return true;\n }\n validateAnimatableStyleProperty(prop) {\n // Perform actual validation in dev mode only, in prod mode this check is a noop.\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n const cssProp = camelCaseToDashCase(prop);\n return validateWebAnimatableStyleProperty(cssProp);\n }\n return true;\n }\n matchesElement(_element, _selector) {\n // This method is deprecated and no longer in use so we return false.\n return false;\n }\n containsElement(elm1, elm2) {\n return containsElement(elm1, elm2);\n }\n getParentElement(element) {\n return getParentElement(element);\n }\n query(element, selector, multi) {\n return invokeQuery(element, selector, multi);\n }\n computeStyle(element, prop, defaultValue) {\n return computeStyle(element, prop);\n }\n animate(element, keyframes, duration, delay, easing, previousPlayers = []) {\n const fill = delay == 0 ? 'both' : 'forwards';\n const playerOptions = { duration, delay, fill };\n // we check for this to avoid having a null|undefined value be present\n // for the easing (which results in an error for certain browsers #9752)\n if (easing) {\n playerOptions['easing'] = easing;\n }\n const previousStyles = new Map();\n const previousWebAnimationPlayers = (previousPlayers.filter((player) => player instanceof WebAnimationsPlayer));\n if (allowPreviousPlayerStylesMerge(duration, delay)) {\n previousWebAnimationPlayers.forEach((player) => {\n player.currentSnapshot.forEach((val, prop) => previousStyles.set(prop, val));\n });\n }\n let _keyframes = normalizeKeyframes(keyframes).map((styles) => new Map(styles));\n _keyframes = balancePreviousStylesIntoKeyframes(element, _keyframes, previousStyles);\n const specialStyles = packageNonAnimatableStyles(element, _keyframes);\n return new WebAnimationsPlayer(element, _keyframes, playerOptions, specialStyles);\n }\n}\n\nfunction createEngine(type, doc, scheduler) {\n // TODO: find a way to make this tree shakable.\n if (type === 'noop') {\n return new AnimationEngine(doc, new NoopAnimationDriver(), new NoopAnimationStyleNormalizer(), scheduler);\n }\n return new AnimationEngine(doc, new WebAnimationsDriver(), new WebAnimationsStyleNormalizer(), scheduler);\n}\n\nclass Animation {\n constructor(_driver, input) {\n this._driver = _driver;\n const errors = [];\n const warnings = [];\n const ast = buildAnimationAst(_driver, input, errors, warnings);\n if (errors.length) {\n throw validationFailed(errors);\n }\n if (warnings.length) {\n warnValidation(warnings);\n }\n this._animationAst = ast;\n }\n buildTimelines(element, startingStyles, destinationStyles, options, subInstructions) {\n const start = Array.isArray(startingStyles)\n ? normalizeStyles(startingStyles)\n : startingStyles;\n const dest = Array.isArray(destinationStyles)\n ? normalizeStyles(destinationStyles)\n : destinationStyles;\n const errors = [];\n subInstructions = subInstructions || new ElementInstructionMap();\n const result = buildAnimationTimelines(this._driver, element, this._animationAst, ENTER_CLASSNAME, LEAVE_CLASSNAME, start, dest, options, subInstructions, errors);\n if (errors.length) {\n throw buildingFailed(errors);\n }\n return result;\n }\n}\n\nconst ANIMATION_PREFIX = '@';\nconst DISABLE_ANIMATIONS_FLAG = '@.disabled';\nclass BaseAnimationRenderer {\n constructor(namespaceId, delegate, engine, _onDestroy) {\n this.namespaceId = namespaceId;\n this.delegate = delegate;\n this.engine = engine;\n this._onDestroy = _onDestroy;\n // We need to explicitly type this property because of an api-extractor bug\n // See https://github.com/microsoft/rushstack/issues/4390\n this.ɵtype = 0 /* AnimationRendererType.Regular */;\n }\n get data() {\n return this.delegate.data;\n }\n destroyNode(node) {\n this.delegate.destroyNode?.(node);\n }\n destroy() {\n this.engine.destroy(this.namespaceId, this.delegate);\n this.engine.afterFlushAnimationsDone(() => {\n // Call the renderer destroy method after the animations has finished as otherwise\n // styles will be removed too early which will cause an unstyled animation.\n queueMicrotask(() => {\n this.delegate.destroy();\n });\n });\n this._onDestroy?.();\n }\n createElement(name, namespace) {\n return this.delegate.createElement(name, namespace);\n }\n createComment(value) {\n return this.delegate.createComment(value);\n }\n createText(value) {\n return this.delegate.createText(value);\n }\n appendChild(parent, newChild) {\n this.delegate.appendChild(parent, newChild);\n this.engine.onInsert(this.namespaceId, newChild, parent, false);\n }\n insertBefore(parent, newChild, refChild, isMove = true) {\n this.delegate.insertBefore(parent, newChild, refChild);\n // If `isMove` true than we should animate this insert.\n this.engine.onInsert(this.namespaceId, newChild, parent, isMove);\n }\n removeChild(parent, oldChild, isHostElement) {\n this.engine.onRemove(this.namespaceId, oldChild, this.delegate);\n }\n selectRootElement(selectorOrNode, preserveContent) {\n return this.delegate.selectRootElement(selectorOrNode, preserveContent);\n }\n parentNode(node) {\n return this.delegate.parentNode(node);\n }\n nextSibling(node) {\n return this.delegate.nextSibling(node);\n }\n setAttribute(el, name, value, namespace) {\n this.delegate.setAttribute(el, name, value, namespace);\n }\n removeAttribute(el, name, namespace) {\n this.delegate.removeAttribute(el, name, namespace);\n }\n addClass(el, name) {\n this.delegate.addClass(el, name);\n }\n removeClass(el, name) {\n this.delegate.removeClass(el, name);\n }\n setStyle(el, style, value, flags) {\n this.delegate.setStyle(el, style, value, flags);\n }\n removeStyle(el, style, flags) {\n this.delegate.removeStyle(el, style, flags);\n }\n setProperty(el, name, value) {\n if (name.charAt(0) == ANIMATION_PREFIX && name == DISABLE_ANIMATIONS_FLAG) {\n this.disableAnimations(el, !!value);\n }\n else {\n this.delegate.setProperty(el, name, value);\n }\n }\n setValue(node, value) {\n this.delegate.setValue(node, value);\n }\n listen(target, eventName, callback) {\n return this.delegate.listen(target, eventName, callback);\n }\n disableAnimations(element, value) {\n this.engine.disableAnimations(element, value);\n }\n}\nclass AnimationRenderer extends BaseAnimationRenderer {\n constructor(factory, namespaceId, delegate, engine, onDestroy) {\n super(namespaceId, delegate, engine, onDestroy);\n this.factory = factory;\n this.namespaceId = namespaceId;\n }\n setProperty(el, name, value) {\n if (name.charAt(0) == ANIMATION_PREFIX) {\n if (name.charAt(1) == '.' && name == DISABLE_ANIMATIONS_FLAG) {\n value = value === undefined ? true : !!value;\n this.disableAnimations(el, value);\n }\n else {\n this.engine.process(this.namespaceId, el, name.slice(1), value);\n }\n }\n else {\n this.delegate.setProperty(el, name, value);\n }\n }\n listen(target, eventName, callback) {\n if (eventName.charAt(0) == ANIMATION_PREFIX) {\n const element = resolveElementFromTarget(target);\n let name = eventName.slice(1);\n let phase = '';\n // @listener.phase is for trigger animation callbacks\n // @@listener is for animation builder callbacks\n if (name.charAt(0) != ANIMATION_PREFIX) {\n [name, phase] = parseTriggerCallbackName(name);\n }\n return this.engine.listen(this.namespaceId, element, name, phase, (event) => {\n const countId = event['_data'] || -1;\n this.factory.scheduleListenerCallback(countId, callback, event);\n });\n }\n return this.delegate.listen(target, eventName, callback);\n }\n}\nfunction resolveElementFromTarget(target) {\n switch (target) {\n case 'body':\n return document.body;\n case 'document':\n return document;\n case 'window':\n return window;\n default:\n return target;\n }\n}\nfunction parseTriggerCallbackName(triggerName) {\n const dotIndex = triggerName.indexOf('.');\n const trigger = triggerName.substring(0, dotIndex);\n const phase = triggerName.slice(dotIndex + 1);\n return [trigger, phase];\n}\n\nclass AnimationRendererFactory {\n constructor(delegate, engine, _zone) {\n this.delegate = delegate;\n this.engine = engine;\n this._zone = _zone;\n this._currentId = 0;\n this._microtaskId = 1;\n this._animationCallbacksBuffer = [];\n this._rendererCache = new Map();\n this._cdRecurDepth = 0;\n engine.onRemovalComplete = (element, delegate) => {\n // Note: if a component element has a leave animation, and a host leave animation,\n // the view engine will call `removeChild` for the parent\n // component renderer as well as for the child component renderer.\n // Therefore, we need to check if we already removed the element.\n const parentNode = delegate?.parentNode(element);\n if (parentNode) {\n delegate.removeChild(parentNode, element);\n }\n };\n }\n createRenderer(hostElement, type) {\n const EMPTY_NAMESPACE_ID = '';\n // cache the delegates to find out which cached delegate can\n // be used by which cached renderer\n const delegate = this.delegate.createRenderer(hostElement, type);\n if (!hostElement || !type?.data?.['animation']) {\n const cache = this._rendererCache;\n let renderer = cache.get(delegate);\n if (!renderer) {\n // Ensure that the renderer is removed from the cache on destroy\n // since it may contain references to detached DOM nodes.\n const onRendererDestroy = () => cache.delete(delegate);\n renderer = new BaseAnimationRenderer(EMPTY_NAMESPACE_ID, delegate, this.engine, onRendererDestroy);\n // only cache this result when the base renderer is used\n cache.set(delegate, renderer);\n }\n return renderer;\n }\n const componentId = type.id;\n const namespaceId = type.id + '-' + this._currentId;\n this._currentId++;\n this.engine.register(namespaceId, hostElement);\n const registerTrigger = (trigger) => {\n if (Array.isArray(trigger)) {\n trigger.forEach(registerTrigger);\n }\n else {\n this.engine.registerTrigger(componentId, namespaceId, hostElement, trigger.name, trigger);\n }\n };\n const animationTriggers = type.data['animation'];\n animationTriggers.forEach(registerTrigger);\n return new AnimationRenderer(this, namespaceId, delegate, this.engine);\n }\n begin() {\n this._cdRecurDepth++;\n if (this.delegate.begin) {\n this.delegate.begin();\n }\n }\n _scheduleCountTask() {\n queueMicrotask(() => {\n this._microtaskId++;\n });\n }\n /** @internal */\n scheduleListenerCallback(count, fn, data) {\n if (count >= 0 && count < this._microtaskId) {\n this._zone.run(() => fn(data));\n return;\n }\n const animationCallbacksBuffer = this._animationCallbacksBuffer;\n if (animationCallbacksBuffer.length == 0) {\n queueMicrotask(() => {\n this._zone.run(() => {\n animationCallbacksBuffer.forEach((tuple) => {\n const [fn, data] = tuple;\n fn(data);\n });\n this._animationCallbacksBuffer = [];\n });\n });\n }\n animationCallbacksBuffer.push([fn, data]);\n }\n end() {\n this._cdRecurDepth--;\n // this is to prevent animations from running twice when an inner\n // component does CD when a parent component instead has inserted it\n if (this._cdRecurDepth == 0) {\n this._zone.runOutsideAngular(() => {\n this._scheduleCountTask();\n this.engine.flush(this._microtaskId);\n });\n }\n if (this.delegate.end) {\n this.delegate.end();\n }\n }\n whenRenderingDone() {\n return this.engine.whenRenderingDone();\n }\n}\n\n/**\n * @module\n * @description\n * Entry point for all animation APIs of the animation browser package.\n */\n\n/**\n * @module\n * @description\n * Entry point for all public APIs of this package.\n */\n\n// This file is not used to build this module. It is only used during editing\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { AnimationDriver, NoopAnimationDriver, Animation as ɵAnimation, AnimationEngine as ɵAnimationEngine, AnimationRenderer as ɵAnimationRenderer, AnimationRendererFactory as ɵAnimationRendererFactory, AnimationStyleNormalizer as ɵAnimationStyleNormalizer, BaseAnimationRenderer as ɵBaseAnimationRenderer, NoopAnimationStyleNormalizer as ɵNoopAnimationStyleNormalizer, WebAnimationsDriver as ɵWebAnimationsDriver, WebAnimationsPlayer as ɵWebAnimationsPlayer, WebAnimationsStyleNormalizer as ɵWebAnimationsStyleNormalizer, allowPreviousPlayerStylesMerge as ɵallowPreviousPlayerStylesMerge, camelCaseToDashCase as ɵcamelCaseToDashCase, containsElement as ɵcontainsElement, createEngine as ɵcreateEngine, getParentElement as ɵgetParentElement, invokeQuery as ɵinvokeQuery, normalizeKeyframes as ɵnormalizeKeyframes, validateStyleProperty as ɵvalidateStyleProperty, validateWebAnimatableStyleProperty as ɵvalidateWebAnimatableStyleProperty };\n","import { DOCUMENT } from '@angular/common';\nimport * as i0 from '@angular/core';\nimport { inject, APP_ID, Injectable, Inject, QueryList, isSignal, effect, booleanAttribute, Directive, Input, InjectionToken, Optional, EventEmitter, Output, NgModule } from '@angular/core';\nimport * as i1 from '@angular/cdk/platform';\nimport { Platform, _getFocusedElementPierceShadowDom, normalizePassiveListenerOptions, _getEventTarget, _getShadowRoot } from '@angular/cdk/platform';\nimport { Subject, Subscription, BehaviorSubject, of } from 'rxjs';\nimport { hasModifierKey, A, Z, ZERO, NINE, PAGE_DOWN, PAGE_UP, END, HOME, LEFT_ARROW, RIGHT_ARROW, UP_ARROW, DOWN_ARROW, TAB, ALT, CONTROL, MAC_META, META, SHIFT } from '@angular/cdk/keycodes';\nimport { tap, debounceTime, filter, map, take, skip, distinctUntilChanged, takeUntil } from 'rxjs/operators';\nimport * as i1$1 from '@angular/cdk/observers';\nimport { ObserversModule } from '@angular/cdk/observers';\nimport { coerceElement } from '@angular/cdk/coercion';\nimport { BreakpointObserver } from '@angular/cdk/layout';\n\n/** IDs are delimited by an empty space, as per the spec. */\nconst ID_DELIMITER = ' ';\n/**\n * Adds the given ID to the specified ARIA attribute on an element.\n * Used for attributes such as aria-labelledby, aria-owns, etc.\n */\nfunction addAriaReferencedId(el, attr, id) {\n const ids = getAriaReferenceIds(el, attr);\n id = id.trim();\n if (ids.some(existingId => existingId.trim() === id)) {\n return;\n }\n ids.push(id);\n el.setAttribute(attr, ids.join(ID_DELIMITER));\n}\n/**\n * Removes the given ID from the specified ARIA attribute on an element.\n * Used for attributes such as aria-labelledby, aria-owns, etc.\n */\nfunction removeAriaReferencedId(el, attr, id) {\n const ids = getAriaReferenceIds(el, attr);\n id = id.trim();\n const filteredIds = ids.filter(val => val !== id);\n if (filteredIds.length) {\n el.setAttribute(attr, filteredIds.join(ID_DELIMITER));\n }\n else {\n el.removeAttribute(attr);\n }\n}\n/**\n * Gets the list of IDs referenced by the given ARIA attribute on an element.\n * Used for attributes such as aria-labelledby, aria-owns, etc.\n */\nfunction getAriaReferenceIds(el, attr) {\n // Get string array of all individual ids (whitespace delimited) in the attribute value\n const attrValue = el.getAttribute(attr);\n return attrValue?.match(/\\S+/g) ?? [];\n}\n\n/**\n * ID used for the body container where all messages are appended.\n * @deprecated No longer being used. To be removed.\n * @breaking-change 14.0.0\n */\nconst MESSAGES_CONTAINER_ID = 'cdk-describedby-message-container';\n/**\n * ID prefix used for each created message element.\n * @deprecated To be turned into a private variable.\n * @breaking-change 14.0.0\n */\nconst CDK_DESCRIBEDBY_ID_PREFIX = 'cdk-describedby-message';\n/**\n * Attribute given to each host element that is described by a message element.\n * @deprecated To be turned into a private variable.\n * @breaking-change 14.0.0\n */\nconst CDK_DESCRIBEDBY_HOST_ATTRIBUTE = 'cdk-describedby-host';\n/** Global incremental identifier for each registered message element. */\nlet nextId = 0;\n/**\n * Utility that creates visually hidden elements with a message content. Useful for elements that\n * want to use aria-describedby to further describe themselves without adding additional visual\n * content.\n */\nclass AriaDescriber {\n constructor(_document, \n /**\n * @deprecated To be turned into a required parameter.\n * @breaking-change 14.0.0\n */\n _platform) {\n this._platform = _platform;\n /** Map of all registered message elements that have been placed into the document. */\n this._messageRegistry = new Map();\n /** Container for all registered messages. */\n this._messagesContainer = null;\n /** Unique ID for the service. */\n this._id = `${nextId++}`;\n this._document = _document;\n this._id = inject(APP_ID) + '-' + nextId++;\n }\n describe(hostElement, message, role) {\n if (!this._canBeDescribed(hostElement, message)) {\n return;\n }\n const key = getKey(message, role);\n if (typeof message !== 'string') {\n // We need to ensure that the element has an ID.\n setMessageId(message, this._id);\n this._messageRegistry.set(key, { messageElement: message, referenceCount: 0 });\n }\n else if (!this._messageRegistry.has(key)) {\n this._createMessageElement(message, role);\n }\n if (!this._isElementDescribedByMessage(hostElement, key)) {\n this._addMessageReference(hostElement, key);\n }\n }\n removeDescription(hostElement, message, role) {\n if (!message || !this._isElementNode(hostElement)) {\n return;\n }\n const key = getKey(message, role);\n if (this._isElementDescribedByMessage(hostElement, key)) {\n this._removeMessageReference(hostElement, key);\n }\n // If the message is a string, it means that it's one that we created for the\n // consumer so we can remove it safely, otherwise we should leave it in place.\n if (typeof message === 'string') {\n const registeredMessage = this._messageRegistry.get(key);\n if (registeredMessage && registeredMessage.referenceCount === 0) {\n this._deleteMessageElement(key);\n }\n }\n if (this._messagesContainer?.childNodes.length === 0) {\n this._messagesContainer.remove();\n this._messagesContainer = null;\n }\n }\n /** Unregisters all created message elements and removes the message container. */\n ngOnDestroy() {\n const describedElements = this._document.querySelectorAll(`[${CDK_DESCRIBEDBY_HOST_ATTRIBUTE}=\"${this._id}\"]`);\n for (let i = 0; i < describedElements.length; i++) {\n this._removeCdkDescribedByReferenceIds(describedElements[i]);\n describedElements[i].removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);\n }\n this._messagesContainer?.remove();\n this._messagesContainer = null;\n this._messageRegistry.clear();\n }\n /**\n * Creates a new element in the visually hidden message container element with the message\n * as its content and adds it to the message registry.\n */\n _createMessageElement(message, role) {\n const messageElement = this._document.createElement('div');\n setMessageId(messageElement, this._id);\n messageElement.textContent = message;\n if (role) {\n messageElement.setAttribute('role', role);\n }\n this._createMessagesContainer();\n this._messagesContainer.appendChild(messageElement);\n this._messageRegistry.set(getKey(message, role), { messageElement, referenceCount: 0 });\n }\n /** Deletes the message element from the global messages container. */\n _deleteMessageElement(key) {\n this._messageRegistry.get(key)?.messageElement?.remove();\n this._messageRegistry.delete(key);\n }\n /** Creates the global container for all aria-describedby messages. */\n _createMessagesContainer() {\n if (this._messagesContainer) {\n return;\n }\n const containerClassName = 'cdk-describedby-message-container';\n const serverContainers = this._document.querySelectorAll(`.${containerClassName}[platform=\"server\"]`);\n for (let i = 0; i < serverContainers.length; i++) {\n // When going from the server to the client, we may end up in a situation where there's\n // already a container on the page, but we don't have a reference to it. Clear the\n // old container so we don't get duplicates. Doing this, instead of emptying the previous\n // container, should be slightly faster.\n serverContainers[i].remove();\n }\n const messagesContainer = this._document.createElement('div');\n // We add `visibility: hidden` in order to prevent text in this container from\n // being searchable by the browser's Ctrl + F functionality.\n // Screen-readers will still read the description for elements with aria-describedby even\n // when the description element is not visible.\n messagesContainer.style.visibility = 'hidden';\n // Even though we use `visibility: hidden`, we still apply `cdk-visually-hidden` so that\n // the description element doesn't impact page layout.\n messagesContainer.classList.add(containerClassName);\n messagesContainer.classList.add('cdk-visually-hidden');\n // @breaking-change 14.0.0 Remove null check for `_platform`.\n if (this._platform && !this._platform.isBrowser) {\n messagesContainer.setAttribute('platform', 'server');\n }\n this._document.body.appendChild(messagesContainer);\n this._messagesContainer = messagesContainer;\n }\n /** Removes all cdk-describedby messages that are hosted through the element. */\n _removeCdkDescribedByReferenceIds(element) {\n // Remove all aria-describedby reference IDs that are prefixed by CDK_DESCRIBEDBY_ID_PREFIX\n const originalReferenceIds = getAriaReferenceIds(element, 'aria-describedby').filter(id => id.indexOf(CDK_DESCRIBEDBY_ID_PREFIX) != 0);\n element.setAttribute('aria-describedby', originalReferenceIds.join(' '));\n }\n /**\n * Adds a message reference to the element using aria-describedby and increments the registered\n * message's reference count.\n */\n _addMessageReference(element, key) {\n const registeredMessage = this._messageRegistry.get(key);\n // Add the aria-describedby reference and set the\n // describedby_host attribute to mark the element.\n addAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);\n element.setAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE, this._id);\n registeredMessage.referenceCount++;\n }\n /**\n * Removes a message reference from the element using aria-describedby\n * and decrements the registered message's reference count.\n */\n _removeMessageReference(element, key) {\n const registeredMessage = this._messageRegistry.get(key);\n registeredMessage.referenceCount--;\n removeAriaReferencedId(element, 'aria-describedby', registeredMessage.messageElement.id);\n element.removeAttribute(CDK_DESCRIBEDBY_HOST_ATTRIBUTE);\n }\n /** Returns true if the element has been described by the provided message ID. */\n _isElementDescribedByMessage(element, key) {\n const referenceIds = getAriaReferenceIds(element, 'aria-describedby');\n const registeredMessage = this._messageRegistry.get(key);\n const messageId = registeredMessage && registeredMessage.messageElement.id;\n return !!messageId && referenceIds.indexOf(messageId) != -1;\n }\n /** Determines whether a message can be described on a particular element. */\n _canBeDescribed(element, message) {\n if (!this._isElementNode(element)) {\n return false;\n }\n if (message && typeof message === 'object') {\n // We'd have to make some assumptions about the description element's text, if the consumer\n // passed in an element. Assume that if an element is passed in, the consumer has verified\n // that it can be used as a description.\n return true;\n }\n const trimmedMessage = message == null ? '' : `${message}`.trim();\n const ariaLabel = element.getAttribute('aria-label');\n // We shouldn't set descriptions if they're exactly the same as the `aria-label` of the\n // element, because screen readers will end up reading out the same text twice in a row.\n return trimmedMessage ? !ariaLabel || ariaLabel.trim() !== trimmedMessage : false;\n }\n /** Checks whether a node is an Element node. */\n _isElementNode(element) {\n return element.nodeType === this._document.ELEMENT_NODE;\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: AriaDescriber, deps: [{ token: DOCUMENT }, { token: i1.Platform }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: AriaDescriber, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: AriaDescriber, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [{ type: undefined, decorators: [{\n type: Inject,\n args: [DOCUMENT]\n }] }, { type: i1.Platform }] });\n/** Gets a key that can be used to look messages up in the registry. */\nfunction getKey(message, role) {\n return typeof message === 'string' ? `${role || ''}/${message}` : message;\n}\n/** Assigns a unique ID to an element, if it doesn't have one already. */\nfunction setMessageId(element, serviceId) {\n if (!element.id) {\n element.id = `${CDK_DESCRIBEDBY_ID_PREFIX}-${serviceId}-${nextId++}`;\n }\n}\n\n/**\n * This class manages keyboard events for selectable lists. If you pass it a query list\n * of items, it will set the active item correctly when arrow events occur.\n */\nclass ListKeyManager {\n constructor(_items, injector) {\n this._items = _items;\n this._activeItemIndex = -1;\n this._activeItem = null;\n this._wrap = false;\n this._letterKeyStream = new Subject();\n this._typeaheadSubscription = Subscription.EMPTY;\n this._vertical = true;\n this._allowedModifierKeys = [];\n this._homeAndEnd = false;\n this._pageUpAndDown = { enabled: false, delta: 10 };\n /**\n * Predicate function that can be used to check whether an item should be skipped\n * by the key manager. By default, disabled items are skipped.\n */\n this._skipPredicateFn = (item) => item.disabled;\n // Buffer for the letters that the user has pressed when the typeahead option is turned on.\n this._pressedLetters = [];\n /**\n * Stream that emits any time the TAB key is pressed, so components can react\n * when focus is shifted off of the list.\n */\n this.tabOut = new Subject();\n /** Stream that emits whenever the active item of the list manager changes. */\n this.change = new Subject();\n // We allow for the items to be an array because, in some cases, the consumer may\n // not have access to a QueryList of the items they want to manage (e.g. when the\n // items aren't being collected via `ViewChildren` or `ContentChildren`).\n if (_items instanceof QueryList) {\n this._itemChangesSubscription = _items.changes.subscribe((newItems) => this._itemsChanged(newItems.toArray()));\n }\n else if (isSignal(_items)) {\n if (!injector && (typeof ngDevMode === 'undefined' || ngDevMode)) {\n throw new Error('ListKeyManager constructed with a signal must receive an injector');\n }\n this._effectRef = effect(() => this._itemsChanged(_items()), { injector });\n }\n }\n /**\n * Sets the predicate function that determines which items should be skipped by the\n * list key manager.\n * @param predicate Function that determines whether the given item should be skipped.\n */\n skipPredicate(predicate) {\n this._skipPredicateFn = predicate;\n return this;\n }\n /**\n * Configures wrapping mode, which determines whether the active item will wrap to\n * the other end of list when there are no more items in the given direction.\n * @param shouldWrap Whether the list should wrap when reaching the end.\n */\n withWrap(shouldWrap = true) {\n this._wrap = shouldWrap;\n return this;\n }\n /**\n * Configures whether the key manager should be able to move the selection vertically.\n * @param enabled Whether vertical selection should be enabled.\n */\n withVerticalOrientation(enabled = true) {\n this._vertical = enabled;\n return this;\n }\n /**\n * Configures the key manager to move the selection horizontally.\n * Passing in `null` will disable horizontal movement.\n * @param direction Direction in which the selection can be moved.\n */\n withHorizontalOrientation(direction) {\n this._horizontal = direction;\n return this;\n }\n /**\n * Modifier keys which are allowed to be held down and whose default actions will be prevented\n * as the user is pressing the arrow keys. Defaults to not allowing any modifier keys.\n */\n withAllowedModifierKeys(keys) {\n this._allowedModifierKeys = keys;\n return this;\n }\n /**\n * Turns on typeahead mode which allows users to set the active item by typing.\n * @param debounceInterval Time to wait after the last keystroke before setting the active item.\n */\n withTypeAhead(debounceInterval = 200) {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n const items = this._getItemsArray();\n if (items.length > 0 && items.some(item => typeof item.getLabel !== 'function')) {\n throw Error('ListKeyManager items in typeahead mode must implement the `getLabel` method.');\n }\n }\n this._typeaheadSubscription.unsubscribe();\n // Debounce the presses of non-navigational keys, collect the ones that correspond to letters\n // and convert those letters back into a string. Afterwards find the first item that starts\n // with that string and select it.\n this._typeaheadSubscription = this._letterKeyStream\n .pipe(tap(letter => this._pressedLetters.push(letter)), debounceTime(debounceInterval), filter(() => this._pressedLetters.length > 0), map(() => this._pressedLetters.join('')))\n .subscribe(inputString => {\n const items = this._getItemsArray();\n // Start at 1 because we want to start searching at the item immediately\n // following the current active item.\n for (let i = 1; i < items.length + 1; i++) {\n const index = (this._activeItemIndex + i) % items.length;\n const item = items[index];\n if (!this._skipPredicateFn(item) &&\n item.getLabel().toUpperCase().trim().indexOf(inputString) === 0) {\n this.setActiveItem(index);\n break;\n }\n }\n this._pressedLetters = [];\n });\n return this;\n }\n /** Cancels the current typeahead sequence. */\n cancelTypeahead() {\n this._pressedLetters = [];\n return this;\n }\n /**\n * Configures the key manager to activate the first and last items\n * respectively when the Home or End key is pressed.\n * @param enabled Whether pressing the Home or End key activates the first/last item.\n */\n withHomeAndEnd(enabled = true) {\n this._homeAndEnd = enabled;\n return this;\n }\n /**\n * Configures the key manager to activate every 10th, configured or first/last element in up/down direction\n * respectively when the Page-Up or Page-Down key is pressed.\n * @param enabled Whether pressing the Page-Up or Page-Down key activates the first/last item.\n * @param delta Whether pressing the Home or End key activates the first/last item.\n */\n withPageUpDown(enabled = true, delta = 10) {\n this._pageUpAndDown = { enabled, delta };\n return this;\n }\n setActiveItem(item) {\n const previousActiveItem = this._activeItem;\n this.updateActiveItem(item);\n if (this._activeItem !== previousActiveItem) {\n this.change.next(this._activeItemIndex);\n }\n }\n /**\n * Sets the active item depending on the key event passed in.\n * @param event Keyboard event to be used for determining which element should be active.\n */\n onKeydown(event) {\n const keyCode = event.keyCode;\n const modifiers = ['altKey', 'ctrlKey', 'metaKey', 'shiftKey'];\n const isModifierAllowed = modifiers.every(modifier => {\n return !event[modifier] || this._allowedModifierKeys.indexOf(modifier) > -1;\n });\n switch (keyCode) {\n case TAB:\n this.tabOut.next();\n return;\n case DOWN_ARROW:\n if (this._vertical && isModifierAllowed) {\n this.setNextItemActive();\n break;\n }\n else {\n return;\n }\n case UP_ARROW:\n if (this._vertical && isModifierAllowed) {\n this.setPreviousItemActive();\n break;\n }\n else {\n return;\n }\n case RIGHT_ARROW:\n if (this._horizontal && isModifierAllowed) {\n this._horizontal === 'rtl' ? this.setPreviousItemActive() : this.setNextItemActive();\n break;\n }\n else {\n return;\n }\n case LEFT_ARROW:\n if (this._horizontal && isModifierAllowed) {\n this._horizontal === 'rtl' ? this.setNextItemActive() : this.setPreviousItemActive();\n break;\n }\n else {\n return;\n }\n case HOME:\n if (this._homeAndEnd && isModifierAllowed) {\n this.setFirstItemActive();\n break;\n }\n else {\n return;\n }\n case END:\n if (this._homeAndEnd && isModifierAllowed) {\n this.setLastItemActive();\n break;\n }\n else {\n return;\n }\n case PAGE_UP:\n if (this._pageUpAndDown.enabled && isModifierAllowed) {\n const targetIndex = this._activeItemIndex - this._pageUpAndDown.delta;\n this._setActiveItemByIndex(targetIndex > 0 ? targetIndex : 0, 1);\n break;\n }\n else {\n return;\n }\n case PAGE_DOWN:\n if (this._pageUpAndDown.enabled && isModifierAllowed) {\n const targetIndex = this._activeItemIndex + this._pageUpAndDown.delta;\n const itemsLength = this._getItemsArray().length;\n this._setActiveItemByIndex(targetIndex < itemsLength ? targetIndex : itemsLength - 1, -1);\n break;\n }\n else {\n return;\n }\n default:\n if (isModifierAllowed || hasModifierKey(event, 'shiftKey')) {\n // Attempt to use the `event.key` which also maps it to the user's keyboard language,\n // otherwise fall back to resolving alphanumeric characters via the keyCode.\n if (event.key && event.key.length === 1) {\n this._letterKeyStream.next(event.key.toLocaleUpperCase());\n }\n else if ((keyCode >= A && keyCode <= Z) || (keyCode >= ZERO && keyCode <= NINE)) {\n this._letterKeyStream.next(String.fromCharCode(keyCode));\n }\n }\n // Note that we return here, in order to avoid preventing\n // the default action of non-navigational keys.\n return;\n }\n this._pressedLetters = [];\n event.preventDefault();\n }\n /** Index of the currently active item. */\n get activeItemIndex() {\n return this._activeItemIndex;\n }\n /** The active item. */\n get activeItem() {\n return this._activeItem;\n }\n /** Gets whether the user is currently typing into the manager using the typeahead feature. */\n isTyping() {\n return this._pressedLetters.length > 0;\n }\n /** Sets the active item to the first enabled item in the list. */\n setFirstItemActive() {\n this._setActiveItemByIndex(0, 1);\n }\n /** Sets the active item to the last enabled item in the list. */\n setLastItemActive() {\n this._setActiveItemByIndex(this._getItemsArray().length - 1, -1);\n }\n /** Sets the active item to the next enabled item in the list. */\n setNextItemActive() {\n this._activeItemIndex < 0 ? this.setFirstItemActive() : this._setActiveItemByDelta(1);\n }\n /** Sets the active item to a previous enabled item in the list. */\n setPreviousItemActive() {\n this._activeItemIndex < 0 && this._wrap\n ? this.setLastItemActive()\n : this._setActiveItemByDelta(-1);\n }\n updateActiveItem(item) {\n const itemArray = this._getItemsArray();\n const index = typeof item === 'number' ? item : itemArray.indexOf(item);\n const activeItem = itemArray[index];\n // Explicitly check for `null` and `undefined` because other falsy values are valid.\n this._activeItem = activeItem == null ? null : activeItem;\n this._activeItemIndex = index;\n }\n /** Cleans up the key manager. */\n destroy() {\n this._typeaheadSubscription.unsubscribe();\n this._itemChangesSubscription?.unsubscribe();\n this._effectRef?.destroy();\n this._letterKeyStream.complete();\n this.tabOut.complete();\n this.change.complete();\n this._pressedLetters = [];\n }\n /**\n * This method sets the active item, given a list of items and the delta between the\n * currently active item and the new active item. It will calculate differently\n * depending on whether wrap mode is turned on.\n */\n _setActiveItemByDelta(delta) {\n this._wrap ? this._setActiveInWrapMode(delta) : this._setActiveInDefaultMode(delta);\n }\n /**\n * Sets the active item properly given \"wrap\" mode. In other words, it will continue to move\n * down the list until it finds an item that is not disabled, and it will wrap if it\n * encounters either end of the list.\n */\n _setActiveInWrapMode(delta) {\n const items = this._getItemsArray();\n for (let i = 1; i <= items.length; i++) {\n const index = (this._activeItemIndex + delta * i + items.length) % items.length;\n const item = items[index];\n if (!this._skipPredicateFn(item)) {\n this.setActiveItem(index);\n return;\n }\n }\n }\n /**\n * Sets the active item properly given the default mode. In other words, it will\n * continue to move down the list until it finds an item that is not disabled. If\n * it encounters either end of the list, it will stop and not wrap.\n */\n _setActiveInDefaultMode(delta) {\n this._setActiveItemByIndex(this._activeItemIndex + delta, delta);\n }\n /**\n * Sets the active item to the first enabled item starting at the index specified. If the\n * item is disabled, it will move in the fallbackDelta direction until it either\n * finds an enabled item or encounters the end of the list.\n */\n _setActiveItemByIndex(index, fallbackDelta) {\n const items = this._getItemsArray();\n if (!items[index]) {\n return;\n }\n while (this._skipPredicateFn(items[index])) {\n index += fallbackDelta;\n if (!items[index]) {\n return;\n }\n }\n this.setActiveItem(index);\n }\n /** Returns the items as an array. */\n _getItemsArray() {\n if (isSignal(this._items)) {\n return this._items();\n }\n return this._items instanceof QueryList ? this._items.toArray() : this._items;\n }\n /** Callback for when the items have changed. */\n _itemsChanged(newItems) {\n if (this._activeItem) {\n const newIndex = newItems.indexOf(this._activeItem);\n if (newIndex > -1 && newIndex !== this._activeItemIndex) {\n this._activeItemIndex = newIndex;\n }\n }\n }\n}\n\nclass ActiveDescendantKeyManager extends ListKeyManager {\n setActiveItem(index) {\n if (this.activeItem) {\n this.activeItem.setInactiveStyles();\n }\n super.setActiveItem(index);\n if (this.activeItem) {\n this.activeItem.setActiveStyles();\n }\n }\n}\n\nclass FocusKeyManager extends ListKeyManager {\n constructor() {\n super(...arguments);\n this._origin = 'program';\n }\n /**\n * Sets the focus origin that will be passed in to the items for any subsequent `focus` calls.\n * @param origin Focus origin to be used when focusing items.\n */\n setFocusOrigin(origin) {\n this._origin = origin;\n return this;\n }\n setActiveItem(item) {\n super.setActiveItem(item);\n if (this.activeItem) {\n this.activeItem.focus(this._origin);\n }\n }\n}\n\n/**\n * Configuration for the isFocusable method.\n */\nclass IsFocusableConfig {\n constructor() {\n /**\n * Whether to count an element as focusable even if it is not currently visible.\n */\n this.ignoreVisibility = false;\n }\n}\n// The InteractivityChecker leans heavily on the ally.js accessibility utilities.\n// Methods like `isTabbable` are only covering specific edge-cases for the browsers which are\n// supported.\n/**\n * Utility for checking the interactivity of an element, such as whether it is focusable or\n * tabbable.\n */\nclass InteractivityChecker {\n constructor(_platform) {\n this._platform = _platform;\n }\n /**\n * Gets whether an element is disabled.\n *\n * @param element Element to be checked.\n * @returns Whether the element is disabled.\n */\n isDisabled(element) {\n // This does not capture some cases, such as a non-form control with a disabled attribute or\n // a form control inside of a disabled form, but should capture the most common cases.\n return element.hasAttribute('disabled');\n }\n /**\n * Gets whether an element is visible for the purposes of interactivity.\n *\n * This will capture states like `display: none` and `visibility: hidden`, but not things like\n * being clipped by an `overflow: hidden` parent or being outside the viewport.\n *\n * @returns Whether the element is visible.\n */\n isVisible(element) {\n return hasGeometry(element) && getComputedStyle(element).visibility === 'visible';\n }\n /**\n * Gets whether an element can be reached via Tab key.\n * Assumes that the element has already been checked with isFocusable.\n *\n * @param element Element to be checked.\n * @returns Whether the element is tabbable.\n */\n isTabbable(element) {\n // Nothing is tabbable on the server 😎\n if (!this._platform.isBrowser) {\n return false;\n }\n const frameElement = getFrameElement(getWindow(element));\n if (frameElement) {\n // Frame elements inherit their tabindex onto all child elements.\n if (getTabIndexValue(frameElement) === -1) {\n return false;\n }\n // Browsers disable tabbing to an element inside of an invisible frame.\n if (!this.isVisible(frameElement)) {\n return false;\n }\n }\n let nodeName = element.nodeName.toLowerCase();\n let tabIndexValue = getTabIndexValue(element);\n if (element.hasAttribute('contenteditable')) {\n return tabIndexValue !== -1;\n }\n if (nodeName === 'iframe' || nodeName === 'object') {\n // The frame or object's content may be tabbable depending on the content, but it's\n // not possibly to reliably detect the content of the frames. We always consider such\n // elements as non-tabbable.\n return false;\n }\n // In iOS, the browser only considers some specific elements as tabbable.\n if (this._platform.WEBKIT && this._platform.IOS && !isPotentiallyTabbableIOS(element)) {\n return false;\n }\n if (nodeName === 'audio') {\n // Audio elements without controls enabled are never tabbable, regardless\n // of the tabindex attribute explicitly being set.\n if (!element.hasAttribute('controls')) {\n return false;\n }\n // Audio elements with controls are by default tabbable unless the\n // tabindex attribute is set to `-1` explicitly.\n return tabIndexValue !== -1;\n }\n if (nodeName === 'video') {\n // For all video elements, if the tabindex attribute is set to `-1`, the video\n // is not tabbable. Note: We cannot rely on the default `HTMLElement.tabIndex`\n // property as that one is set to `-1` in Chrome, Edge and Safari v13.1. The\n // tabindex attribute is the source of truth here.\n if (tabIndexValue === -1) {\n return false;\n }\n // If the tabindex is explicitly set, and not `-1` (as per check before), the\n // video element is always tabbable (regardless of whether it has controls or not).\n if (tabIndexValue !== null) {\n return true;\n }\n // Otherwise (when no explicit tabindex is set), a video is only tabbable if it\n // has controls enabled. Firefox is special as videos are always tabbable regardless\n // of whether there are controls or not.\n return this._platform.FIREFOX || element.hasAttribute('controls');\n }\n return element.tabIndex >= 0;\n }\n /**\n * Gets whether an element can be focused by the user.\n *\n * @param element Element to be checked.\n * @param config The config object with options to customize this method's behavior\n * @returns Whether the element is focusable.\n */\n isFocusable(element, config) {\n // Perform checks in order of left to most expensive.\n // Again, naive approach that does not capture many edge cases and browser quirks.\n return (isPotentiallyFocusable(element) &&\n !this.isDisabled(element) &&\n (config?.ignoreVisibility || this.isVisible(element)));\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: InteractivityChecker, deps: [{ token: i1.Platform }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: InteractivityChecker, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: InteractivityChecker, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [{ type: i1.Platform }] });\n/**\n * Returns the frame element from a window object. Since browsers like MS Edge throw errors if\n * the frameElement property is being accessed from a different host address, this property\n * should be accessed carefully.\n */\nfunction getFrameElement(window) {\n try {\n return window.frameElement;\n }\n catch {\n return null;\n }\n}\n/** Checks whether the specified element has any geometry / rectangles. */\nfunction hasGeometry(element) {\n // Use logic from jQuery to check for an invisible element.\n // See https://github.com/jquery/jquery/blob/master/src/css/hiddenVisibleSelectors.js#L12\n return !!(element.offsetWidth ||\n element.offsetHeight ||\n (typeof element.getClientRects === 'function' && element.getClientRects().length));\n}\n/** Gets whether an element's */\nfunction isNativeFormElement(element) {\n let nodeName = element.nodeName.toLowerCase();\n return (nodeName === 'input' ||\n nodeName === 'select' ||\n nodeName === 'button' ||\n nodeName === 'textarea');\n}\n/** Gets whether an element is an ``. */\nfunction isHiddenInput(element) {\n return isInputElement(element) && element.type == 'hidden';\n}\n/** Gets whether an element is an anchor that has an href attribute. */\nfunction isAnchorWithHref(element) {\n return isAnchorElement(element) && element.hasAttribute('href');\n}\n/** Gets whether an element is an input element. */\nfunction isInputElement(element) {\n return element.nodeName.toLowerCase() == 'input';\n}\n/** Gets whether an element is an anchor element. */\nfunction isAnchorElement(element) {\n return element.nodeName.toLowerCase() == 'a';\n}\n/** Gets whether an element has a valid tabindex. */\nfunction hasValidTabIndex(element) {\n if (!element.hasAttribute('tabindex') || element.tabIndex === undefined) {\n return false;\n }\n let tabIndex = element.getAttribute('tabindex');\n return !!(tabIndex && !isNaN(parseInt(tabIndex, 10)));\n}\n/**\n * Returns the parsed tabindex from the element attributes instead of returning the\n * evaluated tabindex from the browsers defaults.\n */\nfunction getTabIndexValue(element) {\n if (!hasValidTabIndex(element)) {\n return null;\n }\n // See browser issue in Gecko https://bugzilla.mozilla.org/show_bug.cgi?id=1128054\n const tabIndex = parseInt(element.getAttribute('tabindex') || '', 10);\n return isNaN(tabIndex) ? -1 : tabIndex;\n}\n/** Checks whether the specified element is potentially tabbable on iOS */\nfunction isPotentiallyTabbableIOS(element) {\n let nodeName = element.nodeName.toLowerCase();\n let inputType = nodeName === 'input' && element.type;\n return (inputType === 'text' ||\n inputType === 'password' ||\n nodeName === 'select' ||\n nodeName === 'textarea');\n}\n/**\n * Gets whether an element is potentially focusable without taking current visible/disabled state\n * into account.\n */\nfunction isPotentiallyFocusable(element) {\n // Inputs are potentially focusable *unless* they're type=\"hidden\".\n if (isHiddenInput(element)) {\n return false;\n }\n return (isNativeFormElement(element) ||\n isAnchorWithHref(element) ||\n element.hasAttribute('contenteditable') ||\n hasValidTabIndex(element));\n}\n/** Gets the parent window of a DOM node with regards of being inside of an iframe. */\nfunction getWindow(node) {\n // ownerDocument is null if `node` itself *is* a document.\n return (node.ownerDocument && node.ownerDocument.defaultView) || window;\n}\n\n/**\n * Class that allows for trapping focus within a DOM element.\n *\n * This class currently uses a relatively simple approach to focus trapping.\n * It assumes that the tab order is the same as DOM order, which is not necessarily true.\n * Things like `tabIndex > 0`, flex `order`, and shadow roots can cause the two to be misaligned.\n */\nclass FocusTrap {\n /** Whether the focus trap is active. */\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n this._enabled = value;\n if (this._startAnchor && this._endAnchor) {\n this._toggleAnchorTabIndex(value, this._startAnchor);\n this._toggleAnchorTabIndex(value, this._endAnchor);\n }\n }\n constructor(_element, _checker, _ngZone, _document, deferAnchors = false) {\n this._element = _element;\n this._checker = _checker;\n this._ngZone = _ngZone;\n this._document = _document;\n this._hasAttached = false;\n // Event listeners for the anchors. Need to be regular functions so that we can unbind them later.\n this.startAnchorListener = () => this.focusLastTabbableElement();\n this.endAnchorListener = () => this.focusFirstTabbableElement();\n this._enabled = true;\n if (!deferAnchors) {\n this.attachAnchors();\n }\n }\n /** Destroys the focus trap by cleaning up the anchors. */\n destroy() {\n const startAnchor = this._startAnchor;\n const endAnchor = this._endAnchor;\n if (startAnchor) {\n startAnchor.removeEventListener('focus', this.startAnchorListener);\n startAnchor.remove();\n }\n if (endAnchor) {\n endAnchor.removeEventListener('focus', this.endAnchorListener);\n endAnchor.remove();\n }\n this._startAnchor = this._endAnchor = null;\n this._hasAttached = false;\n }\n /**\n * Inserts the anchors into the DOM. This is usually done automatically\n * in the constructor, but can be deferred for cases like directives with `*ngIf`.\n * @returns Whether the focus trap managed to attach successfully. This may not be the case\n * if the target element isn't currently in the DOM.\n */\n attachAnchors() {\n // If we're not on the browser, there can be no focus to trap.\n if (this._hasAttached) {\n return true;\n }\n this._ngZone.runOutsideAngular(() => {\n if (!this._startAnchor) {\n this._startAnchor = this._createAnchor();\n this._startAnchor.addEventListener('focus', this.startAnchorListener);\n }\n if (!this._endAnchor) {\n this._endAnchor = this._createAnchor();\n this._endAnchor.addEventListener('focus', this.endAnchorListener);\n }\n });\n if (this._element.parentNode) {\n this._element.parentNode.insertBefore(this._startAnchor, this._element);\n this._element.parentNode.insertBefore(this._endAnchor, this._element.nextSibling);\n this._hasAttached = true;\n }\n return this._hasAttached;\n }\n /**\n * Waits for the zone to stabilize, then focuses the first tabbable element.\n * @returns Returns a promise that resolves with a boolean, depending\n * on whether focus was moved successfully.\n */\n focusInitialElementWhenReady(options) {\n return new Promise(resolve => {\n this._executeOnStable(() => resolve(this.focusInitialElement(options)));\n });\n }\n /**\n * Waits for the zone to stabilize, then focuses\n * the first tabbable element within the focus trap region.\n * @returns Returns a promise that resolves with a boolean, depending\n * on whether focus was moved successfully.\n */\n focusFirstTabbableElementWhenReady(options) {\n return new Promise(resolve => {\n this._executeOnStable(() => resolve(this.focusFirstTabbableElement(options)));\n });\n }\n /**\n * Waits for the zone to stabilize, then focuses\n * the last tabbable element within the focus trap region.\n * @returns Returns a promise that resolves with a boolean, depending\n * on whether focus was moved successfully.\n */\n focusLastTabbableElementWhenReady(options) {\n return new Promise(resolve => {\n this._executeOnStable(() => resolve(this.focusLastTabbableElement(options)));\n });\n }\n /**\n * Get the specified boundary element of the trapped region.\n * @param bound The boundary to get (start or end of trapped region).\n * @returns The boundary element.\n */\n _getRegionBoundary(bound) {\n // Contains the deprecated version of selector, for temporary backwards comparability.\n const markers = this._element.querySelectorAll(`[cdk-focus-region-${bound}], ` + `[cdkFocusRegion${bound}], ` + `[cdk-focus-${bound}]`);\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n for (let i = 0; i < markers.length; i++) {\n // @breaking-change 8.0.0\n if (markers[i].hasAttribute(`cdk-focus-${bound}`)) {\n console.warn(`Found use of deprecated attribute 'cdk-focus-${bound}', ` +\n `use 'cdkFocusRegion${bound}' instead. The deprecated ` +\n `attribute will be removed in 8.0.0.`, markers[i]);\n }\n else if (markers[i].hasAttribute(`cdk-focus-region-${bound}`)) {\n console.warn(`Found use of deprecated attribute 'cdk-focus-region-${bound}', ` +\n `use 'cdkFocusRegion${bound}' instead. The deprecated attribute ` +\n `will be removed in 8.0.0.`, markers[i]);\n }\n }\n }\n if (bound == 'start') {\n return markers.length ? markers[0] : this._getFirstTabbableElement(this._element);\n }\n return markers.length\n ? markers[markers.length - 1]\n : this._getLastTabbableElement(this._element);\n }\n /**\n * Focuses the element that should be focused when the focus trap is initialized.\n * @returns Whether focus was moved successfully.\n */\n focusInitialElement(options) {\n // Contains the deprecated version of selector, for temporary backwards comparability.\n const redirectToElement = this._element.querySelector(`[cdk-focus-initial], ` + `[cdkFocusInitial]`);\n if (redirectToElement) {\n // @breaking-change 8.0.0\n if ((typeof ngDevMode === 'undefined' || ngDevMode) &&\n redirectToElement.hasAttribute(`cdk-focus-initial`)) {\n console.warn(`Found use of deprecated attribute 'cdk-focus-initial', ` +\n `use 'cdkFocusInitial' instead. The deprecated attribute ` +\n `will be removed in 8.0.0`, redirectToElement);\n }\n // Warn the consumer if the element they've pointed to\n // isn't focusable, when not in production mode.\n if ((typeof ngDevMode === 'undefined' || ngDevMode) &&\n !this._checker.isFocusable(redirectToElement)) {\n console.warn(`Element matching '[cdkFocusInitial]' is not focusable.`, redirectToElement);\n }\n if (!this._checker.isFocusable(redirectToElement)) {\n const focusableChild = this._getFirstTabbableElement(redirectToElement);\n focusableChild?.focus(options);\n return !!focusableChild;\n }\n redirectToElement.focus(options);\n return true;\n }\n return this.focusFirstTabbableElement(options);\n }\n /**\n * Focuses the first tabbable element within the focus trap region.\n * @returns Whether focus was moved successfully.\n */\n focusFirstTabbableElement(options) {\n const redirectToElement = this._getRegionBoundary('start');\n if (redirectToElement) {\n redirectToElement.focus(options);\n }\n return !!redirectToElement;\n }\n /**\n * Focuses the last tabbable element within the focus trap region.\n * @returns Whether focus was moved successfully.\n */\n focusLastTabbableElement(options) {\n const redirectToElement = this._getRegionBoundary('end');\n if (redirectToElement) {\n redirectToElement.focus(options);\n }\n return !!redirectToElement;\n }\n /**\n * Checks whether the focus trap has successfully been attached.\n */\n hasAttached() {\n return this._hasAttached;\n }\n /** Get the first tabbable element from a DOM subtree (inclusive). */\n _getFirstTabbableElement(root) {\n if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {\n return root;\n }\n const children = root.children;\n for (let i = 0; i < children.length; i++) {\n const tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE\n ? this._getFirstTabbableElement(children[i])\n : null;\n if (tabbableChild) {\n return tabbableChild;\n }\n }\n return null;\n }\n /** Get the last tabbable element from a DOM subtree (inclusive). */\n _getLastTabbableElement(root) {\n if (this._checker.isFocusable(root) && this._checker.isTabbable(root)) {\n return root;\n }\n // Iterate in reverse DOM order.\n const children = root.children;\n for (let i = children.length - 1; i >= 0; i--) {\n const tabbableChild = children[i].nodeType === this._document.ELEMENT_NODE\n ? this._getLastTabbableElement(children[i])\n : null;\n if (tabbableChild) {\n return tabbableChild;\n }\n }\n return null;\n }\n /** Creates an anchor element. */\n _createAnchor() {\n const anchor = this._document.createElement('div');\n this._toggleAnchorTabIndex(this._enabled, anchor);\n anchor.classList.add('cdk-visually-hidden');\n anchor.classList.add('cdk-focus-trap-anchor');\n anchor.setAttribute('aria-hidden', 'true');\n return anchor;\n }\n /**\n * Toggles the `tabindex` of an anchor, based on the enabled state of the focus trap.\n * @param isEnabled Whether the focus trap is enabled.\n * @param anchor Anchor on which to toggle the tabindex.\n */\n _toggleAnchorTabIndex(isEnabled, anchor) {\n // Remove the tabindex completely, rather than setting it to -1, because if the\n // element has a tabindex, the user might still hit it when navigating with the arrow keys.\n isEnabled ? anchor.setAttribute('tabindex', '0') : anchor.removeAttribute('tabindex');\n }\n /**\n * Toggles the`tabindex` of both anchors to either trap Tab focus or allow it to escape.\n * @param enabled: Whether the anchors should trap Tab.\n */\n toggleAnchors(enabled) {\n if (this._startAnchor && this._endAnchor) {\n this._toggleAnchorTabIndex(enabled, this._startAnchor);\n this._toggleAnchorTabIndex(enabled, this._endAnchor);\n }\n }\n /** Executes a function when the zone is stable. */\n _executeOnStable(fn) {\n if (this._ngZone.isStable) {\n fn();\n }\n else {\n this._ngZone.onStable.pipe(take(1)).subscribe(fn);\n }\n }\n}\n/**\n * Factory that allows easy instantiation of focus traps.\n */\nclass FocusTrapFactory {\n constructor(_checker, _ngZone, _document) {\n this._checker = _checker;\n this._ngZone = _ngZone;\n this._document = _document;\n }\n /**\n * Creates a focus-trapped region around the given element.\n * @param element The element around which focus will be trapped.\n * @param deferCaptureElements Defers the creation of focus-capturing elements to be done\n * manually by the user.\n * @returns The created focus trap instance.\n */\n create(element, deferCaptureElements = false) {\n return new FocusTrap(element, this._checker, this._ngZone, this._document, deferCaptureElements);\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: FocusTrapFactory, deps: [{ token: InteractivityChecker }, { token: i0.NgZone }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: FocusTrapFactory, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: FocusTrapFactory, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [{ type: InteractivityChecker }, { type: i0.NgZone }, { type: undefined, decorators: [{\n type: Inject,\n args: [DOCUMENT]\n }] }] });\n/** Directive for trapping focus within a region. */\nclass CdkTrapFocus {\n /** Whether the focus trap is active. */\n get enabled() {\n return this.focusTrap?.enabled || false;\n }\n set enabled(value) {\n if (this.focusTrap) {\n this.focusTrap.enabled = value;\n }\n }\n constructor(_elementRef, _focusTrapFactory, \n /**\n * @deprecated No longer being used. To be removed.\n * @breaking-change 13.0.0\n */\n _document) {\n this._elementRef = _elementRef;\n this._focusTrapFactory = _focusTrapFactory;\n /** Previously focused element to restore focus to upon destroy when using autoCapture. */\n this._previouslyFocusedElement = null;\n const platform = inject(Platform);\n if (platform.isBrowser) {\n this.focusTrap = this._focusTrapFactory.create(this._elementRef.nativeElement, true);\n }\n }\n ngOnDestroy() {\n this.focusTrap?.destroy();\n // If we stored a previously focused element when using autoCapture, return focus to that\n // element now that the trapped region is being destroyed.\n if (this._previouslyFocusedElement) {\n this._previouslyFocusedElement.focus();\n this._previouslyFocusedElement = null;\n }\n }\n ngAfterContentInit() {\n this.focusTrap?.attachAnchors();\n if (this.autoCapture) {\n this._captureFocus();\n }\n }\n ngDoCheck() {\n if (this.focusTrap && !this.focusTrap.hasAttached()) {\n this.focusTrap.attachAnchors();\n }\n }\n ngOnChanges(changes) {\n const autoCaptureChange = changes['autoCapture'];\n if (autoCaptureChange &&\n !autoCaptureChange.firstChange &&\n this.autoCapture &&\n this.focusTrap?.hasAttached()) {\n this._captureFocus();\n }\n }\n _captureFocus() {\n this._previouslyFocusedElement = _getFocusedElementPierceShadowDom();\n this.focusTrap?.focusInitialElementWhenReady();\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: CdkTrapFocus, deps: [{ token: i0.ElementRef }, { token: FocusTrapFactory }, { token: DOCUMENT }], target: i0.ɵɵFactoryTarget.Directive }); }\n static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: \"16.1.0\", version: \"17.2.0\", type: CdkTrapFocus, isStandalone: true, selector: \"[cdkTrapFocus]\", inputs: { enabled: [\"cdkTrapFocus\", \"enabled\", booleanAttribute], autoCapture: [\"cdkTrapFocusAutoCapture\", \"autoCapture\", booleanAttribute] }, exportAs: [\"cdkTrapFocus\"], usesOnChanges: true, ngImport: i0 }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: CdkTrapFocus, decorators: [{\n type: Directive,\n args: [{\n selector: '[cdkTrapFocus]',\n exportAs: 'cdkTrapFocus',\n standalone: true,\n }]\n }], ctorParameters: () => [{ type: i0.ElementRef }, { type: FocusTrapFactory }, { type: undefined, decorators: [{\n type: Inject,\n args: [DOCUMENT]\n }] }], propDecorators: { enabled: [{\n type: Input,\n args: [{ alias: 'cdkTrapFocus', transform: booleanAttribute }]\n }], autoCapture: [{\n type: Input,\n args: [{ alias: 'cdkTrapFocusAutoCapture', transform: booleanAttribute }]\n }] } });\n\n/**\n * Class that allows for trapping focus within a DOM element.\n *\n * This class uses a strategy pattern that determines how it traps focus.\n * See FocusTrapInertStrategy.\n */\nclass ConfigurableFocusTrap extends FocusTrap {\n /** Whether the FocusTrap is enabled. */\n get enabled() {\n return this._enabled;\n }\n set enabled(value) {\n this._enabled = value;\n if (this._enabled) {\n this._focusTrapManager.register(this);\n }\n else {\n this._focusTrapManager.deregister(this);\n }\n }\n constructor(_element, _checker, _ngZone, _document, _focusTrapManager, _inertStrategy, config) {\n super(_element, _checker, _ngZone, _document, config.defer);\n this._focusTrapManager = _focusTrapManager;\n this._inertStrategy = _inertStrategy;\n this._focusTrapManager.register(this);\n }\n /** Notifies the FocusTrapManager that this FocusTrap will be destroyed. */\n destroy() {\n this._focusTrapManager.deregister(this);\n super.destroy();\n }\n /** @docs-private Implemented as part of ManagedFocusTrap. */\n _enable() {\n this._inertStrategy.preventFocus(this);\n this.toggleAnchors(true);\n }\n /** @docs-private Implemented as part of ManagedFocusTrap. */\n _disable() {\n this._inertStrategy.allowFocus(this);\n this.toggleAnchors(false);\n }\n}\n\n/** The injection token used to specify the inert strategy. */\nconst FOCUS_TRAP_INERT_STRATEGY = new InjectionToken('FOCUS_TRAP_INERT_STRATEGY');\n\n/**\n * Lightweight FocusTrapInertStrategy that adds a document focus event\n * listener to redirect focus back inside the FocusTrap.\n */\nclass EventListenerFocusTrapInertStrategy {\n constructor() {\n /** Focus event handler. */\n this._listener = null;\n }\n /** Adds a document event listener that keeps focus inside the FocusTrap. */\n preventFocus(focusTrap) {\n // Ensure there's only one listener per document\n if (this._listener) {\n focusTrap._document.removeEventListener('focus', this._listener, true);\n }\n this._listener = (e) => this._trapFocus(focusTrap, e);\n focusTrap._ngZone.runOutsideAngular(() => {\n focusTrap._document.addEventListener('focus', this._listener, true);\n });\n }\n /** Removes the event listener added in preventFocus. */\n allowFocus(focusTrap) {\n if (!this._listener) {\n return;\n }\n focusTrap._document.removeEventListener('focus', this._listener, true);\n this._listener = null;\n }\n /**\n * Refocuses the first element in the FocusTrap if the focus event target was outside\n * the FocusTrap.\n *\n * This is an event listener callback. The event listener is added in runOutsideAngular,\n * so all this code runs outside Angular as well.\n */\n _trapFocus(focusTrap, event) {\n const target = event.target;\n const focusTrapRoot = focusTrap._element;\n // Don't refocus if target was in an overlay, because the overlay might be associated\n // with an element inside the FocusTrap, ex. mat-select.\n if (target && !focusTrapRoot.contains(target) && !target.closest?.('div.cdk-overlay-pane')) {\n // Some legacy FocusTrap usages have logic that focuses some element on the page\n // just before FocusTrap is destroyed. For backwards compatibility, wait\n // to be sure FocusTrap is still enabled before refocusing.\n setTimeout(() => {\n // Check whether focus wasn't put back into the focus trap while the timeout was pending.\n if (focusTrap.enabled && !focusTrapRoot.contains(focusTrap._document.activeElement)) {\n focusTrap.focusFirstTabbableElement();\n }\n });\n }\n }\n}\n\n/** Injectable that ensures only the most recently enabled FocusTrap is active. */\nclass FocusTrapManager {\n constructor() {\n // A stack of the FocusTraps on the page. Only the FocusTrap at the\n // top of the stack is active.\n this._focusTrapStack = [];\n }\n /**\n * Disables the FocusTrap at the top of the stack, and then pushes\n * the new FocusTrap onto the stack.\n */\n register(focusTrap) {\n // Dedupe focusTraps that register multiple times.\n this._focusTrapStack = this._focusTrapStack.filter(ft => ft !== focusTrap);\n let stack = this._focusTrapStack;\n if (stack.length) {\n stack[stack.length - 1]._disable();\n }\n stack.push(focusTrap);\n focusTrap._enable();\n }\n /**\n * Removes the FocusTrap from the stack, and activates the\n * FocusTrap that is the new top of the stack.\n */\n deregister(focusTrap) {\n focusTrap._disable();\n const stack = this._focusTrapStack;\n const i = stack.indexOf(focusTrap);\n if (i !== -1) {\n stack.splice(i, 1);\n if (stack.length) {\n stack[stack.length - 1]._enable();\n }\n }\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: FocusTrapManager, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: FocusTrapManager, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: FocusTrapManager, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }] });\n\n/** Factory that allows easy instantiation of configurable focus traps. */\nclass ConfigurableFocusTrapFactory {\n constructor(_checker, _ngZone, _focusTrapManager, _document, _inertStrategy) {\n this._checker = _checker;\n this._ngZone = _ngZone;\n this._focusTrapManager = _focusTrapManager;\n this._document = _document;\n // TODO split up the strategies into different modules, similar to DateAdapter.\n this._inertStrategy = _inertStrategy || new EventListenerFocusTrapInertStrategy();\n }\n create(element, config = { defer: false }) {\n let configObject;\n if (typeof config === 'boolean') {\n configObject = { defer: config };\n }\n else {\n configObject = config;\n }\n return new ConfigurableFocusTrap(element, this._checker, this._ngZone, this._document, this._focusTrapManager, this._inertStrategy, configObject);\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: ConfigurableFocusTrapFactory, deps: [{ token: InteractivityChecker }, { token: i0.NgZone }, { token: FocusTrapManager }, { token: DOCUMENT }, { token: FOCUS_TRAP_INERT_STRATEGY, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: ConfigurableFocusTrapFactory, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: ConfigurableFocusTrapFactory, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [{ type: InteractivityChecker }, { type: i0.NgZone }, { type: FocusTrapManager }, { type: undefined, decorators: [{\n type: Inject,\n args: [DOCUMENT]\n }] }, { type: undefined, decorators: [{\n type: Optional\n }, {\n type: Inject,\n args: [FOCUS_TRAP_INERT_STRATEGY]\n }] }] });\n\n/** Gets whether an event could be a faked `mousedown` event dispatched by a screen reader. */\nfunction isFakeMousedownFromScreenReader(event) {\n // Some screen readers will dispatch a fake `mousedown` event when pressing enter or space on\n // a clickable element. We can distinguish these events when `event.buttons` is zero, or\n // `event.detail` is zero depending on the browser:\n // - `event.buttons` works on Firefox, but fails on Chrome.\n // - `detail` works on Chrome, but fails on Firefox.\n return event.buttons === 0 || event.detail === 0;\n}\n/** Gets whether an event could be a faked `touchstart` event dispatched by a screen reader. */\nfunction isFakeTouchstartFromScreenReader(event) {\n const touch = (event.touches && event.touches[0]) || (event.changedTouches && event.changedTouches[0]);\n // A fake `touchstart` can be distinguished from a real one by looking at the `identifier`\n // which is typically >= 0 on a real device versus -1 from a screen reader. Just to be safe,\n // we can also look at `radiusX` and `radiusY`. This behavior was observed against a Windows 10\n // device with a touch screen running NVDA v2020.4 and Firefox 85 or Chrome 88.\n return (!!touch &&\n touch.identifier === -1 &&\n (touch.radiusX == null || touch.radiusX === 1) &&\n (touch.radiusY == null || touch.radiusY === 1));\n}\n\n/**\n * Injectable options for the InputModalityDetector. These are shallowly merged with the default\n * options.\n */\nconst INPUT_MODALITY_DETECTOR_OPTIONS = new InjectionToken('cdk-input-modality-detector-options');\n/**\n * Default options for the InputModalityDetector.\n *\n * Modifier keys are ignored by default (i.e. when pressed won't cause the service to detect\n * keyboard input modality) for two reasons:\n *\n * 1. Modifier keys are commonly used with mouse to perform actions such as 'right click' or 'open\n * in new tab', and are thus less representative of actual keyboard interaction.\n * 2. VoiceOver triggers some keyboard events when linearly navigating with Control + Option (but\n * confusingly not with Caps Lock). Thus, to have parity with other screen readers, we ignore\n * these keys so as to not update the input modality.\n *\n * Note that we do not by default ignore the right Meta key on Safari because it has the same key\n * code as the ContextMenu key on other browsers. When we switch to using event.key, we can\n * distinguish between the two.\n */\nconst INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS = {\n ignoreKeys: [ALT, CONTROL, MAC_META, META, SHIFT],\n};\n/**\n * The amount of time needed to pass after a touchstart event in order for a subsequent mousedown\n * event to be attributed as mouse and not touch.\n *\n * This is the value used by AngularJS Material. Through trial and error (on iPhone 6S) they found\n * that a value of around 650ms seems appropriate.\n */\nconst TOUCH_BUFFER_MS = 650;\n/**\n * Event listener options that enable capturing and also mark the listener as passive if the browser\n * supports it.\n */\nconst modalityEventListenerOptions = normalizePassiveListenerOptions({\n passive: true,\n capture: true,\n});\n/**\n * Service that detects the user's input modality.\n *\n * This service does not update the input modality when a user navigates with a screen reader\n * (e.g. linear navigation with VoiceOver, object navigation / browse mode with NVDA, virtual PC\n * cursor mode with JAWS). This is in part due to technical limitations (i.e. keyboard events do not\n * fire as expected in these modes) but is also arguably the correct behavior. Navigating with a\n * screen reader is akin to visually scanning a page, and should not be interpreted as actual user\n * input interaction.\n *\n * When a user is not navigating but *interacting* with a screen reader, this service attempts to\n * update the input modality to keyboard, but in general this service's behavior is largely\n * undefined.\n */\nclass InputModalityDetector {\n /** The most recently detected input modality. */\n get mostRecentModality() {\n return this._modality.value;\n }\n constructor(_platform, ngZone, document, options) {\n this._platform = _platform;\n /**\n * The most recently detected input modality event target. Is null if no input modality has been\n * detected or if the associated event target is null for some unknown reason.\n */\n this._mostRecentTarget = null;\n /** The underlying BehaviorSubject that emits whenever an input modality is detected. */\n this._modality = new BehaviorSubject(null);\n /**\n * The timestamp of the last touch input modality. Used to determine whether mousedown events\n * should be attributed to mouse or touch.\n */\n this._lastTouchMs = 0;\n /**\n * Handles keydown events. Must be an arrow function in order to preserve the context when it gets\n * bound.\n */\n this._onKeydown = (event) => {\n // If this is one of the keys we should ignore, then ignore it and don't update the input\n // modality to keyboard.\n if (this._options?.ignoreKeys?.some(keyCode => keyCode === event.keyCode)) {\n return;\n }\n this._modality.next('keyboard');\n this._mostRecentTarget = _getEventTarget(event);\n };\n /**\n * Handles mousedown events. Must be an arrow function in order to preserve the context when it\n * gets bound.\n */\n this._onMousedown = (event) => {\n // Touches trigger both touch and mouse events, so we need to distinguish between mouse events\n // that were triggered via mouse vs touch. To do so, check if the mouse event occurs closely\n // after the previous touch event.\n if (Date.now() - this._lastTouchMs < TOUCH_BUFFER_MS) {\n return;\n }\n // Fake mousedown events are fired by some screen readers when controls are activated by the\n // screen reader. Attribute them to keyboard input modality.\n this._modality.next(isFakeMousedownFromScreenReader(event) ? 'keyboard' : 'mouse');\n this._mostRecentTarget = _getEventTarget(event);\n };\n /**\n * Handles touchstart events. Must be an arrow function in order to preserve the context when it\n * gets bound.\n */\n this._onTouchstart = (event) => {\n // Same scenario as mentioned in _onMousedown, but on touch screen devices, fake touchstart\n // events are fired. Again, attribute to keyboard input modality.\n if (isFakeTouchstartFromScreenReader(event)) {\n this._modality.next('keyboard');\n return;\n }\n // Store the timestamp of this touch event, as it's used to distinguish between mouse events\n // triggered via mouse vs touch.\n this._lastTouchMs = Date.now();\n this._modality.next('touch');\n this._mostRecentTarget = _getEventTarget(event);\n };\n this._options = {\n ...INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS,\n ...options,\n };\n // Skip the first emission as it's null.\n this.modalityDetected = this._modality.pipe(skip(1));\n this.modalityChanged = this.modalityDetected.pipe(distinctUntilChanged());\n // If we're not in a browser, this service should do nothing, as there's no relevant input\n // modality to detect.\n if (_platform.isBrowser) {\n ngZone.runOutsideAngular(() => {\n document.addEventListener('keydown', this._onKeydown, modalityEventListenerOptions);\n document.addEventListener('mousedown', this._onMousedown, modalityEventListenerOptions);\n document.addEventListener('touchstart', this._onTouchstart, modalityEventListenerOptions);\n });\n }\n }\n ngOnDestroy() {\n this._modality.complete();\n if (this._platform.isBrowser) {\n document.removeEventListener('keydown', this._onKeydown, modalityEventListenerOptions);\n document.removeEventListener('mousedown', this._onMousedown, modalityEventListenerOptions);\n document.removeEventListener('touchstart', this._onTouchstart, modalityEventListenerOptions);\n }\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: InputModalityDetector, deps: [{ token: i1.Platform }, { token: i0.NgZone }, { token: DOCUMENT }, { token: INPUT_MODALITY_DETECTOR_OPTIONS, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: InputModalityDetector, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: InputModalityDetector, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [{ type: i1.Platform }, { type: i0.NgZone }, { type: Document, decorators: [{\n type: Inject,\n args: [DOCUMENT]\n }] }, { type: undefined, decorators: [{\n type: Optional\n }, {\n type: Inject,\n args: [INPUT_MODALITY_DETECTOR_OPTIONS]\n }] }] });\n\nconst LIVE_ANNOUNCER_ELEMENT_TOKEN = new InjectionToken('liveAnnouncerElement', {\n providedIn: 'root',\n factory: LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY,\n});\n/** @docs-private */\nfunction LIVE_ANNOUNCER_ELEMENT_TOKEN_FACTORY() {\n return null;\n}\n/** Injection token that can be used to configure the default options for the LiveAnnouncer. */\nconst LIVE_ANNOUNCER_DEFAULT_OPTIONS = new InjectionToken('LIVE_ANNOUNCER_DEFAULT_OPTIONS');\n\nlet uniqueIds = 0;\nclass LiveAnnouncer {\n constructor(elementToken, _ngZone, _document, _defaultOptions) {\n this._ngZone = _ngZone;\n this._defaultOptions = _defaultOptions;\n // We inject the live element and document as `any` because the constructor signature cannot\n // reference browser globals (HTMLElement, Document) on non-browser environments, since having\n // a class decorator causes TypeScript to preserve the constructor signature types.\n this._document = _document;\n this._liveElement = elementToken || this._createLiveElement();\n }\n announce(message, ...args) {\n const defaultOptions = this._defaultOptions;\n let politeness;\n let duration;\n if (args.length === 1 && typeof args[0] === 'number') {\n duration = args[0];\n }\n else {\n [politeness, duration] = args;\n }\n this.clear();\n clearTimeout(this._previousTimeout);\n if (!politeness) {\n politeness =\n defaultOptions && defaultOptions.politeness ? defaultOptions.politeness : 'polite';\n }\n if (duration == null && defaultOptions) {\n duration = defaultOptions.duration;\n }\n // TODO: ensure changing the politeness works on all environments we support.\n this._liveElement.setAttribute('aria-live', politeness);\n if (this._liveElement.id) {\n this._exposeAnnouncerToModals(this._liveElement.id);\n }\n // This 100ms timeout is necessary for some browser + screen-reader combinations:\n // - Both JAWS and NVDA over IE11 will not announce anything without a non-zero timeout.\n // - With Chrome and IE11 with NVDA or JAWS, a repeated (identical) message won't be read a\n // second time without clearing and then using a non-zero delay.\n // (using JAWS 17 at time of this writing).\n return this._ngZone.runOutsideAngular(() => {\n if (!this._currentPromise) {\n this._currentPromise = new Promise(resolve => (this._currentResolve = resolve));\n }\n clearTimeout(this._previousTimeout);\n this._previousTimeout = setTimeout(() => {\n this._liveElement.textContent = message;\n if (typeof duration === 'number') {\n this._previousTimeout = setTimeout(() => this.clear(), duration);\n }\n // For some reason in tests this can be undefined\n // Probably related to ZoneJS and every other thing that patches browser APIs in tests\n this._currentResolve?.();\n this._currentPromise = this._currentResolve = undefined;\n }, 100);\n return this._currentPromise;\n });\n }\n /**\n * Clears the current text from the announcer element. Can be used to prevent\n * screen readers from reading the text out again while the user is going\n * through the page landmarks.\n */\n clear() {\n if (this._liveElement) {\n this._liveElement.textContent = '';\n }\n }\n ngOnDestroy() {\n clearTimeout(this._previousTimeout);\n this._liveElement?.remove();\n this._liveElement = null;\n this._currentResolve?.();\n this._currentPromise = this._currentResolve = undefined;\n }\n _createLiveElement() {\n const elementClass = 'cdk-live-announcer-element';\n const previousElements = this._document.getElementsByClassName(elementClass);\n const liveEl = this._document.createElement('div');\n // Remove any old containers. This can happen when coming in from a server-side-rendered page.\n for (let i = 0; i < previousElements.length; i++) {\n previousElements[i].remove();\n }\n liveEl.classList.add(elementClass);\n liveEl.classList.add('cdk-visually-hidden');\n liveEl.setAttribute('aria-atomic', 'true');\n liveEl.setAttribute('aria-live', 'polite');\n liveEl.id = `cdk-live-announcer-${uniqueIds++}`;\n this._document.body.appendChild(liveEl);\n return liveEl;\n }\n /**\n * Some browsers won't expose the accessibility node of the live announcer element if there is an\n * `aria-modal` and the live announcer is outside of it. This method works around the issue by\n * pointing the `aria-owns` of all modals to the live announcer element.\n */\n _exposeAnnouncerToModals(id) {\n // TODO(http://github.com/angular/components/issues/26853): consider de-duplicating this with\n // the `SnakBarContainer` and other usages.\n //\n // Note that the selector here is limited to CDK overlays at the moment in order to reduce the\n // section of the DOM we need to look through. This should cover all the cases we support, but\n // the selector can be expanded if it turns out to be too narrow.\n const modals = this._document.querySelectorAll('body > .cdk-overlay-container [aria-modal=\"true\"]');\n for (let i = 0; i < modals.length; i++) {\n const modal = modals[i];\n const ariaOwns = modal.getAttribute('aria-owns');\n if (!ariaOwns) {\n modal.setAttribute('aria-owns', id);\n }\n else if (ariaOwns.indexOf(id) === -1) {\n modal.setAttribute('aria-owns', ariaOwns + ' ' + id);\n }\n }\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: LiveAnnouncer, deps: [{ token: LIVE_ANNOUNCER_ELEMENT_TOKEN, optional: true }, { token: i0.NgZone }, { token: DOCUMENT }, { token: LIVE_ANNOUNCER_DEFAULT_OPTIONS, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: LiveAnnouncer, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: LiveAnnouncer, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [{ type: undefined, decorators: [{\n type: Optional\n }, {\n type: Inject,\n args: [LIVE_ANNOUNCER_ELEMENT_TOKEN]\n }] }, { type: i0.NgZone }, { type: undefined, decorators: [{\n type: Inject,\n args: [DOCUMENT]\n }] }, { type: undefined, decorators: [{\n type: Optional\n }, {\n type: Inject,\n args: [LIVE_ANNOUNCER_DEFAULT_OPTIONS]\n }] }] });\n/**\n * A directive that works similarly to aria-live, but uses the LiveAnnouncer to ensure compatibility\n * with a wider range of browsers and screen readers.\n */\nclass CdkAriaLive {\n /** The aria-live politeness level to use when announcing messages. */\n get politeness() {\n return this._politeness;\n }\n set politeness(value) {\n this._politeness = value === 'off' || value === 'assertive' ? value : 'polite';\n if (this._politeness === 'off') {\n if (this._subscription) {\n this._subscription.unsubscribe();\n this._subscription = null;\n }\n }\n else if (!this._subscription) {\n this._subscription = this._ngZone.runOutsideAngular(() => {\n return this._contentObserver.observe(this._elementRef).subscribe(() => {\n // Note that we use textContent here, rather than innerText, in order to avoid a reflow.\n const elementText = this._elementRef.nativeElement.textContent;\n // The `MutationObserver` fires also for attribute\n // changes which we don't want to announce.\n if (elementText !== this._previousAnnouncedText) {\n this._liveAnnouncer.announce(elementText, this._politeness, this.duration);\n this._previousAnnouncedText = elementText;\n }\n });\n });\n }\n }\n constructor(_elementRef, _liveAnnouncer, _contentObserver, _ngZone) {\n this._elementRef = _elementRef;\n this._liveAnnouncer = _liveAnnouncer;\n this._contentObserver = _contentObserver;\n this._ngZone = _ngZone;\n this._politeness = 'polite';\n }\n ngOnDestroy() {\n if (this._subscription) {\n this._subscription.unsubscribe();\n }\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: CdkAriaLive, deps: [{ token: i0.ElementRef }, { token: LiveAnnouncer }, { token: i1$1.ContentObserver }, { token: i0.NgZone }], target: i0.ɵɵFactoryTarget.Directive }); }\n static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: \"14.0.0\", version: \"17.2.0\", type: CdkAriaLive, isStandalone: true, selector: \"[cdkAriaLive]\", inputs: { politeness: [\"cdkAriaLive\", \"politeness\"], duration: [\"cdkAriaLiveDuration\", \"duration\"] }, exportAs: [\"cdkAriaLive\"], ngImport: i0 }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.2.0\", ngImport: i0, type: CdkAriaLive, decorators: [{\n type: Directive,\n args: [{\n selector: '[cdkAriaLive]',\n exportAs: 'cdkAriaLive',\n standalone: true,\n }]\n }], ctorParameters: () => [{ type: i0.ElementRef }, { type: LiveAnnouncer }, { type: i1$1.ContentObserver }, { type: i0.NgZone }], propDecorators: { politeness: [{\n type: Input,\n args: ['cdkAriaLive']\n }], duration: [{\n type: Input,\n args: ['cdkAriaLiveDuration']\n }] } });\n\n/** Detection mode used for attributing the origin of a focus event. */\nvar FocusMonitorDetectionMode;\n(function (FocusMonitorDetectionMode) {\n /**\n * Any mousedown, keydown, or touchstart event that happened in the previous\n * tick or the current tick will be used to assign a focus event's origin (to\n * either mouse, keyboard, or touch). This is the default option.\n */\n FocusMonitorDetectionMode[FocusMonitorDetectionMode[\"IMMEDIATE\"] = 0] = \"IMMEDIATE\";\n /**\n * A focus event's origin is always attributed to the last corresponding\n * mousedown, keydown, or touchstart event, no matter how long ago it occurred.\n */\n FocusMonitorDetectionMode[FocusMonitorDetectionMode[\"EVENTUAL\"] = 1] = \"EVENTUAL\";\n})(FocusMonitorDetectionMode || (FocusMonitorDetectionMode = {}));\n/** InjectionToken for FocusMonitorOptions. */\nconst FOCUS_MONITOR_DEFAULT_OPTIONS = new InjectionToken('cdk-focus-monitor-default-options');\n/**\n * Event listener options that enable capturing and also\n * mark the listener as passive if the browser supports it.\n */\nconst captureEventListenerOptions = normalizePassiveListenerOptions({\n passive: true,\n capture: true,\n});\n/** Monitors mouse and keyboard events to determine the cause of focus events. */\nclass FocusMonitor {\n constructor(_ngZone, _platform, _inputModalityDetector, \n /** @breaking-change 11.0.0 make document required */\n document, options) {\n this._ngZone = _ngZone;\n this._platform = _platform;\n this._inputModalityDetector = _inputModalityDetector;\n /** The focus origin that the next focus event is a result of. */\n this._origin = null;\n /** Whether the window has just been focused. */\n this._windowFocused = false;\n /**\n * Whether the origin was determined via a touch interaction. Necessary as properly attributing\n * focus events to touch interactions requires special logic.\n */\n this._originFromTouchInteraction = false;\n /** Map of elements being monitored to their info. */\n this._elementInfo = new Map();\n /** The number of elements currently being monitored. */\n this._monitoredElementCount = 0;\n /**\n * Keeps track of the root nodes to which we've currently bound a focus/blur handler,\n * as well as the number of monitored elements that they contain. We have to treat focus/blur\n * handlers differently from the rest of the events, because the browser won't emit events\n * to the document when focus moves inside of a shadow root.\n */\n this._rootNodeFocusListenerCount = new Map();\n /**\n * Event listener for `focus` events on the window.\n * Needs to be an arrow function in order to preserve the context when it gets bound.\n */\n this._windowFocusListener = () => {\n // Make a note of when the window regains focus, so we can\n // restore the origin info for the focused element.\n this._windowFocused = true;\n this._windowFocusTimeoutId = window.setTimeout(() => (this._windowFocused = false));\n };\n /** Subject for stopping our InputModalityDetector subscription. */\n this._stopInputModalityDetector = new Subject();\n /**\n * Event listener for `focus` and 'blur' events on the document.\n * Needs to be an arrow function in order to preserve the context when it gets bound.\n */\n this._rootNodeFocusAndBlurListener = (event) => {\n const target = _getEventTarget(event);\n // We need to walk up the ancestor chain in order to support `checkChildren`.\n for (let element = target; element; element = element.parentElement) {\n if (event.type === 'focus') {\n this._onFocus(event, element);\n }\n else {\n this._onBlur(event, element);\n }\n }\n };\n this._document = document;\n this._detectionMode = options?.detectionMode || FocusMonitorDetectionMode.IMMEDIATE;\n }\n monitor(element, checkChildren = false) {\n const nativeElement = coerceElement(element);\n // Do nothing if we're not on the browser platform or the passed in node isn't an element.\n if (!this._platform.isBrowser || nativeElement.nodeType !== 1) {\n // Note: we don't want the observable to emit at all so we don't pass any parameters.\n return of();\n }\n // If the element is inside the shadow DOM, we need to bind our focus/blur listeners to\n // the shadow root, rather than the `document`, because the browser won't emit focus events\n // to the `document`, if focus is moving within the same shadow root.\n const rootNode = _getShadowRoot(nativeElement) || this._getDocument();\n const cachedInfo = this._elementInfo.get(nativeElement);\n // Check if we're already monitoring this element.\n if (cachedInfo) {\n if (checkChildren) {\n // TODO(COMP-318): this can be problematic, because it'll turn all non-checkChildren\n // observers into ones that behave as if `checkChildren` was turned on. We need a more\n // robust solution.\n cachedInfo.checkChildren = true;\n }\n return cachedInfo.subject;\n }\n // Create monitored element info.\n const info = {\n checkChildren: checkChildren,\n subject: new Subject(),\n rootNode,\n };\n this._elementInfo.set(nativeElement, info);\n this._registerGlobalListeners(info);\n return info.subject;\n }\n stopMonitoring(element) {\n const nativeElement = coerceElement(element);\n const elementInfo = this._elementInfo.get(nativeElement);\n if (elementInfo) {\n elementInfo.subject.complete();\n this._setClasses(nativeElement);\n this._elementInfo.delete(nativeElement);\n this._removeGlobalListeners(elementInfo);\n }\n }\n focusVia(element, origin, options) {\n const nativeElement = coerceElement(element);\n const focusedElement = this._getDocument().activeElement;\n // If the element is focused already, calling `focus` again won't trigger the event listener\n // which means that the focus classes won't be updated. If that's the case, update the classes\n // directly without waiting for an event.\n if (nativeElement === focusedElement) {\n this._getClosestElementsInfo(nativeElement).forEach(([currentElement, info]) => this._originChanged(currentElement, origin, info));\n }\n else {\n this._setOrigin(origin);\n // `focus` isn't available on the server\n if (typeof nativeElement.focus === 'function') {\n nativeElement.focus(options);\n }\n }\n }\n ngOnDestroy() {\n this._elementInfo.forEach((_info, element) => this.stopMonitoring(element));\n }\n /** Access injected document if available or fallback to global document reference */\n _getDocument() {\n return this._document || document;\n }\n /** Use defaultView of injected document if available or fallback to global window reference */\n _getWindow() {\n const doc = this._getDocument();\n return doc.defaultView || window;\n }\n _getFocusOrigin(focusEventTarget) {\n if (this._origin) {\n // If the origin was realized via a touch interaction, we need to perform additional checks\n // to determine whether the focus origin should be attributed to touch or program.\n if (this._originFromTouchInteraction) {\n return this._shouldBeAttributedToTouch(focusEventTarget) ? 'touch' : 'program';\n }\n else {\n return this._origin;\n }\n }\n // If the window has just regained focus, we can restore the most recent origin from before the\n // window blurred. Otherwise, we've reached the point where we can't identify the source of the\n // focus. This typically means one of two things happened:\n //\n // 1) The element was programmatically focused, or\n // 2) The element was focused via screen reader navigation (which generally doesn't fire\n // events).\n //\n // Because we can't distinguish between these two cases, we default to setting `program`.\n if (this._windowFocused && this._lastFocusOrigin) {\n return this._lastFocusOrigin;\n }\n // If the interaction is coming from an input label, we consider it a mouse interactions.\n // This is a special case where focus moves on `click`, rather than `mousedown` which breaks\n // our detection, because all our assumptions are for `mousedown`. We need to handle this\n // special case, because it's very common for checkboxes and radio buttons.\n if (focusEventTarget && this._isLastInteractionFromInputLabel(focusEventTarget)) {\n return 'mouse';\n }\n return 'program';\n }\n /**\n * Returns whether the focus event should be attributed to touch. Recall that in IMMEDIATE mode, a\n * touch origin isn't immediately reset at the next tick (see _setOrigin). This means that when we\n * handle a focus event following a touch interaction, we need to determine whether (1) the focus\n * event was directly caused by the touch interaction or (2) the focus event was caused by a\n * subsequent programmatic focus call triggered by the touch interaction.\n * @param focusEventTarget The target of the focus event under examination.\n */\n _shouldBeAttributedToTouch(focusEventTarget) {\n // Please note that this check is not perfect. Consider the following edge case:\n //\n // http://example.com#/foo
,\n * and `PathLocationStrategy` produces\n * http://example.com/foo
as an equivalent URL.\n *\n * See these two classes for more.\n *\n * @publicApi\n */\nclass LocationStrategy {\n historyGo(relativePosition) {\n throw new Error(ngDevMode ? 'Not implemented' : '');\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: LocationStrategy, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: LocationStrategy, providedIn: 'root', useFactory: () => inject(PathLocationStrategy) }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: LocationStrategy, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root', useFactory: () => inject(PathLocationStrategy) }]\n }] });\n/**\n * A predefined [DI token](guide/glossary#di-token) for the base href\n * to be used with the `PathLocationStrategy`.\n * The base href is the URL prefix that should be preserved when generating\n * and recognizing URLs.\n *\n * @usageNotes\n *\n * The following example shows how to use this token to configure the root app injector\n * with a base href value, so that the DI framework can supply the dependency anywhere in the app.\n *\n * ```typescript\n * import {NgModule} from '@angular/core';\n * import {APP_BASE_HREF} from '@angular/common';\n *\n * @NgModule({\n * providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]\n * })\n * class AppModule {}\n * ```\n *\n * @publicApi\n */\nconst APP_BASE_HREF = new InjectionToken(ngDevMode ? 'appBaseHref' : '');\n/**\n * @description\n * A {@link LocationStrategy} used to configure the {@link Location} service to\n * represent its state in the\n * [path](https://en.wikipedia.org/wiki/Uniform_Resource_Locator#Syntax) of the\n * browser's URL.\n *\n * If you're using `PathLocationStrategy`, you may provide a {@link APP_BASE_HREF}\n * or add a `
\n *\n * ```\n * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}\n * ```\n *\n * - `minIntegerDigits`:\n * The minimum number of integer digits before the decimal point.\n * Default is 1.\n *\n * - `minFractionDigits`:\n * The minimum number of digits after the decimal point.\n * Default is 0.\n *\n * - `maxFractionDigits`:\n * The maximum number of digits after the decimal point.\n * Default is 3.\n *\n * If the formatted value is truncated it will be rounded using the \"to-nearest\" method:\n *\n * ```\n * {{3.6 | number: '1.0-0'}}\n * \n *\n * {{-3.6 | number:'1.0-0'}}\n * \n * ```\n *\n * ### locale\n *\n * `locale` will format a value according to locale rules.\n * Locale determines group sizing and separator,\n * decimal point character, and other locale-specific configurations.\n *\n * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.\n *\n * See [Setting your app locale](guide/i18n-common-locale-id).\n *\n * ### Example\n *\n * The following code shows how the pipe transforms values\n * according to various format specifications,\n * where the caller's default locale is `en-US`.\n *\n *
\n * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
.\n * - `minIntegerDigits`: The minimum number of integer digits before the decimal point.\n * Default is `1`.\n * - `minFractionDigits`: The minimum number of digits after the decimal point.\n * Default is `0`.\n * - `maxFractionDigits`: The maximum number of digits after the decimal point.\n * Default is `0`.\n * @param locale A locale code for the locale format rules to use.\n * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.\n * See [Setting your app locale](guide/i18n-common-locale-id).\n */\n transform(value, digitsInfo, locale) {\n if (!isValue(value))\n return null;\n locale ||= this._locale;\n try {\n const num = strToNumber(value);\n return formatPercent(num, locale, digitsInfo);\n }\n catch (error) {\n throw invalidPipeArgumentError(PercentPipe, error.message);\n }\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: PercentPipe, deps: [{ token: LOCALE_ID }], target: i0.ɵɵFactoryTarget.Pipe }); }\n static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: \"14.0.0\", version: \"17.3.10\", ngImport: i0, type: PercentPipe, isStandalone: true, name: \"percent\" }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: PercentPipe, decorators: [{\n type: Pipe,\n args: [{\n name: 'percent',\n standalone: true,\n }]\n }], ctorParameters: () => [{ type: undefined, decorators: [{\n type: Inject,\n args: [LOCALE_ID]\n }] }] });\n/**\n * @ngModule CommonModule\n * @description\n *\n * Transforms a number to a currency string, formatted according to locale rules\n * that determine group sizing and separator, decimal-point character,\n * and other locale-specific configurations.\n *\n *\n * @see {@link getCurrencySymbol}\n * @see {@link formatCurrency}\n *\n * @usageNotes\n * The following code shows how the pipe transforms numbers\n * into text strings, according to various format specifications,\n * where the caller's default locale is `en-US`.\n *\n *
\n * {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
.\n * - `minIntegerDigits`: The minimum number of integer digits before the decimal point.\n * Default is `1`.\n * - `minFractionDigits`: The minimum number of digits after the decimal point.\n * Default is `2`.\n * - `maxFractionDigits`: The maximum number of digits after the decimal point.\n * Default is `2`.\n * If not provided, the number will be formatted with the proper amount of digits,\n * depending on what the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) specifies.\n * For example, the Canadian dollar has 2 digits, whereas the Chilean peso has none.\n * @param locale A locale code for the locale format rules to use.\n * When not supplied, uses the value of `LOCALE_ID`, which is `en-US` by default.\n * See [Setting your app locale](guide/i18n-common-locale-id).\n */\n transform(value, currencyCode = this._defaultCurrencyCode, display = 'symbol', digitsInfo, locale) {\n if (!isValue(value))\n return null;\n locale ||= this._locale;\n if (typeof display === 'boolean') {\n if ((typeof ngDevMode === 'undefined' || ngDevMode) && console && console.warn) {\n console.warn(`Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are \"code\", \"symbol\" or \"symbol-narrow\".`);\n }\n display = display ? 'symbol' : 'code';\n }\n let currency = currencyCode || this._defaultCurrencyCode;\n if (display !== 'code') {\n if (display === 'symbol' || display === 'symbol-narrow') {\n currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale);\n }\n else {\n currency = display;\n }\n }\n try {\n const num = strToNumber(value);\n return formatCurrency(num, locale, currency, currencyCode, digitsInfo);\n }\n catch (error) {\n throw invalidPipeArgumentError(CurrencyPipe, error.message);\n }\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: CurrencyPipe, deps: [{ token: LOCALE_ID }, { token: DEFAULT_CURRENCY_CODE }], target: i0.ɵɵFactoryTarget.Pipe }); }\n static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: \"14.0.0\", version: \"17.3.10\", ngImport: i0, type: CurrencyPipe, isStandalone: true, name: \"currency\" }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: CurrencyPipe, decorators: [{\n type: Pipe,\n args: [{\n name: 'currency',\n standalone: true,\n }]\n }], ctorParameters: () => [{ type: undefined, decorators: [{\n type: Inject,\n args: [LOCALE_ID]\n }] }, { type: undefined, decorators: [{\n type: Inject,\n args: [DEFAULT_CURRENCY_CODE]\n }] }] });\nfunction isValue(value) {\n return !(value == null || value === '' || value !== value);\n}\n/**\n * Transforms a string into a number (if needed).\n */\nfunction strToNumber(value) {\n // Convert strings to numbers\n if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {\n return Number(value);\n }\n if (typeof value !== 'number') {\n throw new Error(`${value} is not a number`);\n }\n return value;\n}\n\n/**\n * @ngModule CommonModule\n * @description\n *\n * Creates a new `Array` or `String` containing a subset (slice) of the elements.\n *\n * @usageNotes\n *\n * All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()`\n * and `String.prototype.slice()`.\n *\n * When operating on an `Array`, the returned `Array` is always a copy even when all\n * the elements are being returned.\n *\n * When operating on a blank value, the pipe returns the blank value.\n *\n * ### List Example\n *\n * This `ngFor` example:\n *\n * {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'}\n *\n * produces the following:\n *\n * ```html\n * \\` tag with an invalid \\`ngSrc\\` attribute: ${url}. ` +\n `This image loader expects \\`ngSrc\\` to be a relative URL - ` +\n `however the provided value is an absolute URL. ` +\n `To fix this, provide \\`ngSrc\\` as a path relative to the base URL ` +\n `configured for this loader (\\`${path}\\`).`);\n}\n\n/**\n * Function that generates an ImageLoader for [Cloudflare Image\n * Resizing](https://developers.cloudflare.com/images/image-resizing/) and turns it into an Angular\n * provider. Note: Cloudflare has multiple image products - this provider is specifically for\n * Cloudflare Image Resizing; it will not work with Cloudflare Images or Cloudflare Polish.\n *\n * @param path Your domain name, e.g. https://mysite.com\n * @returns Provider that provides an ImageLoader function\n *\n * @publicApi\n */\nconst provideCloudflareLoader = createImageLoader(createCloudflareUrl, ngDevMode ? ['https://
\\` tag with the unsupported attribute \"\\`${param}\\`\".`));\n }\n }\n }\n // The \"a\" hostname is used for relative URLs, so we can remove it from the final URL.\n return url.hostname === 'a' ? url.href.replace(url.origin, '') : url.href;\n}\n\n// Assembles directive details string, useful for error messages.\nfunction imgDirectiveDetails(ngSrc, includeNgSrc = true) {\n const ngSrcInfo = includeNgSrc\n ? `(activated on an
element with the \\`ngSrc=\"${ngSrc}\"\\`) `\n : '';\n return `The NgOptimizedImage directive ${ngSrcInfo}has detected that`;\n}\n\n/**\n * Asserts that the application is in development mode. Throws an error if the application is in\n * production mode. This assert can be used to make sure that there is no dev-mode code invoked in\n * the prod mode accidentally.\n */\nfunction assertDevMode(checkName) {\n if (!ngDevMode) {\n throw new ɵRuntimeError(2958 /* RuntimeErrorCode.UNEXPECTED_DEV_MODE_CHECK_IN_PROD_MODE */, `Unexpected invocation of the ${checkName} in the prod mode. ` +\n `Please make sure that the prod mode is enabled for production builds.`);\n }\n}\n\n/**\n * Observer that detects whether an image with `NgOptimizedImage`\n * is treated as a Largest Contentful Paint (LCP) element. If so,\n * asserts that the image has the `priority` attribute.\n *\n * Note: this is a dev-mode only class and it does not appear in prod bundles,\n * thus there is no `ngDevMode` use in the code.\n *\n * Based on https://web.dev/lcp/#measure-lcp-in-javascript.\n */\nclass LCPImageObserver {\n constructor() {\n // Map of full image URLs -> original `ngSrc` values.\n this.images = new Map();\n this.window = null;\n this.observer = null;\n assertDevMode('LCP checker');\n const win = inject(DOCUMENT).defaultView;\n if (typeof win !== 'undefined' && typeof PerformanceObserver !== 'undefined') {\n this.window = win;\n this.observer = this.initPerformanceObserver();\n }\n }\n /**\n * Inits PerformanceObserver and subscribes to LCP events.\n * Based on https://web.dev/lcp/#measure-lcp-in-javascript\n */\n initPerformanceObserver() {\n const observer = new PerformanceObserver((entryList) => {\n const entries = entryList.getEntries();\n if (entries.length === 0)\n return;\n // We use the latest entry produced by the `PerformanceObserver` as the best\n // signal on which element is actually an LCP one. As an example, the first image to load on\n // a page, by virtue of being the only thing on the page so far, is often a LCP candidate\n // and gets reported by PerformanceObserver, but isn't necessarily the LCP element.\n const lcpElement = entries[entries.length - 1];\n // Cast to `any` due to missing `element` on the `LargestContentfulPaint` type of entry.\n // See https://developer.mozilla.org/en-US/docs/Web/API/LargestContentfulPaint\n const imgSrc = lcpElement.element?.src ?? '';\n // Exclude `data:` and `blob:` URLs, since they are not supported by the directive.\n if (imgSrc.startsWith('data:') || imgSrc.startsWith('blob:'))\n return;\n const img = this.images.get(imgSrc);\n if (!img)\n return;\n if (!img.priority && !img.alreadyWarnedPriority) {\n img.alreadyWarnedPriority = true;\n logMissingPriorityError(imgSrc);\n }\n if (img.modified && !img.alreadyWarnedModified) {\n img.alreadyWarnedModified = true;\n logModifiedWarning(imgSrc);\n }\n });\n observer.observe({ type: 'largest-contentful-paint', buffered: true });\n return observer;\n }\n registerImage(rewrittenSrc, originalNgSrc, isPriority) {\n if (!this.observer)\n return;\n const newObservedImageState = {\n priority: isPriority,\n modified: false,\n alreadyWarnedModified: false,\n alreadyWarnedPriority: false,\n };\n this.images.set(getUrl(rewrittenSrc, this.window).href, newObservedImageState);\n }\n unregisterImage(rewrittenSrc) {\n if (!this.observer)\n return;\n this.images.delete(getUrl(rewrittenSrc, this.window).href);\n }\n updateImage(originalSrc, newSrc) {\n const originalUrl = getUrl(originalSrc, this.window).href;\n const img = this.images.get(originalUrl);\n if (img) {\n img.modified = true;\n this.images.set(getUrl(newSrc, this.window).href, img);\n this.images.delete(originalUrl);\n }\n }\n ngOnDestroy() {\n if (!this.observer)\n return;\n this.observer.disconnect();\n this.images.clear();\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: LCPImageObserver, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: LCPImageObserver, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: LCPImageObserver, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [] });\nfunction logMissingPriorityError(ngSrc) {\n const directiveDetails = imgDirectiveDetails(ngSrc);\n console.error(ɵformatRuntimeError(2955 /* RuntimeErrorCode.LCP_IMG_MISSING_PRIORITY */, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` +\n `element but was not marked \"priority\". This image should be marked ` +\n `\"priority\" in order to prioritize its loading. ` +\n `To fix this, add the \"priority\" attribute.`));\n}\nfunction logModifiedWarning(ngSrc) {\n const directiveDetails = imgDirectiveDetails(ngSrc);\n console.warn(ɵformatRuntimeError(2964 /* RuntimeErrorCode.LCP_IMG_NGSRC_MODIFIED */, `${directiveDetails} this image is the Largest Contentful Paint (LCP) ` +\n `element and has had its \"ngSrc\" attribute modified. This can cause ` +\n `slower loading performance. It is recommended not to modify the \"ngSrc\" ` +\n `property on any image which could be the LCP element.`));\n}\n\n// Set of origins that are always excluded from the preconnect checks.\nconst INTERNAL_PRECONNECT_CHECK_BLOCKLIST = new Set(['localhost', '127.0.0.1', '0.0.0.0']);\n/**\n * Injection token to configure which origins should be excluded\n * from the preconnect checks. It can either be a single string or an array of strings\n * to represent a group of origins, for example:\n *\n * ```typescript\n * {provide: PRECONNECT_CHECK_BLOCKLIST, useValue: 'https://your-domain.com'}\n * ```\n *\n * or:\n *\n * ```typescript\n * {provide: PRECONNECT_CHECK_BLOCKLIST,\n * useValue: ['https://your-domain-1.com', 'https://your-domain-2.com']}\n * ```\n *\n * @publicApi\n */\nconst PRECONNECT_CHECK_BLOCKLIST = new InjectionToken(ngDevMode ? 'PRECONNECT_CHECK_BLOCKLIST' : '');\n/**\n * Contains the logic to detect whether an image, marked with the \"priority\" attribute\n * has a corresponding `` tag in the `document.head`.\n *\n * Note: this is a dev-mode only class, which should not appear in prod bundles,\n * thus there is no `ngDevMode` use in the code.\n */\nclass PreconnectLinkChecker {\n constructor() {\n this.document = inject(DOCUMENT);\n /**\n * Set of tags found on this page.\n * The `null` value indicates that there was no DOM query operation performed.\n */\n this.preconnectLinks = null;\n /*\n * Keep track of all already seen origin URLs to avoid repeating the same check.\n */\n this.alreadySeen = new Set();\n this.window = null;\n this.blocklist = new Set(INTERNAL_PRECONNECT_CHECK_BLOCKLIST);\n assertDevMode('preconnect link checker');\n const win = this.document.defaultView;\n if (typeof win !== 'undefined') {\n this.window = win;\n }\n const blocklist = inject(PRECONNECT_CHECK_BLOCKLIST, { optional: true });\n if (blocklist) {\n this.populateBlocklist(blocklist);\n }\n }\n populateBlocklist(origins) {\n if (Array.isArray(origins)) {\n deepForEach(origins, (origin) => {\n this.blocklist.add(extractHostname(origin));\n });\n }\n else {\n this.blocklist.add(extractHostname(origins));\n }\n }\n /**\n * Checks that a preconnect resource hint exists in the head for the\n * given src.\n *\n * @param rewrittenSrc src formatted with loader\n * @param originalNgSrc ngSrc value\n */\n assertPreconnect(rewrittenSrc, originalNgSrc) {\n if (!this.window)\n return;\n const imgUrl = getUrl(rewrittenSrc, this.window);\n if (this.blocklist.has(imgUrl.hostname) || this.alreadySeen.has(imgUrl.origin))\n return;\n // Register this origin as seen, so we don't check it again later.\n this.alreadySeen.add(imgUrl.origin);\n // Note: we query for preconnect links only *once* and cache the results\n // for the entire lifespan of an application, since it's unlikely that the\n // list would change frequently. This allows to make sure there are no\n // performance implications of making extra DOM lookups for each image.\n this.preconnectLinks ??= this.queryPreconnectLinks();\n if (!this.preconnectLinks.has(imgUrl.origin)) {\n console.warn(ɵformatRuntimeError(2956 /* RuntimeErrorCode.PRIORITY_IMG_MISSING_PRECONNECT_TAG */, `${imgDirectiveDetails(originalNgSrc)} there is no preconnect tag present for this ` +\n `image. Preconnecting to the origin(s) that serve priority images ensures that these ` +\n `images are delivered as soon as possible. To fix this, please add the following ` +\n `element into the of the document:\\n` +\n ` `));\n }\n }\n queryPreconnectLinks() {\n const preconnectUrls = new Set();\n const selector = 'link[rel=preconnect]';\n const links = Array.from(this.document.querySelectorAll(selector));\n for (let link of links) {\n const url = getUrl(link.href, this.window);\n preconnectUrls.add(url.origin);\n }\n return preconnectUrls;\n }\n ngOnDestroy() {\n this.preconnectLinks?.clear();\n this.alreadySeen.clear();\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: PreconnectLinkChecker, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: PreconnectLinkChecker, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: PreconnectLinkChecker, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }], ctorParameters: () => [] });\n/**\n * Invokes a callback for each element in the array. Also invokes a callback\n * recursively for each nested array.\n */\nfunction deepForEach(input, fn) {\n for (let value of input) {\n Array.isArray(value) ? deepForEach(value, fn) : fn(value);\n }\n}\n\n/**\n * In SSR scenarios, a preload `` element is generated for priority images.\n * Having a large number of preload tags may negatively affect the performance,\n * so we warn developers (by throwing an error) if the number of preloaded images\n * is above a certain threshold. This const specifies this threshold.\n */\nconst DEFAULT_PRELOADED_IMAGES_LIMIT = 5;\n/**\n * Helps to keep track of priority images that already have a corresponding\n * preload tag (to avoid generating multiple preload tags with the same URL).\n *\n * This Set tracks the original src passed into the `ngSrc` input not the src after it has been\n * run through the specified `IMAGE_LOADER`.\n */\nconst PRELOADED_IMAGES = new InjectionToken('NG_OPTIMIZED_PRELOADED_IMAGES', {\n providedIn: 'root',\n factory: () => new Set(),\n});\n\n/**\n * @description Contains the logic needed to track and add preload link tags to the `` tag. It\n * will also track what images have already had preload link tags added so as to not duplicate link\n * tags.\n *\n * In dev mode this service will validate that the number of preloaded images does not exceed the\n * configured default preloaded images limit: {@link DEFAULT_PRELOADED_IMAGES_LIMIT}.\n */\nclass PreloadLinkCreator {\n constructor() {\n this.preloadedImages = inject(PRELOADED_IMAGES);\n this.document = inject(DOCUMENT);\n }\n /**\n * @description Add a preload `` to the `` of the `index.html` that is served from the\n * server while using Angular Universal and SSR to kick off image loads for high priority images.\n *\n * The `sizes` (passed in from the user) and `srcset` (parsed and formatted from `ngSrcset`)\n * properties used to set the corresponding attributes, `imagesizes` and `imagesrcset`\n * respectively, on the preload `` tag so that the correctly sized image is preloaded from\n * the CDN.\n *\n * {@link https://web.dev/preload-responsive-images/#imagesrcset-and-imagesizes}\n *\n * @param renderer The `Renderer2` passed in from the directive\n * @param src The original src of the image that is set on the `ngSrc` input.\n * @param srcset The parsed and formatted srcset created from the `ngSrcset` input\n * @param sizes The value of the `sizes` attribute passed in to the `
` tag\n */\n createPreloadLinkTag(renderer, src, srcset, sizes) {\n if (ngDevMode) {\n if (this.preloadedImages.size >= DEFAULT_PRELOADED_IMAGES_LIMIT) {\n throw new ɵRuntimeError(2961 /* RuntimeErrorCode.TOO_MANY_PRELOADED_IMAGES */, ngDevMode &&\n `The \\`NgOptimizedImage\\` directive has detected that more than ` +\n `${DEFAULT_PRELOADED_IMAGES_LIMIT} images were marked as priority. ` +\n `This might negatively affect an overall performance of the page. ` +\n `To fix this, remove the \"priority\" attribute from images with less priority.`);\n }\n }\n if (this.preloadedImages.has(src)) {\n return;\n }\n this.preloadedImages.add(src);\n const preload = renderer.createElement('link');\n renderer.setAttribute(preload, 'as', 'image');\n renderer.setAttribute(preload, 'href', src);\n renderer.setAttribute(preload, 'rel', 'preload');\n renderer.setAttribute(preload, 'fetchpriority', 'high');\n if (sizes) {\n renderer.setAttribute(preload, 'imageSizes', sizes);\n }\n if (srcset) {\n renderer.setAttribute(preload, 'imageSrcset', srcset);\n }\n renderer.appendChild(this.document.head, preload);\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: PreloadLinkCreator, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }\n static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: PreloadLinkCreator, providedIn: 'root' }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: PreloadLinkCreator, decorators: [{\n type: Injectable,\n args: [{ providedIn: 'root' }]\n }] });\n\n/**\n * When a Base64-encoded image is passed as an input to the `NgOptimizedImage` directive,\n * an error is thrown. The image content (as a string) might be very long, thus making\n * it hard to read an error message if the entire string is included. This const defines\n * the number of characters that should be included into the error message. The rest\n * of the content is truncated.\n */\nconst BASE64_IMG_MAX_LENGTH_IN_ERROR = 50;\n/**\n * RegExpr to determine whether a src in a srcset is using width descriptors.\n * Should match something like: \"100w, 200w\".\n */\nconst VALID_WIDTH_DESCRIPTOR_SRCSET = /^((\\s*\\d+w\\s*(,|$)){1,})$/;\n/**\n * RegExpr to determine whether a src in a srcset is using density descriptors.\n * Should match something like: \"1x, 2x, 50x\". Also supports decimals like \"1.5x, 1.50x\".\n */\nconst VALID_DENSITY_DESCRIPTOR_SRCSET = /^((\\s*\\d+(\\.\\d+)?x\\s*(,|$)){1,})$/;\n/**\n * Srcset values with a density descriptor higher than this value will actively\n * throw an error. Such densities are not permitted as they cause image sizes\n * to be unreasonably large and slow down LCP.\n */\nconst ABSOLUTE_SRCSET_DENSITY_CAP = 3;\n/**\n * Used only in error message text to communicate best practices, as we will\n * only throw based on the slightly more conservative ABSOLUTE_SRCSET_DENSITY_CAP.\n */\nconst RECOMMENDED_SRCSET_DENSITY_CAP = 2;\n/**\n * Used in generating automatic density-based srcsets\n */\nconst DENSITY_SRCSET_MULTIPLIERS = [1, 2];\n/**\n * Used to determine which breakpoints to use on full-width images\n */\nconst VIEWPORT_BREAKPOINT_CUTOFF = 640;\n/**\n * Used to determine whether two aspect ratios are similar in value.\n */\nconst ASPECT_RATIO_TOLERANCE = 0.1;\n/**\n * Used to determine whether the image has been requested at an overly\n * large size compared to the actual rendered image size (after taking\n * into account a typical device pixel ratio). In pixels.\n */\nconst OVERSIZED_IMAGE_TOLERANCE = 1000;\n/**\n * Used to limit automatic srcset generation of very large sources for\n * fixed-size images. In pixels.\n */\nconst FIXED_SRCSET_WIDTH_LIMIT = 1920;\nconst FIXED_SRCSET_HEIGHT_LIMIT = 1080;\n/**\n * Default blur radius of the CSS filter used on placeholder images, in pixels\n */\nconst PLACEHOLDER_BLUR_AMOUNT = 15;\n/**\n * Used to warn or error when the user provides an overly large dataURL for the placeholder\n * attribute.\n * Character count of Base64 images is 1 character per byte, and base64 encoding is approximately\n * 33% larger than base images, so 4000 characters is around 3KB on disk and 10000 characters is\n * around 7.7KB. Experimentally, 4000 characters is about 20x20px in PNG or medium-quality JPEG\n * format, and 10,000 is around 50x50px, but there's quite a bit of variation depending on how the\n * image is saved.\n */\nconst DATA_URL_WARN_LIMIT = 4000;\nconst DATA_URL_ERROR_LIMIT = 10000;\n/** Info about built-in loaders we can test for. */\nconst BUILT_IN_LOADERS = [\n imgixLoaderInfo,\n imageKitLoaderInfo,\n cloudinaryLoaderInfo,\n netlifyLoaderInfo,\n];\n/**\n * Directive that improves image loading performance by enforcing best practices.\n *\n * `NgOptimizedImage` ensures that the loading of the Largest Contentful Paint (LCP) image is\n * prioritized by:\n * - Automatically setting the `fetchpriority` attribute on the `
` tag\n * - Lazy loading non-priority images by default\n * - Automatically generating a preconnect link tag in the document head\n *\n * In addition, the directive:\n * - Generates appropriate asset URLs if a corresponding `ImageLoader` function is provided\n * - Automatically generates a srcset\n * - Requires that `width` and `height` are set\n * - Warns if `width` or `height` have been set incorrectly\n * - Warns if the image will be visually distorted when rendered\n *\n * @usageNotes\n * The `NgOptimizedImage` directive is marked as [standalone](guide/standalone-components) and can\n * be imported directly.\n *\n * Follow the steps below to enable and use the directive:\n * 1. Import it into the necessary NgModule or a standalone Component.\n * 2. Optionally provide an `ImageLoader` if you use an image hosting service.\n * 3. Update the necessary `
` tags in templates and replace `src` attributes with `ngSrc`.\n * Using a `ngSrc` allows the directive to control when the `src` gets set, which triggers an image\n * download.\n *\n * Step 1: import the `NgOptimizedImage` directive.\n *\n * ```typescript\n * import { NgOptimizedImage } from '@angular/common';\n *\n * // Include it into the necessary NgModule\n * @NgModule({\n * imports: [NgOptimizedImage],\n * })\n * class AppModule {}\n *\n * // ... or a standalone Component\n * @Component({\n * standalone: true\n * imports: [NgOptimizedImage],\n * })\n * class MyStandaloneComponent {}\n * ```\n *\n * Step 2: configure a loader.\n *\n * To use the **default loader**: no additional code changes are necessary. The URL returned by the\n * generic loader will always match the value of \"src\". In other words, this loader applies no\n * transformations to the resource URL and the value of the `ngSrc` attribute will be used as is.\n *\n * To use an existing loader for a **third-party image service**: add the provider factory for your\n * chosen service to the `providers` array. In the example below, the Imgix loader is used:\n *\n * ```typescript\n * import {provideImgixLoader} from '@angular/common';\n *\n * // Call the function and add the result to the `providers` array:\n * providers: [\n * provideImgixLoader(\"https://my.base.url/\"),\n * ],\n * ```\n *\n * The `NgOptimizedImage` directive provides the following functions:\n * - `provideCloudflareLoader`\n * - `provideCloudinaryLoader`\n * - `provideImageKitLoader`\n * - `provideImgixLoader`\n *\n * If you use a different image provider, you can create a custom loader function as described\n * below.\n *\n * To use a **custom loader**: provide your loader function as a value for the `IMAGE_LOADER` DI\n * token.\n *\n * ```typescript\n * import {IMAGE_LOADER, ImageLoaderConfig} from '@angular/common';\n *\n * // Configure the loader using the `IMAGE_LOADER` token.\n * providers: [\n * {\n * provide: IMAGE_LOADER,\n * useValue: (config: ImageLoaderConfig) => {\n * return `https://example.com/${config.src}-${config.width}.jpg}`;\n * }\n * },\n * ],\n * ```\n *\n * Step 3: update `
` tags in templates to use `ngSrc` instead of `src`.\n *\n * ```\n *
\n * ```\n *\n * @publicApi\n */\nclass NgOptimizedImage {\n constructor() {\n this.imageLoader = inject(IMAGE_LOADER);\n this.config = processConfig(inject(ɵIMAGE_CONFIG));\n this.renderer = inject(Renderer2);\n this.imgElement = inject(ElementRef).nativeElement;\n this.injector = inject(Injector);\n this.isServer = isPlatformServer(inject(PLATFORM_ID));\n this.preloadLinkCreator = inject(PreloadLinkCreator);\n // a LCP image observer - should be injected only in the dev mode\n this.lcpObserver = ngDevMode ? this.injector.get(LCPImageObserver) : null;\n /**\n * Calculate the rewritten `src` once and store it.\n * This is needed to avoid repetitive calculations and make sure the directive cleanup in the\n * `ngOnDestroy` does not rely on the `IMAGE_LOADER` logic (which in turn can rely on some other\n * instance that might be already destroyed).\n */\n this._renderedSrc = null;\n /**\n * Indicates whether this image should have a high priority.\n */\n this.priority = false;\n /**\n * Disables automatic srcset generation for this image.\n */\n this.disableOptimizedSrcset = false;\n /**\n * Sets the image to \"fill mode\", which eliminates the height/width requirement and adds\n * styles such that the image fills its containing element.\n */\n this.fill = false;\n }\n /** @nodoc */\n ngOnInit() {\n ɵperformanceMarkFeature('NgOptimizedImage');\n if (ngDevMode) {\n const ngZone = this.injector.get(NgZone);\n assertNonEmptyInput(this, 'ngSrc', this.ngSrc);\n assertValidNgSrcset(this, this.ngSrcset);\n assertNoConflictingSrc(this);\n if (this.ngSrcset) {\n assertNoConflictingSrcset(this);\n }\n assertNotBase64Image(this);\n assertNotBlobUrl(this);\n if (this.fill) {\n assertEmptyWidthAndHeight(this);\n // This leaves the Angular zone to avoid triggering unnecessary change detection cycles when\n // `load` tasks are invoked on images.\n ngZone.runOutsideAngular(() => assertNonZeroRenderedHeight(this, this.imgElement, this.renderer));\n }\n else {\n assertNonEmptyWidthAndHeight(this);\n if (this.height !== undefined) {\n assertGreaterThanZero(this, this.height, 'height');\n }\n if (this.width !== undefined) {\n assertGreaterThanZero(this, this.width, 'width');\n }\n // Only check for distorted images when not in fill mode, where\n // images may be intentionally stretched, cropped or letterboxed.\n ngZone.runOutsideAngular(() => assertNoImageDistortion(this, this.imgElement, this.renderer));\n }\n assertValidLoadingInput(this);\n if (!this.ngSrcset) {\n assertNoComplexSizes(this);\n }\n assertValidPlaceholder(this, this.imageLoader);\n assertNotMissingBuiltInLoader(this.ngSrc, this.imageLoader);\n assertNoNgSrcsetWithoutLoader(this, this.imageLoader);\n assertNoLoaderParamsWithoutLoader(this, this.imageLoader);\n if (this.lcpObserver !== null) {\n const ngZone = this.injector.get(NgZone);\n ngZone.runOutsideAngular(() => {\n this.lcpObserver.registerImage(this.getRewrittenSrc(), this.ngSrc, this.priority);\n });\n }\n if (this.priority) {\n const checker = this.injector.get(PreconnectLinkChecker);\n checker.assertPreconnect(this.getRewrittenSrc(), this.ngSrc);\n }\n }\n if (this.placeholder) {\n this.removePlaceholderOnLoad(this.imgElement);\n }\n this.setHostAttributes();\n }\n setHostAttributes() {\n // Must set width/height explicitly in case they are bound (in which case they will\n // only be reflected and not found by the browser)\n if (this.fill) {\n this.sizes ||= '100vw';\n }\n else {\n this.setHostAttribute('width', this.width.toString());\n this.setHostAttribute('height', this.height.toString());\n }\n this.setHostAttribute('loading', this.getLoadingBehavior());\n this.setHostAttribute('fetchpriority', this.getFetchPriority());\n // The `data-ng-img` attribute flags an image as using the directive, to allow\n // for analysis of the directive's performance.\n this.setHostAttribute('ng-img', 'true');\n // The `src` and `srcset` attributes should be set last since other attributes\n // could affect the image's loading behavior.\n const rewrittenSrcset = this.updateSrcAndSrcset();\n if (this.sizes) {\n this.setHostAttribute('sizes', this.sizes);\n }\n if (this.isServer && this.priority) {\n this.preloadLinkCreator.createPreloadLinkTag(this.renderer, this.getRewrittenSrc(), rewrittenSrcset, this.sizes);\n }\n }\n /** @nodoc */\n ngOnChanges(changes) {\n if (ngDevMode) {\n assertNoPostInitInputChange(this, changes, [\n 'ngSrcset',\n 'width',\n 'height',\n 'priority',\n 'fill',\n 'loading',\n 'sizes',\n 'loaderParams',\n 'disableOptimizedSrcset',\n ]);\n }\n if (changes['ngSrc'] && !changes['ngSrc'].isFirstChange()) {\n const oldSrc = this._renderedSrc;\n this.updateSrcAndSrcset(true);\n const newSrc = this._renderedSrc;\n if (this.lcpObserver !== null && oldSrc && newSrc && oldSrc !== newSrc) {\n const ngZone = this.injector.get(NgZone);\n ngZone.runOutsideAngular(() => {\n this.lcpObserver?.updateImage(oldSrc, newSrc);\n });\n }\n }\n }\n callImageLoader(configWithoutCustomParams) {\n let augmentedConfig = configWithoutCustomParams;\n if (this.loaderParams) {\n augmentedConfig.loaderParams = this.loaderParams;\n }\n return this.imageLoader(augmentedConfig);\n }\n getLoadingBehavior() {\n if (!this.priority && this.loading !== undefined) {\n return this.loading;\n }\n return this.priority ? 'eager' : 'lazy';\n }\n getFetchPriority() {\n return this.priority ? 'high' : 'auto';\n }\n getRewrittenSrc() {\n // ImageLoaderConfig supports setting a width property. However, we're not setting width here\n // because if the developer uses rendered width instead of intrinsic width in the HTML width\n // attribute, the image requested may be too small for 2x+ screens.\n if (!this._renderedSrc) {\n const imgConfig = { src: this.ngSrc };\n // Cache calculated image src to reuse it later in the code.\n this._renderedSrc = this.callImageLoader(imgConfig);\n }\n return this._renderedSrc;\n }\n getRewrittenSrcset() {\n const widthSrcSet = VALID_WIDTH_DESCRIPTOR_SRCSET.test(this.ngSrcset);\n const finalSrcs = this.ngSrcset\n .split(',')\n .filter((src) => src !== '')\n .map((srcStr) => {\n srcStr = srcStr.trim();\n const width = widthSrcSet ? parseFloat(srcStr) : parseFloat(srcStr) * this.width;\n return `${this.callImageLoader({ src: this.ngSrc, width })} ${srcStr}`;\n });\n return finalSrcs.join(', ');\n }\n getAutomaticSrcset() {\n if (this.sizes) {\n return this.getResponsiveSrcset();\n }\n else {\n return this.getFixedSrcset();\n }\n }\n getResponsiveSrcset() {\n const { breakpoints } = this.config;\n let filteredBreakpoints = breakpoints;\n if (this.sizes?.trim() === '100vw') {\n // Since this is a full-screen-width image, our srcset only needs to include\n // breakpoints with full viewport widths.\n filteredBreakpoints = breakpoints.filter((bp) => bp >= VIEWPORT_BREAKPOINT_CUTOFF);\n }\n const finalSrcs = filteredBreakpoints.map((bp) => `${this.callImageLoader({ src: this.ngSrc, width: bp })} ${bp}w`);\n return finalSrcs.join(', ');\n }\n updateSrcAndSrcset(forceSrcRecalc = false) {\n if (forceSrcRecalc) {\n // Reset cached value, so that the followup `getRewrittenSrc()` call\n // will recalculate it and update the cache.\n this._renderedSrc = null;\n }\n const rewrittenSrc = this.getRewrittenSrc();\n this.setHostAttribute('src', rewrittenSrc);\n let rewrittenSrcset = undefined;\n if (this.ngSrcset) {\n rewrittenSrcset = this.getRewrittenSrcset();\n }\n else if (this.shouldGenerateAutomaticSrcset()) {\n rewrittenSrcset = this.getAutomaticSrcset();\n }\n if (rewrittenSrcset) {\n this.setHostAttribute('srcset', rewrittenSrcset);\n }\n return rewrittenSrcset;\n }\n getFixedSrcset() {\n const finalSrcs = DENSITY_SRCSET_MULTIPLIERS.map((multiplier) => `${this.callImageLoader({\n src: this.ngSrc,\n width: this.width * multiplier,\n })} ${multiplier}x`);\n return finalSrcs.join(', ');\n }\n shouldGenerateAutomaticSrcset() {\n let oversizedImage = false;\n if (!this.sizes) {\n oversizedImage =\n this.width > FIXED_SRCSET_WIDTH_LIMIT || this.height > FIXED_SRCSET_HEIGHT_LIMIT;\n }\n return (!this.disableOptimizedSrcset &&\n !this.srcset &&\n this.imageLoader !== noopImageLoader &&\n !oversizedImage);\n }\n /**\n * Returns an image url formatted for use with the CSS background-image property. Expects one of:\n * * A base64 encoded image, which is wrapped and passed through.\n * * A boolean. If true, calls the image loader to generate a small placeholder url.\n */\n generatePlaceholder(placeholderInput) {\n const { placeholderResolution } = this.config;\n if (placeholderInput === true) {\n return `url(${this.callImageLoader({\n src: this.ngSrc,\n width: placeholderResolution,\n isPlaceholder: true,\n })})`;\n }\n else if (typeof placeholderInput === 'string' && placeholderInput.startsWith('data:')) {\n return `url(${placeholderInput})`;\n }\n return null;\n }\n /**\n * Determines if blur should be applied, based on an optional boolean\n * property `blur` within the optional configuration object `placeholderConfig`.\n */\n shouldBlurPlaceholder(placeholderConfig) {\n if (!placeholderConfig || !placeholderConfig.hasOwnProperty('blur')) {\n return true;\n }\n return Boolean(placeholderConfig.blur);\n }\n removePlaceholderOnLoad(img) {\n const callback = () => {\n const changeDetectorRef = this.injector.get(ChangeDetectorRef);\n removeLoadListenerFn();\n removeErrorListenerFn();\n this.placeholder = false;\n changeDetectorRef.markForCheck();\n };\n const removeLoadListenerFn = this.renderer.listen(img, 'load', callback);\n const removeErrorListenerFn = this.renderer.listen(img, 'error', callback);\n }\n /** @nodoc */\n ngOnDestroy() {\n if (ngDevMode) {\n if (!this.priority && this._renderedSrc !== null && this.lcpObserver !== null) {\n this.lcpObserver.unregisterImage(this._renderedSrc);\n }\n }\n }\n setHostAttribute(name, value) {\n this.renderer.setAttribute(this.imgElement, name, value);\n }\n static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: NgOptimizedImage, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }\n static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: \"16.1.0\", version: \"17.3.10\", type: NgOptimizedImage, isStandalone: true, selector: \"img[ngSrc]\", inputs: { ngSrc: [\"ngSrc\", \"ngSrc\", unwrapSafeUrl], ngSrcset: \"ngSrcset\", sizes: \"sizes\", width: [\"width\", \"width\", numberAttribute], height: [\"height\", \"height\", numberAttribute], loading: \"loading\", priority: [\"priority\", \"priority\", booleanAttribute], loaderParams: \"loaderParams\", disableOptimizedSrcset: [\"disableOptimizedSrcset\", \"disableOptimizedSrcset\", booleanAttribute], fill: [\"fill\", \"fill\", booleanAttribute], placeholder: [\"placeholder\", \"placeholder\", booleanOrDataUrlAttribute], placeholderConfig: \"placeholderConfig\", src: \"src\", srcset: \"srcset\" }, host: { properties: { \"style.position\": \"fill ? \\\"absolute\\\" : null\", \"style.width\": \"fill ? \\\"100%\\\" : null\", \"style.height\": \"fill ? \\\"100%\\\" : null\", \"style.inset\": \"fill ? \\\"0\\\" : null\", \"style.background-size\": \"placeholder ? \\\"cover\\\" : null\", \"style.background-position\": \"placeholder ? \\\"50% 50%\\\" : null\", \"style.background-repeat\": \"placeholder ? \\\"no-repeat\\\" : null\", \"style.background-image\": \"placeholder ? generatePlaceholder(placeholder) : null\", \"style.filter\": \"placeholder && shouldBlurPlaceholder(placeholderConfig) ? \\\"blur(15px)\\\" : null\" } }, usesOnChanges: true, ngImport: i0 }); }\n}\ni0.ɵɵngDeclareClassMetadata({ minVersion: \"12.0.0\", version: \"17.3.10\", ngImport: i0, type: NgOptimizedImage, decorators: [{\n type: Directive,\n args: [{\n standalone: true,\n selector: 'img[ngSrc]',\n host: {\n '[style.position]': 'fill ? \"absolute\" : null',\n '[style.width]': 'fill ? \"100%\" : null',\n '[style.height]': 'fill ? \"100%\" : null',\n '[style.inset]': 'fill ? \"0\" : null',\n '[style.background-size]': 'placeholder ? \"cover\" : null',\n '[style.background-position]': 'placeholder ? \"50% 50%\" : null',\n '[style.background-repeat]': 'placeholder ? \"no-repeat\" : null',\n '[style.background-image]': 'placeholder ? generatePlaceholder(placeholder) : null',\n '[style.filter]': `placeholder && shouldBlurPlaceholder(placeholderConfig) ? \"blur(${PLACEHOLDER_BLUR_AMOUNT}px)\" : null`,\n },\n }]\n }], propDecorators: { ngSrc: [{\n type: Input,\n args: [{ required: true, transform: unwrapSafeUrl }]\n }], ngSrcset: [{\n type: Input\n }], sizes: [{\n type: Input\n }], width: [{\n type: Input,\n args: [{ transform: numberAttribute }]\n }], height: [{\n type: Input,\n args: [{ transform: numberAttribute }]\n }], loading: [{\n type: Input\n }], priority: [{\n type: Input,\n args: [{ transform: booleanAttribute }]\n }], loaderParams: [{\n type: Input\n }], disableOptimizedSrcset: [{\n type: Input,\n args: [{ transform: booleanAttribute }]\n }], fill: [{\n type: Input,\n args: [{ transform: booleanAttribute }]\n }], placeholder: [{\n type: Input,\n args: [{ transform: booleanOrDataUrlAttribute }]\n }], placeholderConfig: [{\n type: Input\n }], src: [{\n type: Input\n }], srcset: [{\n type: Input\n }] } });\n/***** Helpers *****/\n/**\n * Sorts provided config breakpoints and uses defaults.\n */\nfunction processConfig(config) {\n let sortedBreakpoints = {};\n if (config.breakpoints) {\n sortedBreakpoints.breakpoints = config.breakpoints.sort((a, b) => a - b);\n }\n return Object.assign({}, ɵIMAGE_CONFIG_DEFAULTS, config, sortedBreakpoints);\n}\n/***** Assert functions *****/\n/**\n * Verifies that there is no `src` set on a host element.\n */\nfunction assertNoConflictingSrc(dir) {\n if (dir.src) {\n throw new ɵRuntimeError(2950 /* RuntimeErrorCode.UNEXPECTED_SRC_ATTR */, `${imgDirectiveDetails(dir.ngSrc)} both \\`src\\` and \\`ngSrc\\` have been set. ` +\n `Supplying both of these attributes breaks lazy loading. ` +\n `The NgOptimizedImage directive sets \\`src\\` itself based on the value of \\`ngSrc\\`. ` +\n `To fix this, please remove the \\`src\\` attribute.`);\n }\n}\n/**\n * Verifies that there is no `srcset` set on a host element.\n */\nfunction assertNoConflictingSrcset(dir) {\n if (dir.srcset) {\n throw new ɵRuntimeError(2951 /* RuntimeErrorCode.UNEXPECTED_SRCSET_ATTR */, `${imgDirectiveDetails(dir.ngSrc)} both \\`srcset\\` and \\`ngSrcset\\` have been set. ` +\n `Supplying both of these attributes breaks lazy loading. ` +\n `The NgOptimizedImage directive sets \\`srcset\\` itself based on the value of ` +\n `\\`ngSrcset\\`. To fix this, please remove the \\`srcset\\` attribute.`);\n }\n}\n/**\n * Verifies that the `ngSrc` is not a Base64-encoded image.\n */\nfunction assertNotBase64Image(dir) {\n let ngSrc = dir.ngSrc.trim();\n if (ngSrc.startsWith('data:')) {\n if (ngSrc.length > BASE64_IMG_MAX_LENGTH_IN_ERROR) {\n ngSrc = ngSrc.substring(0, BASE64_IMG_MAX_LENGTH_IN_ERROR) + '...';\n }\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \\`ngSrc\\` is a Base64-encoded string ` +\n `(${ngSrc}). NgOptimizedImage does not support Base64-encoded strings. ` +\n `To fix this, disable the NgOptimizedImage directive for this element ` +\n `by removing \\`ngSrc\\` and using a standard \\`src\\` attribute instead.`);\n }\n}\n/**\n * Verifies that the 'sizes' only includes responsive values.\n */\nfunction assertNoComplexSizes(dir) {\n let sizes = dir.sizes;\n if (sizes?.match(/((\\)|,)\\s|^)\\d+px/)) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \\`sizes\\` was set to a string including ` +\n `pixel values. For automatic \\`srcset\\` generation, \\`sizes\\` must only include responsive ` +\n `values, such as \\`sizes=\"50vw\"\\` or \\`sizes=\"(min-width: 768px) 50vw, 100vw\"\\`. ` +\n `To fix this, modify the \\`sizes\\` attribute, or provide your own \\`ngSrcset\\` value directly.`);\n }\n}\nfunction assertValidPlaceholder(dir, imageLoader) {\n assertNoPlaceholderConfigWithoutPlaceholder(dir);\n assertNoRelativePlaceholderWithoutLoader(dir, imageLoader);\n assertNoOversizedDataUrl(dir);\n}\n/**\n * Verifies that placeholderConfig isn't being used without placeholder\n */\nfunction assertNoPlaceholderConfigWithoutPlaceholder(dir) {\n if (dir.placeholderConfig && !dir.placeholder) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc, false)} \\`placeholderConfig\\` options were provided for an ` +\n `image that does not use the \\`placeholder\\` attribute, and will have no effect.`);\n }\n}\n/**\n * Warns if a relative URL placeholder is specified, but no loader is present to provide the small\n * image.\n */\nfunction assertNoRelativePlaceholderWithoutLoader(dir, imageLoader) {\n if (dir.placeholder === true && imageLoader === noopImageLoader) {\n throw new ɵRuntimeError(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \\`placeholder\\` attribute is set to true but ` +\n `no image loader is configured (i.e. the default one is being used), ` +\n `which would result in the same image being used for the primary image and its placeholder. ` +\n `To fix this, provide a loader or remove the \\`placeholder\\` attribute from the image.`);\n }\n}\n/**\n * Warns or throws an error if an oversized dataURL placeholder is provided.\n */\nfunction assertNoOversizedDataUrl(dir) {\n if (dir.placeholder &&\n typeof dir.placeholder === 'string' &&\n dir.placeholder.startsWith('data:')) {\n if (dir.placeholder.length > DATA_URL_ERROR_LIMIT) {\n throw new ɵRuntimeError(2965 /* RuntimeErrorCode.OVERSIZED_PLACEHOLDER */, `${imgDirectiveDetails(dir.ngSrc)} the \\`placeholder\\` attribute is set to a data URL which is longer ` +\n `than ${DATA_URL_ERROR_LIMIT} characters. This is strongly discouraged, as large inline placeholders ` +\n `directly increase the bundle size of Angular and hurt page load performance. To fix this, generate ` +\n `a smaller data URL placeholder.`);\n }\n if (dir.placeholder.length > DATA_URL_WARN_LIMIT) {\n console.warn(ɵformatRuntimeError(2965 /* RuntimeErrorCode.OVERSIZED_PLACEHOLDER */, `${imgDirectiveDetails(dir.ngSrc)} the \\`placeholder\\` attribute is set to a data URL which is longer ` +\n `than ${DATA_URL_WARN_LIMIT} characters. This is discouraged, as large inline placeholders ` +\n `directly increase the bundle size of Angular and hurt page load performance. For better loading performance, ` +\n `generate a smaller data URL placeholder.`));\n }\n }\n}\n/**\n * Verifies that the `ngSrc` is not a Blob URL.\n */\nfunction assertNotBlobUrl(dir) {\n const ngSrc = dir.ngSrc.trim();\n if (ngSrc.startsWith('blob:')) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \\`ngSrc\\` was set to a blob URL (${ngSrc}). ` +\n `Blob URLs are not supported by the NgOptimizedImage directive. ` +\n `To fix this, disable the NgOptimizedImage directive for this element ` +\n `by removing \\`ngSrc\\` and using a regular \\`src\\` attribute instead.`);\n }\n}\n/**\n * Verifies that the input is set to a non-empty string.\n */\nfunction assertNonEmptyInput(dir, name, value) {\n const isString = typeof value === 'string';\n const isEmptyString = isString && value.trim() === '';\n if (!isString || isEmptyString) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \\`${name}\\` has an invalid value ` +\n `(\\`${value}\\`). To fix this, change the value to a non-empty string.`);\n }\n}\n/**\n * Verifies that the `ngSrcset` is in a valid format, e.g. \"100w, 200w\" or \"1x, 2x\".\n */\nfunction assertValidNgSrcset(dir, value) {\n if (value == null)\n return;\n assertNonEmptyInput(dir, 'ngSrcset', value);\n const stringVal = value;\n const isValidWidthDescriptor = VALID_WIDTH_DESCRIPTOR_SRCSET.test(stringVal);\n const isValidDensityDescriptor = VALID_DENSITY_DESCRIPTOR_SRCSET.test(stringVal);\n if (isValidDensityDescriptor) {\n assertUnderDensityCap(dir, stringVal);\n }\n const isValidSrcset = isValidWidthDescriptor || isValidDensityDescriptor;\n if (!isValidSrcset) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \\`ngSrcset\\` has an invalid value (\\`${value}\\`). ` +\n `To fix this, supply \\`ngSrcset\\` using a comma-separated list of one or more width ` +\n `descriptors (e.g. \"100w, 200w\") or density descriptors (e.g. \"1x, 2x\").`);\n }\n}\nfunction assertUnderDensityCap(dir, value) {\n const underDensityCap = value\n .split(',')\n .every((num) => num === '' || parseFloat(num) <= ABSOLUTE_SRCSET_DENSITY_CAP);\n if (!underDensityCap) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \\`ngSrcset\\` contains an unsupported image density:` +\n `\\`${value}\\`. NgOptimizedImage generally recommends a max image density of ` +\n `${RECOMMENDED_SRCSET_DENSITY_CAP}x but supports image densities up to ` +\n `${ABSOLUTE_SRCSET_DENSITY_CAP}x. The human eye cannot distinguish between image densities ` +\n `greater than ${RECOMMENDED_SRCSET_DENSITY_CAP}x - which makes them unnecessary for ` +\n `most use cases. Images that will be pinch-zoomed are typically the primary use case for ` +\n `${ABSOLUTE_SRCSET_DENSITY_CAP}x images. Please remove the high density descriptor and try again.`);\n }\n}\n/**\n * Creates a `RuntimeError` instance to represent a situation when an input is set after\n * the directive has initialized.\n */\nfunction postInitInputChangeError(dir, inputName) {\n let reason;\n if (inputName === 'width' || inputName === 'height') {\n reason =\n `Changing \\`${inputName}\\` may result in different attribute value ` +\n `applied to the underlying image element and cause layout shifts on a page.`;\n }\n else {\n reason =\n `Changing the \\`${inputName}\\` would have no effect on the underlying ` +\n `image element, because the resource loading has already occurred.`;\n }\n return new ɵRuntimeError(2953 /* RuntimeErrorCode.UNEXPECTED_INPUT_CHANGE */, `${imgDirectiveDetails(dir.ngSrc)} \\`${inputName}\\` was updated after initialization. ` +\n `The NgOptimizedImage directive will not react to this input change. ${reason} ` +\n `To fix this, either switch \\`${inputName}\\` to a static value ` +\n `or wrap the image element in an *ngIf that is gated on the necessary value.`);\n}\n/**\n * Verify that none of the listed inputs has changed.\n */\nfunction assertNoPostInitInputChange(dir, changes, inputs) {\n inputs.forEach((input) => {\n const isUpdated = changes.hasOwnProperty(input);\n if (isUpdated && !changes[input].isFirstChange()) {\n if (input === 'ngSrc') {\n // When the `ngSrc` input changes, we detect that only in the\n // `ngOnChanges` hook, thus the `ngSrc` is already set. We use\n // `ngSrc` in the error message, so we use a previous value, but\n // not the updated one in it.\n dir = { ngSrc: changes[input].previousValue };\n }\n throw postInitInputChangeError(dir, input);\n }\n });\n}\n/**\n * Verifies that a specified input is a number greater than 0.\n */\nfunction assertGreaterThanZero(dir, inputValue, inputName) {\n const validNumber = typeof inputValue === 'number' && inputValue > 0;\n const validString = typeof inputValue === 'string' && /^\\d+$/.test(inputValue.trim()) && parseInt(inputValue) > 0;\n if (!validNumber && !validString) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} \\`${inputName}\\` has an invalid value. ` +\n `To fix this, provide \\`${inputName}\\` as a number greater than 0.`);\n }\n}\n/**\n * Verifies that the rendered image is not visually distorted. Effectively this is checking:\n * - Whether the \"width\" and \"height\" attributes reflect the actual dimensions of the image.\n * - Whether image styling is \"correct\" (see below for a longer explanation).\n */\nfunction assertNoImageDistortion(dir, img, renderer) {\n const removeLoadListenerFn = renderer.listen(img, 'load', () => {\n removeLoadListenerFn();\n removeErrorListenerFn();\n const computedStyle = window.getComputedStyle(img);\n let renderedWidth = parseFloat(computedStyle.getPropertyValue('width'));\n let renderedHeight = parseFloat(computedStyle.getPropertyValue('height'));\n const boxSizing = computedStyle.getPropertyValue('box-sizing');\n if (boxSizing === 'border-box') {\n const paddingTop = computedStyle.getPropertyValue('padding-top');\n const paddingRight = computedStyle.getPropertyValue('padding-right');\n const paddingBottom = computedStyle.getPropertyValue('padding-bottom');\n const paddingLeft = computedStyle.getPropertyValue('padding-left');\n renderedWidth -= parseFloat(paddingRight) + parseFloat(paddingLeft);\n renderedHeight -= parseFloat(paddingTop) + parseFloat(paddingBottom);\n }\n const renderedAspectRatio = renderedWidth / renderedHeight;\n const nonZeroRenderedDimensions = renderedWidth !== 0 && renderedHeight !== 0;\n const intrinsicWidth = img.naturalWidth;\n const intrinsicHeight = img.naturalHeight;\n const intrinsicAspectRatio = intrinsicWidth / intrinsicHeight;\n const suppliedWidth = dir.width;\n const suppliedHeight = dir.height;\n const suppliedAspectRatio = suppliedWidth / suppliedHeight;\n // Tolerance is used to account for the impact of subpixel rendering.\n // Due to subpixel rendering, the rendered, intrinsic, and supplied\n // aspect ratios of a correctly configured image may not exactly match.\n // For example, a `width=4030 height=3020` image might have a rendered\n // size of \"1062w, 796.48h\". (An aspect ratio of 1.334... vs. 1.333...)\n const inaccurateDimensions = Math.abs(suppliedAspectRatio - intrinsicAspectRatio) > ASPECT_RATIO_TOLERANCE;\n const stylingDistortion = nonZeroRenderedDimensions &&\n Math.abs(intrinsicAspectRatio - renderedAspectRatio) > ASPECT_RATIO_TOLERANCE;\n if (inaccurateDimensions) {\n console.warn(ɵformatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the image does not match ` +\n `the aspect ratio indicated by the width and height attributes. ` +\n `\\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` +\n `(aspect-ratio: ${round(intrinsicAspectRatio)}). \\nSupplied width and height attributes: ` +\n `${suppliedWidth}w x ${suppliedHeight}h (aspect-ratio: ${round(suppliedAspectRatio)}). ` +\n `\\nTo fix this, update the width and height attributes.`));\n }\n else if (stylingDistortion) {\n console.warn(ɵformatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the aspect ratio of the rendered image ` +\n `does not match the image's intrinsic aspect ratio. ` +\n `\\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h ` +\n `(aspect-ratio: ${round(intrinsicAspectRatio)}). \\nRendered image size: ` +\n `${renderedWidth}w x ${renderedHeight}h (aspect-ratio: ` +\n `${round(renderedAspectRatio)}). \\nThis issue can occur if \"width\" and \"height\" ` +\n `attributes are added to an image without updating the corresponding ` +\n `image styling. To fix this, adjust image styling. In most cases, ` +\n `adding \"height: auto\" or \"width: auto\" to the image styling will fix ` +\n `this issue.`));\n }\n else if (!dir.ngSrcset && nonZeroRenderedDimensions) {\n // If `ngSrcset` hasn't been set, sanity check the intrinsic size.\n const recommendedWidth = RECOMMENDED_SRCSET_DENSITY_CAP * renderedWidth;\n const recommendedHeight = RECOMMENDED_SRCSET_DENSITY_CAP * renderedHeight;\n const oversizedWidth = intrinsicWidth - recommendedWidth >= OVERSIZED_IMAGE_TOLERANCE;\n const oversizedHeight = intrinsicHeight - recommendedHeight >= OVERSIZED_IMAGE_TOLERANCE;\n if (oversizedWidth || oversizedHeight) {\n console.warn(ɵformatRuntimeError(2960 /* RuntimeErrorCode.OVERSIZED_IMAGE */, `${imgDirectiveDetails(dir.ngSrc)} the intrinsic image is significantly ` +\n `larger than necessary. ` +\n `\\nRendered image size: ${renderedWidth}w x ${renderedHeight}h. ` +\n `\\nIntrinsic image size: ${intrinsicWidth}w x ${intrinsicHeight}h. ` +\n `\\nRecommended intrinsic image size: ${recommendedWidth}w x ${recommendedHeight}h. ` +\n `\\nNote: Recommended intrinsic image size is calculated assuming a maximum DPR of ` +\n `${RECOMMENDED_SRCSET_DENSITY_CAP}. To improve loading time, resize the image ` +\n `or consider using the \"ngSrcset\" and \"sizes\" attributes.`));\n }\n }\n });\n // We only listen to the `error` event to remove the `load` event listener because it will not be\n // fired if the image fails to load. This is done to prevent memory leaks in development mode\n // because image elements aren't garbage-collected properly. It happens because zone.js stores the\n // event listener directly on the element and closures capture `dir`.\n const removeErrorListenerFn = renderer.listen(img, 'error', () => {\n removeLoadListenerFn();\n removeErrorListenerFn();\n });\n}\n/**\n * Verifies that a specified input is set.\n */\nfunction assertNonEmptyWidthAndHeight(dir) {\n let missingAttributes = [];\n if (dir.width === undefined)\n missingAttributes.push('width');\n if (dir.height === undefined)\n missingAttributes.push('height');\n if (missingAttributes.length > 0) {\n throw new ɵRuntimeError(2954 /* RuntimeErrorCode.REQUIRED_INPUT_MISSING */, `${imgDirectiveDetails(dir.ngSrc)} these required attributes ` +\n `are missing: ${missingAttributes.map((attr) => `\"${attr}\"`).join(', ')}. ` +\n `Including \"width\" and \"height\" attributes will prevent image-related layout shifts. ` +\n `To fix this, include \"width\" and \"height\" attributes on the image tag or turn on ` +\n `\"fill\" mode with the \\`fill\\` attribute.`);\n }\n}\n/**\n * Verifies that width and height are not set. Used in fill mode, where those attributes don't make\n * sense.\n */\nfunction assertEmptyWidthAndHeight(dir) {\n if (dir.width || dir.height) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the attributes \\`height\\` and/or \\`width\\` are present ` +\n `along with the \\`fill\\` attribute. Because \\`fill\\` mode causes an image to fill its containing ` +\n `element, the size attributes have no effect and should be removed.`);\n }\n}\n/**\n * Verifies that the rendered image has a nonzero height. If the image is in fill mode, provides\n * guidance that this can be caused by the containing element's CSS position property.\n */\nfunction assertNonZeroRenderedHeight(dir, img, renderer) {\n const removeLoadListenerFn = renderer.listen(img, 'load', () => {\n removeLoadListenerFn();\n removeErrorListenerFn();\n const renderedHeight = img.clientHeight;\n if (dir.fill && renderedHeight === 0) {\n console.warn(ɵformatRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the height of the fill-mode image is zero. ` +\n `This is likely because the containing element does not have the CSS 'position' ` +\n `property set to one of the following: \"relative\", \"fixed\", or \"absolute\". ` +\n `To fix this problem, make sure the container element has the CSS 'position' ` +\n `property defined and the height of the element is not zero.`));\n }\n });\n // See comments in the `assertNoImageDistortion`.\n const removeErrorListenerFn = renderer.listen(img, 'error', () => {\n removeLoadListenerFn();\n removeErrorListenerFn();\n });\n}\n/**\n * Verifies that the `loading` attribute is set to a valid input &\n * is not used on priority images.\n */\nfunction assertValidLoadingInput(dir) {\n if (dir.loading && dir.priority) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \\`loading\\` attribute ` +\n `was used on an image that was marked \"priority\". ` +\n `Setting \\`loading\\` on priority images is not allowed ` +\n `because these images will always be eagerly loaded. ` +\n `To fix this, remove the “loading” attribute from the priority image.`);\n }\n const validInputs = ['auto', 'eager', 'lazy'];\n if (typeof dir.loading === 'string' && !validInputs.includes(dir.loading)) {\n throw new ɵRuntimeError(2952 /* RuntimeErrorCode.INVALID_INPUT */, `${imgDirectiveDetails(dir.ngSrc)} the \\`loading\\` attribute ` +\n `has an invalid value (\\`${dir.loading}\\`). ` +\n `To fix this, provide a valid value (\"lazy\", \"eager\", or \"auto\").`);\n }\n}\n/**\n * Warns if NOT using a loader (falling back to the generic loader) and\n * the image appears to be hosted on one of the image CDNs for which\n * we do have a built-in image loader. Suggests switching to the\n * built-in loader.\n *\n * @param ngSrc Value of the ngSrc attribute\n * @param imageLoader ImageLoader provided\n */\nfunction assertNotMissingBuiltInLoader(ngSrc, imageLoader) {\n if (imageLoader === noopImageLoader) {\n let builtInLoaderName = '';\n for (const loader of BUILT_IN_LOADERS) {\n if (loader.testUrl(ngSrc)) {\n builtInLoaderName = loader.name;\n break;\n }\n }\n if (builtInLoaderName) {\n console.warn(ɵformatRuntimeError(2962 /* RuntimeErrorCode.MISSING_BUILTIN_LOADER */, `NgOptimizedImage: It looks like your images may be hosted on the ` +\n `${builtInLoaderName} CDN, but your app is not using Angular's ` +\n `built-in loader for that CDN. We recommend switching to use ` +\n `the built-in by calling \\`provide${builtInLoaderName}Loader()\\` ` +\n `in your \\`providers\\` and passing it your instance's base URL. ` +\n `If you don't want to use the built-in loader, define a custom ` +\n `loader function using IMAGE_LOADER to silence this warning.`));\n }\n }\n}\n/**\n * Warns if ngSrcset is present and no loader is configured (i.e. the default one is being used).\n */\nfunction assertNoNgSrcsetWithoutLoader(dir, imageLoader) {\n if (dir.ngSrcset && imageLoader === noopImageLoader) {\n console.warn(ɵformatRuntimeError(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \\`ngSrcset\\` attribute is present but ` +\n `no image loader is configured (i.e. the default one is being used), ` +\n `which would result in the same image being used for all configured sizes. ` +\n `To fix this, provide a loader or remove the \\`ngSrcset\\` attribute from the image.`));\n }\n}\n/**\n * Warns if loaderParams is present and no loader is configured (i.e. the default one is being\n * used).\n */\nfunction assertNoLoaderParamsWithoutLoader(dir, imageLoader) {\n if (dir.loaderParams && imageLoader === noopImageLoader) {\n console.warn(ɵformatRuntimeError(2963 /* RuntimeErrorCode.MISSING_NECESSARY_LOADER */, `${imgDirectiveDetails(dir.ngSrc)} the \\`loaderParams\\` attribute is present but ` +\n `no image loader is configured (i.e. the default one is being used), ` +\n `which means that the loaderParams data will not be consumed and will not affect the URL. ` +\n `To fix this, provide a custom loader or remove the \\`loaderParams\\` attribute from the image.`));\n }\n}\nfunction round(input) {\n return Number.isInteger(input) ? input : input.toFixed(2);\n}\n// Transform function to handle SafeValue input for ngSrc. This doesn't do any sanitization,\n// as that is not needed for img.src and img.srcset. This transform is purely for compatibility.\nfunction unwrapSafeUrl(value) {\n if (typeof value === 'string') {\n return value;\n }\n return ɵunwrapSafeValue(value);\n}\n// Transform function to handle inputs which may be booleans, strings, or string representations\n// of boolean values. Used for the placeholder attribute.\nfunction booleanOrDataUrlAttribute(value) {\n if (typeof value === 'string' && value.startsWith(`data:`)) {\n return value;\n }\n return booleanAttribute(value);\n}\n\n/**\n * @module\n * @description\n * Entry point for all public APIs of the common package.\n */\n\n/**\n * @module\n * @description\n * Entry point for all public APIs of this package.\n */\n// This file only reexports content of the `src` folder. Keep it that way.\n\n// This file is not used to build this module. It is only used during editing\n\n/**\n * Generated bundle index. Do not edit.\n */\n\nexport { APP_BASE_HREF, AsyncPipe, BrowserPlatformLocation, CommonModule, CurrencyPipe, DATE_PIPE_DEFAULT_OPTIONS, DATE_PIPE_DEFAULT_TIMEZONE, DOCUMENT, DatePipe, DecimalPipe, FormStyle, FormatWidth, HashLocationStrategy, I18nPluralPipe, I18nSelectPipe, IMAGE_LOADER, JsonPipe, KeyValuePipe, LOCATION_INITIALIZED, Location, LocationStrategy, LowerCasePipe, NgClass, NgComponentOutlet, NgForOf as NgFor, NgForOf, NgForOfContext, NgIf, NgIfContext, NgLocaleLocalization, NgLocalization, NgOptimizedImage, NgPlural, NgPluralCase, NgStyle, NgSwitch, NgSwitchCase, NgSwitchDefault, NgTemplateOutlet, NumberFormatStyle, NumberSymbol, PRECONNECT_CHECK_BLOCKLIST, PathLocationStrategy, PercentPipe, PlatformLocation, Plural, SlicePipe, TitleCasePipe, TranslationWidth, UpperCasePipe, VERSION, ViewportScroller, WeekDay, XhrFactory, formatCurrency, formatDate, formatNumber, formatPercent, getCurrencySymbol, getLocaleCurrencyCode, getLocaleCurrencyName, getLocaleCurrencySymbol, getLocaleDateFormat, getLocaleDateTimeFormat, getLocaleDayNames, getLocaleDayPeriods, getLocaleDirection, getLocaleEraNames, getLocaleExtraDayPeriodRules, getLocaleExtraDayPeriods, getLocaleFirstDayOfWeek, getLocaleId, getLocaleMonthNames, getLocaleNumberFormat, getLocaleNumberSymbol, getLocalePluralCase, getLocaleTimeFormat, getLocaleWeekEndRange, getNumberOfCurrencyDigits, isPlatformBrowser, isPlatformServer, isPlatformWorkerApp, isPlatformWorkerUi, provideCloudflareLoader, provideCloudinaryLoader, provideImageKitLoader, provideImgixLoader, provideNetlifyLoader, registerLocaleData, DomAdapter as ɵDomAdapter, NullViewportScroller as ɵNullViewportScroller, PLATFORM_BROWSER_ID as ɵPLATFORM_BROWSER_ID, PLATFORM_SERVER_ID as ɵPLATFORM_SERVER_ID, PLATFORM_WORKER_APP_ID as ɵPLATFORM_WORKER_APP_ID, PLATFORM_WORKER_UI_ID as ɵPLATFORM_WORKER_UI_ID, PlatformNavigation as ɵPlatformNavigation, getDOM as ɵgetDOM, normalizeQueryParams as ɵnormalizeQueryParams, parseCookieValue as ɵparseCookieValue, setRootDomAdapter as ɵsetRootDomAdapter };\n","/**\n * @license Angular v17.3.10\n * (c) 2010-2024 Google LLC. https://angular.io/\n * License: MIT\n */\n\nimport * as i0 from '@angular/core';\nimport { Injectable, inject, NgZone, runInInjectionContext, InjectionToken, ɵPendingTasks, PLATFORM_ID, ɵConsole, ɵformatRuntimeError, Inject, ɵRuntimeError, makeEnvironmentProviders, NgModule, TransferState, makeStateKey, ɵperformanceMarkFeature, APP_BOOTSTRAP_LISTENER, ApplicationRef, ɵwhenStable, ɵtruncateMiddle } from '@angular/core';\nimport { of, Observable, from } from 'rxjs';\nimport { concatMap, filter, map, finalize, switchMap, tap } from 'rxjs/operators';\nimport * as i1 from '@angular/common';\nimport { isPlatformServer, DOCUMENT, ɵparseCookieValue } from '@angular/common';\n\n/**\n * Transforms an `HttpRequest` into a stream of `HttpEvent`s, one of which will likely be a\n * `HttpResponse`.\n *\n * `HttpHandler` is injectable. When injected, the handler instance dispatches requests to the\n * first interceptor in the chain, which dispatches to the second, etc, eventually reaching the\n * `HttpBackend`.\n *\n * In an `HttpInterceptor`, the `HttpHandler` parameter is the next interceptor in the chain.\n *\n * @publicApi\n */\nclass HttpHandler {\n}\n/**\n * A final `HttpHandler` which will dispatch the request via browser HTTP APIs to a backend.\n *\n * Interceptors sit between the `HttpClient` interface and the `HttpBackend`.\n *\n * When injected, `HttpBackend` dispatches requests directly to the backend, without going\n * through the interceptor chain.\n *\n * @publicApi\n */\nclass HttpBackend {\n}\n\n/**\n * Represents the header configuration options for an HTTP request.\n * Instances are immutable. Modifying methods return a cloned\n * instance with the change. The original object is never changed.\n *\n * @publicApi\n */\nclass HttpHeaders {\n /** Constructs a new HTTP header object with the given values.*/\n constructor(headers) {\n /**\n * Internal map of lowercased header names to the normalized\n * form of the name (the form seen first).\n */\n this.normalizedNames = new Map();\n /**\n * Queued updates to be materialized the next initialization.\n */\n this.lazyUpdate = null;\n if (!headers) {\n this.headers = new Map();\n }\n else if (typeof headers === 'string') {\n this.lazyInit = () => {\n this.headers = new Map();\n headers.split('\\n').forEach((line) => {\n const index = line.indexOf(':');\n if (index > 0) {\n const name = line.slice(0, index);\n const key = name.toLowerCase();\n const value = line.slice(index + 1).trim();\n this.maybeSetNormalizedName(name, key);\n if (this.headers.has(key)) {\n this.headers.get(key).push(value);\n }\n else {\n this.headers.set(key, [value]);\n }\n }\n });\n };\n }\n else if (typeof Headers !== 'undefined' && headers instanceof Headers) {\n this.headers = new Map();\n headers.forEach((values, name) => {\n this.setHeaderEntries(name, values);\n });\n }\n else {\n this.lazyInit = () => {\n if (typeof ngDevMode === 'undefined' || ngDevMode) {\n assertValidHeaders(headers);\n }\n this.headers = new Map();\n Object.entries(headers).forEach(([name, values]) => {\n this.setHeaderEntries(name, values);\n });\n };\n }\n }\n /**\n * Checks for existence of a given header.\n *\n * @param name The header name to check for existence.\n *\n * @returns True if the header exists, false otherwise.\n */\n has(name) {\n this.init();\n return this.headers.has(name.toLowerCase());\n }\n /**\n * Retrieves the first value of a given header.\n *\n * @param name The header name.\n *\n * @returns The value string if the header exists, null otherwise\n */\n get(name) {\n this.init();\n const values = this.headers.get(name.toLowerCase());\n return values && values.length > 0 ? values[0] : null;\n }\n /**\n * Retrieves the names of the headers.\n *\n * @returns A list of header names.\n */\n keys() {\n this.init();\n return Array.from(this.normalizedNames.values());\n }\n /**\n * Retrieves a list of values for a given header.\n *\n * @param name The header name from which to retrieve values.\n *\n * @returns A string of values if the header exists, null otherwise.\n */\n getAll(name) {\n this.init();\n return this.headers.get(name.toLowerCase()) || null;\n }\n /**\n * Appends a new value to the existing set of values for a header\n * and returns them in a clone of the original instance.\n *\n * @param name The header name for which to append the values.\n * @param value The value to append.\n *\n * @returns A clone of the HTTP headers object with the value appended to the given header.\n */\n append(name, value) {\n return this.clone({ name, value, op: 'a' });\n }\n /**\n * Sets or modifies a value for a given header in a clone of the original instance.\n * If the header already exists, its value is replaced with the given value\n * in the returned object.\n *\n * @param name The header name.\n * @param value The value or values to set or override for the given header.\n *\n * @returns A clone of the HTTP headers object with the newly set header value.\n */\n set(name, value) {\n return this.clone({ name, value, op: 's' });\n }\n /**\n * Deletes values for a given header in a clone of the original instance.\n *\n * @param name The header name.\n * @param value The value or values to delete for the given header.\n *\n * @returns A clone of the HTTP headers object with the given value deleted.\n */\n delete(name, value) {\n return this.clone({ name, value, op: 'd' });\n }\n maybeSetNormalizedName(name, lcName) {\n if (!this.normalizedNames.has(lcName)) {\n this.normalizedNames.set(lcName, name);\n }\n }\n init() {\n if (!!this.lazyInit) {\n if (this.lazyInit instanceof HttpHeaders) {\n this.copyFrom(this.lazyInit);\n }\n else {\n this.lazyInit();\n }\n this.lazyInit = null;\n if (!!this.lazyUpdate) {\n this.lazyUpdate.forEach((update) => this.applyUpdate(update));\n this.lazyUpdate = null;\n }\n }\n }\n copyFrom(other) {\n other.init();\n Array.from(other.headers.keys()).forEach((key) => {\n this.headers.set(key, other.headers.get(key));\n this.normalizedNames.set(key, other.normalizedNames.get(key));\n });\n }\n clone(update) {\n const clone = new HttpHeaders();\n clone.lazyInit = !!this.lazyInit && this.lazyInit instanceof HttpHeaders ? this.lazyInit : this;\n clone.lazyUpdate = (this.lazyUpdate || []).concat([update]);\n return clone;\n }\n applyUpdate(update) {\n const key = update.name.toLowerCase();\n switch (update.op) {\n case 'a':\n case 's':\n let value = update.value;\n if (typeof value === 'string') {\n value = [value];\n }\n if (value.length === 0) {\n return;\n }\n this.maybeSetNormalizedName(update.name, key);\n const base = (update.op === 'a' ? this.headers.get(key) : undefined) || [];\n base.push(...value);\n this.headers.set(key, base);\n break;\n case 'd':\n const toDelete = update.value;\n if (!toDelete) {\n this.headers.delete(key);\n this.normalizedNames.delete(key);\n }\n else {\n let existing = this.headers.get(key);\n if (!existing) {\n return;\n }\n existing = existing.filter((value) => toDelete.indexOf(value) === -1);\n if (existing.length === 0) {\n this.headers.delete(key);\n this.normalizedNames.delete(key);\n }\n else {\n this.headers.set(key, existing);\n }\n }\n break;\n }\n }\n setHeaderEntries(name, values) {\n const headerValues = (Array.isArray(values) ? values : [values]).map((value) => value.toString());\n const key = name.toLowerCase();\n this.headers.set(key, headerValues);\n this.maybeSetNormalizedName(name, key);\n }\n /**\n * @internal\n */\n forEach(fn) {\n this.init();\n Array.from(this.normalizedNames.keys()).forEach((key) => fn(this.normalizedNames.get(key), this.headers.get(key)));\n }\n}\n/**\n * Verifies that the headers object has the right shape: the values\n * must be either strings, numbers or arrays. Throws an error if an invalid\n * header value is present.\n */\nfunction assertValidHeaders(headers) {\n for (const [key, value] of Object.entries(headers)) {\n if (!(typeof value === 'string' || typeof value === 'number') && !Array.isArray(value)) {\n throw new Error(`Unexpected value of the \\`${key}\\` header provided. ` +\n `Expecting either a string, a number or an array, but got: \\`${value}\\`.`);\n }\n }\n}\n\n/**\n * Provides encoding and decoding of URL parameter and query-string values.\n *\n * Serializes and parses URL parameter keys and values to encode and decode them.\n * If you pass URL query parameters without encoding,\n * the query parameters can be misinterpreted at the receiving end.\n *\n *\n * @publicApi\n */\nclass HttpUrlEncodingCodec {\n /**\n * Encodes a key name for a URL parameter or query-string.\n * @param key The key name.\n * @returns The encoded key name.\n */\n encodeKey(key) {\n return standardEncoding(key);\n }\n /**\n * Encodes the value of a URL parameter or query-string.\n * @param value The value.\n * @returns The encoded value.\n */\n encodeValue(value) {\n return standardEncoding(value);\n }\n /**\n * Decodes an encoded URL parameter or query-string key.\n * @param key The encoded key name.\n * @returns The decoded key name.\n */\n decodeKey(key) {\n return decodeURIComponent(key);\n }\n /**\n * Decodes an encoded URL parameter or query-string value.\n * @param value The encoded value.\n * @returns The decoded value.\n */\n decodeValue(value) {\n return decodeURIComponent(value);\n }\n}\nfunction paramParser(rawParams, codec) {\n const map = new Map();\n if (rawParams.length > 0) {\n // The `window.location.search` can be used while creating an instance of the `HttpParams` class\n // (e.g. `new HttpParams({ fromString: window.location.search })`). The `window.location.search`\n // may start with the `?` char, so we strip it if it's present.\n const params = rawParams.replace(/^\\?/, '').split('&');\n params.forEach((param) => {\n const eqIdx = param.indexOf('=');\n const [key, val] = eqIdx == -1\n ? [codec.decodeKey(param), '']\n : [codec.decodeKey(param.slice(0, eqIdx)), codec.decodeValue(param.slice(eqIdx + 1))];\n const list = map.get(key) || [];\n list.push(val);\n map.set(key, list);\n });\n }\n return map;\n}\n/**\n * Encode input string with standard encodeURIComponent and then un-encode specific characters.\n */\nconst STANDARD_ENCODING_REGEX = /%(\\d[a-f0-9])/gi;\nconst STANDARD_ENCODING_REPLACEMENTS = {\n '40': '@',\n '3A': ':',\n '24': '$',\n '2C': ',',\n '3B': ';',\n '3D': '=',\n '3F': '?',\n '2F': '/',\n};\nfunction standardEncoding(v) {\n return encodeURIComponent(v).replace(STANDARD_ENCODING_REGEX, (s, t) => STANDARD_ENCODING_REPLACEMENTS[t] ?? s);\n}\nfunction valueToString(value) {\n return `${value}`;\n}\n/**\n * An HTTP request/response body that represents serialized parameters,\n * per the MIME type `application/x-www-form-urlencoded`.\n *\n * This class is immutable; all mutation operations return a new instance.\n *\n * @publicApi\n */\nclass HttpParams {\n constructor(options = {}) {\n this.updates = null;\n this.cloneFrom = null;\n this.encoder = options.encoder || new HttpUrlEncodingCodec();\n if (!!options.fromString) {\n if (!!options.fromObject) {\n throw new Error(`Cannot specify both fromString and fromObject.`);\n }\n this.map = paramParser(options.fromString, this.encoder);\n }\n else if (!!options.fromObject) {\n this.map = new Map();\n Object.keys(options.fromObject).forEach((key) => {\n const value = options.fromObject[key];\n // convert the values to strings\n const values = Array.isArray(value) ? value.map(valueToString) : [valueToString(value)];\n this.map.set(key, values);\n });\n }\n else {\n this.map = null;\n }\n }\n /**\n * Reports whether the body includes one or more values for a given parameter.\n * @param param The parameter name.\n * @returns True if the parameter has one or more values,\n * false if it has no value or is not present.\n */\n has(param) {\n this.init();\n return this.map.has(param);\n }\n /**\n * Retrieves the first value for a parameter.\n * @param param The parameter name.\n * @returns The first value of the given parameter,\n * or `null` if the parameter is not present.\n */\n get(param) {\n this.init();\n const res = this.map.get(param);\n return !!res ? res[0] : null;\n }\n /**\n * Retrieves all values for a parameter.\n * @param param The parameter name.\n * @returns All values in a string array,\n * or `null` if the parameter not present.\n */\n getAll(param) {\n this.init();\n return this.map.get(param) || null;\n }\n /**\n * Retrieves all the parameters for this body.\n * @returns The parameter names in a string array.\n */\n keys() {\n this.init();\n return Array.from(this.map.keys());\n }\n /**\n * Appends a new value to existing values for a parameter.\n * @param param The parameter name.\n * @param value The new value to add.\n * @return A new body with the appended value.\n */\n append(param, value) {\n return this.clone({ param, value, op: 'a' });\n }\n /**\n * Constructs a new body with appended values for the given parameter name.\n * @param params parameters and values\n * @return A new body with the new value.\n */\n appendAll(params) {\n const updates = [];\n Object.keys(params).forEach((param) => {\n const value = params[param];\n if (Array.isArray(value)) {\n value.forEach((_value) => {\n updates.push({ param, value: _value, op: 'a' });\n });\n }\n else {\n updates.push({ param, value: value, op: 'a' });\n }\n });\n return this.clone(updates);\n }\n /**\n * Replaces the value for a parameter.\n * @param param The parameter name.\n * @param value The new value.\n * @return A new body with the new value.\n */\n set(param, value) {\n return this.clone({ param, value, op: 's' });\n }\n /**\n * Removes a given value or all values from a parameter.\n * @param param The parameter name.\n * @param value The value to remove, if provided.\n * @return A new body with the given value removed, or with all values\n * removed if no value is specified.\n */\n delete(param, value) {\n return this.clone({ param, value, op: 'd' });\n }\n /**\n * Serializes the body to an encoded string, where key-value pairs (separated by `=`) are\n * separated by `&`s.\n */\n toString() {\n this.init();\n return (this.keys()\n .map((key) => {\n const eKey = this.encoder.encodeKey(key);\n // `a: ['1']` produces `'a=1'`\n // `b: []` produces `''`\n // `c: ['1', '2']` produces `'c=1&c=2'`\n return this.map.get(key)\n .map((value) => eKey + '=' + this.encoder.encodeValue(value))\n .join('&');\n })\n // filter out empty values because `b: []` produces `''`\n // which results in `a=1&&c=1&c=2` instead of `a=1&c=1&c=2` if we don't\n .filter((param) => param !== '')\n .join('&'));\n }\n clone(update) {\n const clone = new HttpParams({ encoder: this.encoder });\n clone.cloneFrom = this.cloneFrom || this;\n clone.updates = (this.updates || []).concat(update);\n return clone;\n }\n init() {\n if (this.map === null) {\n this.map = new Map();\n }\n if (this.cloneFrom !== null) {\n this.cloneFrom.init();\n this.cloneFrom.keys().forEach((key) => this.map.set(key, this.cloneFrom.map.get(key)));\n this.updates.forEach((update) => {\n switch (update.op) {\n case 'a':\n case 's':\n const base = (update.op === 'a' ? this.map.get(update.param) : undefined) || [];\n base.push(valueToString(update.value));\n this.map.set(update.param, base);\n break;\n case 'd':\n if (update.value !== undefined) {\n let base = this.map.get(update.param) || [];\n const idx = base.indexOf(valueToString(update.value));\n if (idx !== -1) {\n base.splice(idx, 1);\n }\n if (base.length > 0) {\n this.map.set(update.param, base);\n }\n else {\n this.map.delete(update.param);\n }\n }\n else {\n this.map.delete(update.param);\n break;\n }\n }\n });\n this.cloneFrom = this.updates = null;\n }\n }\n}\n\n/**\n * A token used to manipulate and access values stored in `HttpContext`.\n *\n * @publicApi\n */\nclass HttpContextToken {\n constructor(defaultValue) {\n this.defaultValue = defaultValue;\n }\n}\n/**\n * Http context stores arbitrary user defined values and ensures type safety without\n * actually knowing the types. It is backed by a `Map` and guarantees that keys do not clash.\n *\n * This context is mutable and is shared between cloned requests unless explicitly specified.\n *\n * @usageNotes\n *\n * ### Usage Example\n *\n * ```typescript\n * // inside cache.interceptors.ts\n * export const IS_CACHE_ENABLED = new HttpContextToken