qrcode.vue 3.4.1 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1099 +1,1178 @@
1
1
  /*!
2
- * qrcode.vue v3.4.1
3
- * A Vue.js component to generate QRCode.
4
- * © 2017-2023 @scopewu(https://github.com/scopewu)
2
+ * qrcode.vue v3.5.0
3
+ * A Vue.js component to generate QRCode. Both support Vue 2 and Vue 3
4
+ * © 2017-PRESENT @scopewu(https://github.com/scopewu)
5
5
  * MIT License.
6
6
  */
7
7
  (function (global, factory) {
8
- typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('vue')) :
9
- typeof define === 'function' && define.amd ? define(['vue'], factory) :
10
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.QrcodeVue = factory(global.Vue));
11
- })(this, (function (vue) { 'use strict';
8
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vue')) :
9
+ typeof define === 'function' && define.amd ? define(['exports', 'vue'], factory) :
10
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.QrcodeVue = {}, global.Vue));
11
+ })(this, (function (exports, vue) { 'use strict';
12
12
 
13
- /******************************************************************************
14
- Copyright (c) Microsoft Corporation.
13
+ /******************************************************************************
14
+ Copyright (c) Microsoft Corporation.
15
15
 
16
- Permission to use, copy, modify, and/or distribute this software for any
17
- purpose with or without fee is hereby granted.
16
+ Permission to use, copy, modify, and/or distribute this software for any
17
+ purpose with or without fee is hereby granted.
18
18
 
19
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
- PERFORMANCE OF THIS SOFTWARE.
26
- ***************************************************************************** */
27
- /* global Reflect, Promise, SuppressedError, Symbol */
19
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
+ PERFORMANCE OF THIS SOFTWARE.
26
+ ***************************************************************************** */
27
+ /* global Reflect, Promise, SuppressedError, Symbol */
28
28
 
29
29
 
30
- var __assign = function() {
31
- __assign = Object.assign || function __assign(t) {
32
- for (var s, i = 1, n = arguments.length; i < n; i++) {
33
- s = arguments[i];
34
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
35
- }
36
- return t;
37
- };
38
- return __assign.apply(this, arguments);
30
+ var __assign = function() {
31
+ __assign = Object.assign || function __assign(t) {
32
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
33
+ s = arguments[i];
34
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
35
+ }
36
+ return t;
39
37
  };
38
+ return __assign.apply(this, arguments);
39
+ };
40
40
 
41
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
42
- var e = new Error(message);
43
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
44
- };
41
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
42
+ var e = new Error(message);
43
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
44
+ };
45
45
 
46
+ /*
47
+ * QR Code generator library (TypeScript)
48
+ *
49
+ * Copyright (c) Project Nayuki. (MIT License)
50
+ * https://www.nayuki.io/page/qr-code-generator-library
51
+ *
52
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
53
+ * this software and associated documentation files (the "Software"), to deal in
54
+ * the Software without restriction, including without limitation the rights to
55
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
56
+ * the Software, and to permit persons to whom the Software is furnished to do so,
57
+ * subject to the following conditions:
58
+ * - The above copyright notice and this permission notice shall be included in
59
+ * all copies or substantial portions of the Software.
60
+ * - The Software is provided "as is", without warranty of any kind, express or
61
+ * implied, including but not limited to the warranties of merchantability,
62
+ * fitness for a particular purpose and noninfringement. In no event shall the
63
+ * authors or copyright holders be liable for any claim, damages or other
64
+ * liability, whether in an action of contract, tort or otherwise, arising from,
65
+ * out of or in connection with the Software or the use or other dealings in the
66
+ * Software.
67
+ */
68
+ var qrcodegen;
69
+ (function (qrcodegen) {
70
+ /*---- QR Code symbol class ----*/
46
71
  /*
47
- * QR Code generator library (TypeScript)
48
- *
49
- * Copyright (c) Project Nayuki. (MIT License)
50
- * https://www.nayuki.io/page/qr-code-generator-library
72
+ * A QR Code symbol, which is a type of two-dimension barcode.
73
+ * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
74
+ * Instances of this class represent an immutable square grid of dark and light cells.
75
+ * The class provides static factory functions to create a QR Code from text or binary data.
76
+ * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
77
+ * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
51
78
  *
52
- * Permission is hereby granted, free of charge, to any person obtaining a copy of
53
- * this software and associated documentation files (the "Software"), to deal in
54
- * the Software without restriction, including without limitation the rights to
55
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
56
- * the Software, and to permit persons to whom the Software is furnished to do so,
57
- * subject to the following conditions:
58
- * - The above copyright notice and this permission notice shall be included in
59
- * all copies or substantial portions of the Software.
60
- * - The Software is provided "as is", without warranty of any kind, express or
61
- * implied, including but not limited to the warranties of merchantability,
62
- * fitness for a particular purpose and noninfringement. In no event shall the
63
- * authors or copyright holders be liable for any claim, damages or other
64
- * liability, whether in an action of contract, tort or otherwise, arising from,
65
- * out of or in connection with the Software or the use or other dealings in the
66
- * Software.
79
+ * Ways to create a QR Code object:
80
+ * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
81
+ * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
82
+ * - Low level: Custom-make the array of data codeword bytes (including
83
+ * segment headers and final padding, excluding error correction codewords),
84
+ * supply the appropriate version number, and call the QrCode() constructor.
85
+ * (Note that all ways require supplying the desired error correction level.)
67
86
  */
68
- var qrcodegen;
69
- (function (qrcodegen) {
70
- /*---- QR Code symbol class ----*/
71
- /*
72
- * A QR Code symbol, which is a type of two-dimension barcode.
73
- * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
74
- * Instances of this class represent an immutable square grid of dark and light cells.
75
- * The class provides static factory functions to create a QR Code from text or binary data.
76
- * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
77
- * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
78
- *
79
- * Ways to create a QR Code object:
80
- * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
81
- * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
82
- * - Low level: Custom-make the array of data codeword bytes (including
83
- * segment headers and final padding, excluding error correction codewords),
84
- * supply the appropriate version number, and call the QrCode() constructor.
85
- * (Note that all ways require supplying the desired error correction level.)
86
- */
87
- var QrCode = /** @class */ (function () {
88
- /*-- Constructor (low level) and fields --*/
89
- // Creates a new QR Code with the given version number,
90
- // error correction level, data codeword bytes, and mask number.
91
- // This is a low-level API that most users should not use directly.
92
- // A mid-level API is the encodeSegments() function.
93
- function QrCode(
94
- // The version number of this QR Code, which is between 1 and 40 (inclusive).
95
- // This determines the size of this barcode.
96
- version,
97
- // The error correction level used in this QR Code.
98
- errorCorrectionLevel, dataCodewords, msk) {
99
- this.version = version;
100
- this.errorCorrectionLevel = errorCorrectionLevel;
101
- // The modules of this QR Code (false = light, true = dark).
102
- // Immutable after constructor finishes. Accessed through getModule().
103
- this.modules = [];
104
- // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
105
- this.isFunction = [];
106
- // Check scalar arguments
107
- if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
108
- throw new RangeError("Version value out of range");
109
- if (msk < -1 || msk > 7)
110
- throw new RangeError("Mask value out of range");
111
- this.size = version * 4 + 17;
112
- // Initialize both grids to be size*size arrays of Boolean false
113
- var row = [];
114
- for (var i = 0; i < this.size; i++)
115
- row.push(false);
116
- for (var i = 0; i < this.size; i++) {
117
- this.modules.push(row.slice()); // Initially all light
118
- this.isFunction.push(row.slice());
119
- }
120
- // Compute ECC, draw modules
121
- this.drawFunctionPatterns();
122
- var allCodewords = this.addEccAndInterleave(dataCodewords);
123
- this.drawCodewords(allCodewords);
124
- // Do masking
125
- if (msk == -1) { // Automatically choose best mask
126
- var minPenalty = 1000000000;
127
- for (var i = 0; i < 8; i++) {
128
- this.applyMask(i);
129
- this.drawFormatBits(i);
130
- var penalty = this.getPenaltyScore();
131
- if (penalty < minPenalty) {
132
- msk = i;
133
- minPenalty = penalty;
134
- }
135
- this.applyMask(i); // Undoes the mask due to XOR
136
- }
137
- }
138
- assert(0 <= msk && msk <= 7);
139
- this.mask = msk;
140
- this.applyMask(msk); // Apply the final choice of mask
141
- this.drawFormatBits(msk); // Overwrite old format bits
142
- this.isFunction = [];
87
+ var QrCode = /** @class */ (function () {
88
+ /*-- Constructor (low level) and fields --*/
89
+ // Creates a new QR Code with the given version number,
90
+ // error correction level, data codeword bytes, and mask number.
91
+ // This is a low-level API that most users should not use directly.
92
+ // A mid-level API is the encodeSegments() function.
93
+ function QrCode(
94
+ // The version number of this QR Code, which is between 1 and 40 (inclusive).
95
+ // This determines the size of this barcode.
96
+ version,
97
+ // The error correction level used in this QR Code.
98
+ errorCorrectionLevel, dataCodewords, msk) {
99
+ this.version = version;
100
+ this.errorCorrectionLevel = errorCorrectionLevel;
101
+ // The modules of this QR Code (false = light, true = dark).
102
+ // Immutable after constructor finishes. Accessed through getModule().
103
+ this.modules = [];
104
+ // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
105
+ this.isFunction = [];
106
+ // Check scalar arguments
107
+ if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
108
+ throw new RangeError("Version value out of range");
109
+ if (msk < -1 || msk > 7)
110
+ throw new RangeError("Mask value out of range");
111
+ this.size = version * 4 + 17;
112
+ // Initialize both grids to be size*size arrays of Boolean false
113
+ var row = [];
114
+ for (var i = 0; i < this.size; i++)
115
+ row.push(false);
116
+ for (var i = 0; i < this.size; i++) {
117
+ this.modules.push(row.slice()); // Initially all light
118
+ this.isFunction.push(row.slice());
143
119
  }
144
- /*-- Static factory functions (high level) --*/
145
- // Returns a QR Code representing the given Unicode text string at the given error correction level.
146
- // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
147
- // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
148
- // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
149
- // ecl argument if it can be done without increasing the version.
150
- QrCode.encodeText = function (text, ecl) {
151
- var segs = qrcodegen.QrSegment.makeSegments(text);
152
- return QrCode.encodeSegments(segs, ecl);
153
- };
154
- // Returns a QR Code representing the given binary data at the given error correction level.
155
- // This function always encodes using the binary segment mode, not any text mode. The maximum number of
156
- // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
157
- // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
158
- QrCode.encodeBinary = function (data, ecl) {
159
- var seg = qrcodegen.QrSegment.makeBytes(data);
160
- return QrCode.encodeSegments([seg], ecl);
161
- };
162
- /*-- Static factory functions (mid level) --*/
163
- // Returns a QR Code representing the given segments with the given encoding parameters.
164
- // The smallest possible QR Code version within the given range is automatically
165
- // chosen for the output. Iff boostEcl is true, then the ECC level of the result
166
- // may be higher than the ecl argument if it can be done without increasing the
167
- // version. The mask number is either between 0 to 7 (inclusive) to force that
168
- // mask, or -1 to automatically choose an appropriate mask (which may be slow).
169
- // This function allows the user to create a custom sequence of segments that switches
170
- // between modes (such as alphanumeric and byte) to encode text in less space.
171
- // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
172
- QrCode.encodeSegments = function (segs, ecl, minVersion, maxVersion, mask, boostEcl) {
173
- if (minVersion === void 0) { minVersion = 1; }
174
- if (maxVersion === void 0) { maxVersion = 40; }
175
- if (mask === void 0) { mask = -1; }
176
- if (boostEcl === void 0) { boostEcl = true; }
177
- if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
178
- || mask < -1 || mask > 7)
179
- throw new RangeError("Invalid value");
180
- // Find the minimal version number to use
181
- var version;
182
- var dataUsedBits;
183
- for (version = minVersion;; version++) {
184
- var dataCapacityBits_1 = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
185
- var usedBits = QrSegment.getTotalBits(segs, version);
186
- if (usedBits <= dataCapacityBits_1) {
187
- dataUsedBits = usedBits;
188
- break; // This version number is found to be suitable
120
+ // Compute ECC, draw modules
121
+ this.drawFunctionPatterns();
122
+ var allCodewords = this.addEccAndInterleave(dataCodewords);
123
+ this.drawCodewords(allCodewords);
124
+ // Do masking
125
+ if (msk == -1) { // Automatically choose best mask
126
+ var minPenalty = 1000000000;
127
+ for (var i = 0; i < 8; i++) {
128
+ this.applyMask(i);
129
+ this.drawFormatBits(i);
130
+ var penalty = this.getPenaltyScore();
131
+ if (penalty < minPenalty) {
132
+ msk = i;
133
+ minPenalty = penalty;
189
134
  }
190
- if (version >= maxVersion) // All versions in the range could not fit the given data
191
- throw new RangeError("Data too long");
192
- }
193
- // Increase the error correction level while the data still fits in the current version number
194
- for (var _i = 0, _a = [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]; _i < _a.length; _i++) { // From low to high
195
- var newEcl = _a[_i];
196
- if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
197
- ecl = newEcl;
135
+ this.applyMask(i); // Undoes the mask due to XOR
198
136
  }
199
- // Concatenate all segments to create the data bit string
200
- var bb = [];
201
- for (var _b = 0, segs_1 = segs; _b < segs_1.length; _b++) {
202
- var seg = segs_1[_b];
203
- appendBits(seg.mode.modeBits, 4, bb);
204
- appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
205
- for (var _c = 0, _d = seg.getData(); _c < _d.length; _c++) {
206
- var b = _d[_c];
207
- bb.push(b);
208
- }
209
- }
210
- assert(bb.length == dataUsedBits);
211
- // Add terminator and pad up to a byte if applicable
212
- var dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
213
- assert(bb.length <= dataCapacityBits);
214
- appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
215
- appendBits(0, (8 - bb.length % 8) % 8, bb);
216
- assert(bb.length % 8 == 0);
217
- // Pad with alternating bytes until data capacity is reached
218
- for (var padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
219
- appendBits(padByte, 8, bb);
220
- // Pack bits into bytes in big endian
221
- var dataCodewords = [];
222
- while (dataCodewords.length * 8 < bb.length)
223
- dataCodewords.push(0);
224
- bb.forEach(function (b, i) {
225
- return dataCodewords[i >>> 3] |= b << (7 - (i & 7));
226
- });
227
- // Create the QR Code object
228
- return new QrCode(version, ecl, dataCodewords, mask);
229
- };
230
- /*-- Accessor methods --*/
231
- // Returns the color of the module (pixel) at the given coordinates, which is false
232
- // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
233
- // If the given coordinates are out of bounds, then false (light) is returned.
234
- QrCode.prototype.getModule = function (x, y) {
235
- return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
236
- };
237
- QrCode.prototype.getModules = function () {
238
- return this.modules;
239
- };
240
- /*-- Private helper methods for constructor: Drawing function modules --*/
241
- // Reads this object's version field, and draws and marks all function modules.
242
- QrCode.prototype.drawFunctionPatterns = function () {
243
- // Draw horizontal and vertical timing patterns
244
- for (var i = 0; i < this.size; i++) {
245
- this.setFunctionModule(6, i, i % 2 == 0);
246
- this.setFunctionModule(i, 6, i % 2 == 0);
247
- }
248
- // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
249
- this.drawFinderPattern(3, 3);
250
- this.drawFinderPattern(this.size - 4, 3);
251
- this.drawFinderPattern(3, this.size - 4);
252
- // Draw numerous alignment patterns
253
- var alignPatPos = this.getAlignmentPatternPositions();
254
- var numAlign = alignPatPos.length;
255
- for (var i = 0; i < numAlign; i++) {
256
- for (var j = 0; j < numAlign; j++) {
257
- // Don't draw on the three finder corners
258
- if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
259
- this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
260
- }
261
- }
262
- // Draw configuration data
263
- this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
264
- this.drawVersion();
265
- };
266
- // Draws two copies of the format bits (with its own error correction code)
267
- // based on the given mask and this object's error correction level field.
268
- QrCode.prototype.drawFormatBits = function (mask) {
269
- // Calculate error correction code and pack bits
270
- var data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
271
- var rem = data;
272
- for (var i = 0; i < 10; i++)
273
- rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
274
- var bits = (data << 10 | rem) ^ 0x5412; // uint15
275
- assert(bits >>> 15 == 0);
276
- // Draw first copy
277
- for (var i = 0; i <= 5; i++)
278
- this.setFunctionModule(8, i, getBit(bits, i));
279
- this.setFunctionModule(8, 7, getBit(bits, 6));
280
- this.setFunctionModule(8, 8, getBit(bits, 7));
281
- this.setFunctionModule(7, 8, getBit(bits, 8));
282
- for (var i = 9; i < 15; i++)
283
- this.setFunctionModule(14 - i, 8, getBit(bits, i));
284
- // Draw second copy
285
- for (var i = 0; i < 8; i++)
286
- this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
287
- for (var i = 8; i < 15; i++)
288
- this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
289
- this.setFunctionModule(8, this.size - 8, true); // Always dark
290
- };
291
- // Draws two copies of the version bits (with its own error correction code),
292
- // based on this object's version field, iff 7 <= version <= 40.
293
- QrCode.prototype.drawVersion = function () {
294
- if (this.version < 7)
295
- return;
296
- // Calculate error correction code and pack bits
297
- var rem = this.version; // version is uint6, in the range [7, 40]
298
- for (var i = 0; i < 12; i++)
299
- rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
300
- var bits = this.version << 12 | rem; // uint18
301
- assert(bits >>> 18 == 0);
302
- // Draw two copies
303
- for (var i = 0; i < 18; i++) {
304
- var color = getBit(bits, i);
305
- var a = this.size - 11 + i % 3;
306
- var b = Math.floor(i / 3);
307
- this.setFunctionModule(a, b, color);
308
- this.setFunctionModule(b, a, color);
309
- }
310
- };
311
- // Draws a 9*9 finder pattern including the border separator,
312
- // with the center module at (x, y). Modules can be out of bounds.
313
- QrCode.prototype.drawFinderPattern = function (x, y) {
314
- for (var dy = -4; dy <= 4; dy++) {
315
- for (var dx = -4; dx <= 4; dx++) {
316
- var dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
317
- var xx = x + dx;
318
- var yy = y + dy;
319
- if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
320
- this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
321
- }
322
- }
323
- };
324
- // Draws a 5*5 alignment pattern, with the center module
325
- // at (x, y). All modules must be in bounds.
326
- QrCode.prototype.drawAlignmentPattern = function (x, y) {
327
- for (var dy = -2; dy <= 2; dy++) {
328
- for (var dx = -2; dx <= 2; dx++)
329
- this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
137
+ }
138
+ assert(0 <= msk && msk <= 7);
139
+ this.mask = msk;
140
+ this.applyMask(msk); // Apply the final choice of mask
141
+ this.drawFormatBits(msk); // Overwrite old format bits
142
+ this.isFunction = [];
143
+ }
144
+ /*-- Static factory functions (high level) --*/
145
+ // Returns a QR Code representing the given Unicode text string at the given error correction level.
146
+ // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
147
+ // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
148
+ // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
149
+ // ecl argument if it can be done without increasing the version.
150
+ QrCode.encodeText = function (text, ecl) {
151
+ var segs = qrcodegen.QrSegment.makeSegments(text);
152
+ return QrCode.encodeSegments(segs, ecl);
153
+ };
154
+ // Returns a QR Code representing the given binary data at the given error correction level.
155
+ // This function always encodes using the binary segment mode, not any text mode. The maximum number of
156
+ // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
157
+ // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
158
+ QrCode.encodeBinary = function (data, ecl) {
159
+ var seg = qrcodegen.QrSegment.makeBytes(data);
160
+ return QrCode.encodeSegments([seg], ecl);
161
+ };
162
+ /*-- Static factory functions (mid level) --*/
163
+ // Returns a QR Code representing the given segments with the given encoding parameters.
164
+ // The smallest possible QR Code version within the given range is automatically
165
+ // chosen for the output. Iff boostEcl is true, then the ECC level of the result
166
+ // may be higher than the ecl argument if it can be done without increasing the
167
+ // version. The mask number is either between 0 to 7 (inclusive) to force that
168
+ // mask, or -1 to automatically choose an appropriate mask (which may be slow).
169
+ // This function allows the user to create a custom sequence of segments that switches
170
+ // between modes (such as alphanumeric and byte) to encode text in less space.
171
+ // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
172
+ QrCode.encodeSegments = function (segs, ecl, minVersion, maxVersion, mask, boostEcl) {
173
+ if (minVersion === void 0) { minVersion = 1; }
174
+ if (maxVersion === void 0) { maxVersion = 40; }
175
+ if (mask === void 0) { mask = -1; }
176
+ if (boostEcl === void 0) { boostEcl = true; }
177
+ if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
178
+ || mask < -1 || mask > 7)
179
+ throw new RangeError("Invalid value");
180
+ // Find the minimal version number to use
181
+ var version;
182
+ var dataUsedBits;
183
+ for (version = minVersion;; version++) {
184
+ var dataCapacityBits_1 = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
185
+ var usedBits = QrSegment.getTotalBits(segs, version);
186
+ if (usedBits <= dataCapacityBits_1) {
187
+ dataUsedBits = usedBits;
188
+ break; // This version number is found to be suitable
330
189
  }
331
- };
332
- // Sets the color of a module and marks it as a function module.
333
- // Only used by the constructor. Coordinates must be in bounds.
334
- QrCode.prototype.setFunctionModule = function (x, y, isDark) {
335
- this.modules[y][x] = isDark;
336
- this.isFunction[y][x] = true;
337
- };
338
- /*-- Private helper methods for constructor: Codewords and masking --*/
339
- // Returns a new byte string representing the given data with the appropriate error correction
340
- // codewords appended to it, based on this object's version and error correction level.
341
- QrCode.prototype.addEccAndInterleave = function (data) {
342
- var ver = this.version;
343
- var ecl = this.errorCorrectionLevel;
344
- if (data.length != QrCode.getNumDataCodewords(ver, ecl))
345
- throw new RangeError("Invalid argument");
346
- // Calculate parameter numbers
347
- var numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
348
- var blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
349
- var rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
350
- var numShortBlocks = numBlocks - rawCodewords % numBlocks;
351
- var shortBlockLen = Math.floor(rawCodewords / numBlocks);
352
- // Split data into blocks and append ECC to each block
353
- var blocks = [];
354
- var rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
355
- for (var i = 0, k = 0; i < numBlocks; i++) {
356
- var dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
357
- k += dat.length;
358
- var ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
359
- if (i < numShortBlocks)
360
- dat.push(0);
361
- blocks.push(dat.concat(ecc));
190
+ if (version >= maxVersion) // All versions in the range could not fit the given data
191
+ throw new RangeError("Data too long");
192
+ }
193
+ // Increase the error correction level while the data still fits in the current version number
194
+ for (var _i = 0, _a = [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]; _i < _a.length; _i++) { // From low to high
195
+ var newEcl = _a[_i];
196
+ if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
197
+ ecl = newEcl;
198
+ }
199
+ // Concatenate all segments to create the data bit string
200
+ var bb = [];
201
+ for (var _b = 0, segs_1 = segs; _b < segs_1.length; _b++) {
202
+ var seg = segs_1[_b];
203
+ appendBits(seg.mode.modeBits, 4, bb);
204
+ appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
205
+ for (var _c = 0, _d = seg.getData(); _c < _d.length; _c++) {
206
+ var b = _d[_c];
207
+ bb.push(b);
362
208
  }
363
- // Interleave (not concatenate) the bytes from every block into a single sequence
364
- var result = [];
365
- var _loop_1 = function (i) {
366
- blocks.forEach(function (block, j) {
367
- // Skip the padding byte in short blocks
368
- if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
369
- result.push(block[i]);
370
- });
371
- };
372
- for (var i = 0; i < blocks[0].length; i++) {
373
- _loop_1(i);
209
+ }
210
+ assert(bb.length == dataUsedBits);
211
+ // Add terminator and pad up to a byte if applicable
212
+ var dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
213
+ assert(bb.length <= dataCapacityBits);
214
+ appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
215
+ appendBits(0, (8 - bb.length % 8) % 8, bb);
216
+ assert(bb.length % 8 == 0);
217
+ // Pad with alternating bytes until data capacity is reached
218
+ for (var padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
219
+ appendBits(padByte, 8, bb);
220
+ // Pack bits into bytes in big endian
221
+ var dataCodewords = [];
222
+ while (dataCodewords.length * 8 < bb.length)
223
+ dataCodewords.push(0);
224
+ bb.forEach(function (b, i) {
225
+ return dataCodewords[i >>> 3] |= b << (7 - (i & 7));
226
+ });
227
+ // Create the QR Code object
228
+ return new QrCode(version, ecl, dataCodewords, mask);
229
+ };
230
+ /*-- Accessor methods --*/
231
+ // Returns the color of the module (pixel) at the given coordinates, which is false
232
+ // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
233
+ // If the given coordinates are out of bounds, then false (light) is returned.
234
+ QrCode.prototype.getModule = function (x, y) {
235
+ return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
236
+ };
237
+ QrCode.prototype.getModules = function () {
238
+ return this.modules;
239
+ };
240
+ /*-- Private helper methods for constructor: Drawing function modules --*/
241
+ // Reads this object's version field, and draws and marks all function modules.
242
+ QrCode.prototype.drawFunctionPatterns = function () {
243
+ // Draw horizontal and vertical timing patterns
244
+ for (var i = 0; i < this.size; i++) {
245
+ this.setFunctionModule(6, i, i % 2 == 0);
246
+ this.setFunctionModule(i, 6, i % 2 == 0);
247
+ }
248
+ // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
249
+ this.drawFinderPattern(3, 3);
250
+ this.drawFinderPattern(this.size - 4, 3);
251
+ this.drawFinderPattern(3, this.size - 4);
252
+ // Draw numerous alignment patterns
253
+ var alignPatPos = this.getAlignmentPatternPositions();
254
+ var numAlign = alignPatPos.length;
255
+ for (var i = 0; i < numAlign; i++) {
256
+ for (var j = 0; j < numAlign; j++) {
257
+ // Don't draw on the three finder corners
258
+ if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
259
+ this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
374
260
  }
375
- assert(result.length == rawCodewords);
376
- return result;
377
- };
378
- // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
379
- // data area of this QR Code. Function modules need to be marked off before this is called.
380
- QrCode.prototype.drawCodewords = function (data) {
381
- if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
382
- throw new RangeError("Invalid argument");
383
- var i = 0; // Bit index into the data
384
- // Do the funny zigzag scan
385
- for (var right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
386
- if (right == 6)
387
- right = 5;
388
- for (var vert = 0; vert < this.size; vert++) { // Vertical counter
389
- for (var j = 0; j < 2; j++) {
390
- var x = right - j; // Actual x coordinate
391
- var upward = ((right + 1) & 2) == 0;
392
- var y = upward ? this.size - 1 - vert : vert; // Actual y coordinate
393
- if (!this.isFunction[y][x] && i < data.length * 8) {
394
- this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
395
- i++;
396
- }
397
- // If this QR Code has any remainder bits (0 to 7), they were assigned as
398
- // 0/false/light by the constructor and are left unchanged by this method
399
- }
400
- }
261
+ }
262
+ // Draw configuration data
263
+ this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
264
+ this.drawVersion();
265
+ };
266
+ // Draws two copies of the format bits (with its own error correction code)
267
+ // based on the given mask and this object's error correction level field.
268
+ QrCode.prototype.drawFormatBits = function (mask) {
269
+ // Calculate error correction code and pack bits
270
+ var data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
271
+ var rem = data;
272
+ for (var i = 0; i < 10; i++)
273
+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
274
+ var bits = (data << 10 | rem) ^ 0x5412; // uint15
275
+ assert(bits >>> 15 == 0);
276
+ // Draw first copy
277
+ for (var i = 0; i <= 5; i++)
278
+ this.setFunctionModule(8, i, getBit(bits, i));
279
+ this.setFunctionModule(8, 7, getBit(bits, 6));
280
+ this.setFunctionModule(8, 8, getBit(bits, 7));
281
+ this.setFunctionModule(7, 8, getBit(bits, 8));
282
+ for (var i = 9; i < 15; i++)
283
+ this.setFunctionModule(14 - i, 8, getBit(bits, i));
284
+ // Draw second copy
285
+ for (var i = 0; i < 8; i++)
286
+ this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
287
+ for (var i = 8; i < 15; i++)
288
+ this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
289
+ this.setFunctionModule(8, this.size - 8, true); // Always dark
290
+ };
291
+ // Draws two copies of the version bits (with its own error correction code),
292
+ // based on this object's version field, iff 7 <= version <= 40.
293
+ QrCode.prototype.drawVersion = function () {
294
+ if (this.version < 7)
295
+ return;
296
+ // Calculate error correction code and pack bits
297
+ var rem = this.version; // version is uint6, in the range [7, 40]
298
+ for (var i = 0; i < 12; i++)
299
+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
300
+ var bits = this.version << 12 | rem; // uint18
301
+ assert(bits >>> 18 == 0);
302
+ // Draw two copies
303
+ for (var i = 0; i < 18; i++) {
304
+ var color = getBit(bits, i);
305
+ var a = this.size - 11 + i % 3;
306
+ var b = Math.floor(i / 3);
307
+ this.setFunctionModule(a, b, color);
308
+ this.setFunctionModule(b, a, color);
309
+ }
310
+ };
311
+ // Draws a 9*9 finder pattern including the border separator,
312
+ // with the center module at (x, y). Modules can be out of bounds.
313
+ QrCode.prototype.drawFinderPattern = function (x, y) {
314
+ for (var dy = -4; dy <= 4; dy++) {
315
+ for (var dx = -4; dx <= 4; dx++) {
316
+ var dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
317
+ var xx = x + dx;
318
+ var yy = y + dy;
319
+ if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
320
+ this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
401
321
  }
402
- assert(i == data.length * 8);
322
+ }
323
+ };
324
+ // Draws a 5*5 alignment pattern, with the center module
325
+ // at (x, y). All modules must be in bounds.
326
+ QrCode.prototype.drawAlignmentPattern = function (x, y) {
327
+ for (var dy = -2; dy <= 2; dy++) {
328
+ for (var dx = -2; dx <= 2; dx++)
329
+ this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
330
+ }
331
+ };
332
+ // Sets the color of a module and marks it as a function module.
333
+ // Only used by the constructor. Coordinates must be in bounds.
334
+ QrCode.prototype.setFunctionModule = function (x, y, isDark) {
335
+ this.modules[y][x] = isDark;
336
+ this.isFunction[y][x] = true;
337
+ };
338
+ /*-- Private helper methods for constructor: Codewords and masking --*/
339
+ // Returns a new byte string representing the given data with the appropriate error correction
340
+ // codewords appended to it, based on this object's version and error correction level.
341
+ QrCode.prototype.addEccAndInterleave = function (data) {
342
+ var ver = this.version;
343
+ var ecl = this.errorCorrectionLevel;
344
+ if (data.length != QrCode.getNumDataCodewords(ver, ecl))
345
+ throw new RangeError("Invalid argument");
346
+ // Calculate parameter numbers
347
+ var numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
348
+ var blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
349
+ var rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
350
+ var numShortBlocks = numBlocks - rawCodewords % numBlocks;
351
+ var shortBlockLen = Math.floor(rawCodewords / numBlocks);
352
+ // Split data into blocks and append ECC to each block
353
+ var blocks = [];
354
+ var rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
355
+ for (var i = 0, k = 0; i < numBlocks; i++) {
356
+ var dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
357
+ k += dat.length;
358
+ var ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
359
+ if (i < numShortBlocks)
360
+ dat.push(0);
361
+ blocks.push(dat.concat(ecc));
362
+ }
363
+ // Interleave (not concatenate) the bytes from every block into a single sequence
364
+ var result = [];
365
+ var _loop_1 = function (i) {
366
+ blocks.forEach(function (block, j) {
367
+ // Skip the padding byte in short blocks
368
+ if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
369
+ result.push(block[i]);
370
+ });
403
371
  };
404
- // XORs the codeword modules in this QR Code with the given mask pattern.
405
- // The function modules must be marked and the codeword bits must be drawn
406
- // before masking. Due to the arithmetic of XOR, calling applyMask() with
407
- // the same mask value a second time will undo the mask. A final well-formed
408
- // QR Code needs exactly one (not zero, two, etc.) mask applied.
409
- QrCode.prototype.applyMask = function (mask) {
410
- if (mask < 0 || mask > 7)
411
- throw new RangeError("Mask value out of range");
412
- for (var y = 0; y < this.size; y++) {
413
- for (var x = 0; x < this.size; x++) {
414
- var invert = void 0;
415
- switch (mask) {
416
- case 0:
417
- invert = (x + y) % 2 == 0;
418
- break;
419
- case 1:
420
- invert = y % 2 == 0;
421
- break;
422
- case 2:
423
- invert = x % 3 == 0;
424
- break;
425
- case 3:
426
- invert = (x + y) % 3 == 0;
427
- break;
428
- case 4:
429
- invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
430
- break;
431
- case 5:
432
- invert = x * y % 2 + x * y % 3 == 0;
433
- break;
434
- case 6:
435
- invert = (x * y % 2 + x * y % 3) % 2 == 0;
436
- break;
437
- case 7:
438
- invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
439
- break;
440
- default: throw new Error("Unreachable");
372
+ for (var i = 0; i < blocks[0].length; i++) {
373
+ _loop_1(i);
374
+ }
375
+ assert(result.length == rawCodewords);
376
+ return result;
377
+ };
378
+ // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
379
+ // data area of this QR Code. Function modules need to be marked off before this is called.
380
+ QrCode.prototype.drawCodewords = function (data) {
381
+ if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
382
+ throw new RangeError("Invalid argument");
383
+ var i = 0; // Bit index into the data
384
+ // Do the funny zigzag scan
385
+ for (var right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
386
+ if (right == 6)
387
+ right = 5;
388
+ for (var vert = 0; vert < this.size; vert++) { // Vertical counter
389
+ for (var j = 0; j < 2; j++) {
390
+ var x = right - j; // Actual x coordinate
391
+ var upward = ((right + 1) & 2) == 0;
392
+ var y = upward ? this.size - 1 - vert : vert; // Actual y coordinate
393
+ if (!this.isFunction[y][x] && i < data.length * 8) {
394
+ this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
395
+ i++;
441
396
  }
442
- if (!this.isFunction[y][x] && invert)
443
- this.modules[y][x] = !this.modules[y][x];
397
+ // If this QR Code has any remainder bits (0 to 7), they were assigned as
398
+ // 0/false/light by the constructor and are left unchanged by this method
444
399
  }
445
400
  }
446
- };
447
- // Calculates and returns the penalty score based on state of this QR Code's current modules.
448
- // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
449
- QrCode.prototype.getPenaltyScore = function () {
450
- var result = 0;
451
- // Adjacent modules in row having same color, and finder-like patterns
452
- for (var y = 0; y < this.size; y++) {
453
- var runColor = false;
454
- var runX = 0;
455
- var runHistory = [0, 0, 0, 0, 0, 0, 0];
456
- for (var x = 0; x < this.size; x++) {
457
- if (this.modules[y][x] == runColor) {
458
- runX++;
459
- if (runX == 5)
460
- result += QrCode.PENALTY_N1;
461
- else if (runX > 5)
462
- result++;
463
- }
464
- else {
465
- this.finderPenaltyAddHistory(runX, runHistory);
466
- if (!runColor)
467
- result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
468
- runColor = this.modules[y][x];
469
- runX = 1;
470
- }
401
+ }
402
+ assert(i == data.length * 8);
403
+ };
404
+ // XORs the codeword modules in this QR Code with the given mask pattern.
405
+ // The function modules must be marked and the codeword bits must be drawn
406
+ // before masking. Due to the arithmetic of XOR, calling applyMask() with
407
+ // the same mask value a second time will undo the mask. A final well-formed
408
+ // QR Code needs exactly one (not zero, two, etc.) mask applied.
409
+ QrCode.prototype.applyMask = function (mask) {
410
+ if (mask < 0 || mask > 7)
411
+ throw new RangeError("Mask value out of range");
412
+ for (var y = 0; y < this.size; y++) {
413
+ for (var x = 0; x < this.size; x++) {
414
+ var invert = void 0;
415
+ switch (mask) {
416
+ case 0:
417
+ invert = (x + y) % 2 == 0;
418
+ break;
419
+ case 1:
420
+ invert = y % 2 == 0;
421
+ break;
422
+ case 2:
423
+ invert = x % 3 == 0;
424
+ break;
425
+ case 3:
426
+ invert = (x + y) % 3 == 0;
427
+ break;
428
+ case 4:
429
+ invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
430
+ break;
431
+ case 5:
432
+ invert = x * y % 2 + x * y % 3 == 0;
433
+ break;
434
+ case 6:
435
+ invert = (x * y % 2 + x * y % 3) % 2 == 0;
436
+ break;
437
+ case 7:
438
+ invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
439
+ break;
440
+ default: throw new Error("Unreachable");
471
441
  }
472
- result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
442
+ if (!this.isFunction[y][x] && invert)
443
+ this.modules[y][x] = !this.modules[y][x];
473
444
  }
474
- // Adjacent modules in column having same color, and finder-like patterns
445
+ }
446
+ };
447
+ // Calculates and returns the penalty score based on state of this QR Code's current modules.
448
+ // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
449
+ QrCode.prototype.getPenaltyScore = function () {
450
+ var result = 0;
451
+ // Adjacent modules in row having same color, and finder-like patterns
452
+ for (var y = 0; y < this.size; y++) {
453
+ var runColor = false;
454
+ var runX = 0;
455
+ var runHistory = [0, 0, 0, 0, 0, 0, 0];
475
456
  for (var x = 0; x < this.size; x++) {
476
- var runColor = false;
477
- var runY = 0;
478
- var runHistory = [0, 0, 0, 0, 0, 0, 0];
479
- for (var y = 0; y < this.size; y++) {
480
- if (this.modules[y][x] == runColor) {
481
- runY++;
482
- if (runY == 5)
483
- result += QrCode.PENALTY_N1;
484
- else if (runY > 5)
485
- result++;
486
- }
487
- else {
488
- this.finderPenaltyAddHistory(runY, runHistory);
489
- if (!runColor)
490
- result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
491
- runColor = this.modules[y][x];
492
- runY = 1;
493
- }
457
+ if (this.modules[y][x] == runColor) {
458
+ runX++;
459
+ if (runX == 5)
460
+ result += QrCode.PENALTY_N1;
461
+ else if (runX > 5)
462
+ result++;
494
463
  }
495
- result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
496
- }
497
- // 2*2 blocks of modules having same color
498
- for (var y = 0; y < this.size - 1; y++) {
499
- for (var x = 0; x < this.size - 1; x++) {
500
- var color = this.modules[y][x];
501
- if (color == this.modules[y][x + 1] &&
502
- color == this.modules[y + 1][x] &&
503
- color == this.modules[y + 1][x + 1])
504
- result += QrCode.PENALTY_N2;
464
+ else {
465
+ this.finderPenaltyAddHistory(runX, runHistory);
466
+ if (!runColor)
467
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
468
+ runColor = this.modules[y][x];
469
+ runX = 1;
505
470
  }
506
471
  }
507
- // Balance of dark and light modules
508
- var dark = 0;
509
- for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
510
- var row = _a[_i];
511
- dark = row.reduce(function (sum, color) { return sum + (color ? 1 : 0); }, dark);
512
- }
513
- var total = this.size * this.size; // Note that size is odd, so dark/total != 1/2
514
- // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
515
- var k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
516
- assert(0 <= k && k <= 9);
517
- result += k * QrCode.PENALTY_N4;
518
- assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
519
- return result;
520
- };
521
- /*-- Private helper functions --*/
522
- // Returns an ascending list of positions of alignment patterns for this version number.
523
- // Each position is in the range [0,177), and are used on both the x and y axes.
524
- // This could be implemented as lookup table of 40 variable-length lists of integers.
525
- QrCode.prototype.getAlignmentPatternPositions = function () {
526
- if (this.version == 1)
527
- return [];
528
- else {
529
- var numAlign = Math.floor(this.version / 7) + 2;
530
- var step = (this.version == 32) ? 26 :
531
- Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;
532
- var result = [6];
533
- for (var pos = this.size - 7; result.length < numAlign; pos -= step)
534
- result.splice(1, 0, pos);
535
- return result;
536
- }
537
- };
538
- // Returns the number of data bits that can be stored in a QR Code of the given version number, after
539
- // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
540
- // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
541
- QrCode.getNumRawDataModules = function (ver) {
542
- if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
543
- throw new RangeError("Version number out of range");
544
- var result = (16 * ver + 128) * ver + 64;
545
- if (ver >= 2) {
546
- var numAlign = Math.floor(ver / 7) + 2;
547
- result -= (25 * numAlign - 10) * numAlign - 55;
548
- if (ver >= 7)
549
- result -= 36;
550
- }
551
- assert(208 <= result && result <= 29648);
552
- return result;
553
- };
554
- // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
555
- // QR Code of the given version number and error correction level, with remainder bits discarded.
556
- // This stateless pure function could be implemented as a (40*4)-cell lookup table.
557
- QrCode.getNumDataCodewords = function (ver, ecl) {
558
- return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
559
- QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *
560
- QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
561
- };
562
- // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
563
- // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
564
- QrCode.reedSolomonComputeDivisor = function (degree) {
565
- if (degree < 1 || degree > 255)
566
- throw new RangeError("Degree out of range");
567
- // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
568
- // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
569
- var result = [];
570
- for (var i = 0; i < degree - 1; i++)
571
- result.push(0);
572
- result.push(1); // Start off with the monomial x^0
573
- // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
574
- // and drop the highest monomial term which is always 1x^degree.
575
- // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
576
- var root = 1;
577
- for (var i = 0; i < degree; i++) {
578
- // Multiply the current product by (x - r^i)
579
- for (var j = 0; j < result.length; j++) {
580
- result[j] = QrCode.reedSolomonMultiply(result[j], root);
581
- if (j + 1 < result.length)
582
- result[j] ^= result[j + 1];
472
+ result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
473
+ }
474
+ // Adjacent modules in column having same color, and finder-like patterns
475
+ for (var x = 0; x < this.size; x++) {
476
+ var runColor = false;
477
+ var runY = 0;
478
+ var runHistory = [0, 0, 0, 0, 0, 0, 0];
479
+ for (var y = 0; y < this.size; y++) {
480
+ if (this.modules[y][x] == runColor) {
481
+ runY++;
482
+ if (runY == 5)
483
+ result += QrCode.PENALTY_N1;
484
+ else if (runY > 5)
485
+ result++;
486
+ }
487
+ else {
488
+ this.finderPenaltyAddHistory(runY, runHistory);
489
+ if (!runColor)
490
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
491
+ runColor = this.modules[y][x];
492
+ runY = 1;
583
493
  }
584
- root = QrCode.reedSolomonMultiply(root, 0x02);
585
494
  }
586
- return result;
587
- };
588
- // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
589
- QrCode.reedSolomonComputeRemainder = function (data, divisor) {
590
- var result = divisor.map(function (_) { return 0; });
591
- var _loop_2 = function (b) {
592
- var factor = b ^ result.shift();
593
- result.push(0);
594
- divisor.forEach(function (coef, i) {
595
- return result[i] ^= QrCode.reedSolomonMultiply(coef, factor);
596
- });
597
- };
598
- for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
599
- var b = data_1[_i];
600
- _loop_2(b);
495
+ result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
496
+ }
497
+ // 2*2 blocks of modules having same color
498
+ for (var y = 0; y < this.size - 1; y++) {
499
+ for (var x = 0; x < this.size - 1; x++) {
500
+ var color = this.modules[y][x];
501
+ if (color == this.modules[y][x + 1] &&
502
+ color == this.modules[y + 1][x] &&
503
+ color == this.modules[y + 1][x + 1])
504
+ result += QrCode.PENALTY_N2;
601
505
  }
506
+ }
507
+ // Balance of dark and light modules
508
+ var dark = 0;
509
+ for (var _i = 0, _a = this.modules; _i < _a.length; _i++) {
510
+ var row = _a[_i];
511
+ dark = row.reduce(function (sum, color) { return sum + (color ? 1 : 0); }, dark);
512
+ }
513
+ var total = this.size * this.size; // Note that size is odd, so dark/total != 1/2
514
+ // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
515
+ var k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
516
+ assert(0 <= k && k <= 9);
517
+ result += k * QrCode.PENALTY_N4;
518
+ assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
519
+ return result;
520
+ };
521
+ /*-- Private helper functions --*/
522
+ // Returns an ascending list of positions of alignment patterns for this version number.
523
+ // Each position is in the range [0,177), and are used on both the x and y axes.
524
+ // This could be implemented as lookup table of 40 variable-length lists of integers.
525
+ QrCode.prototype.getAlignmentPatternPositions = function () {
526
+ if (this.version == 1)
527
+ return [];
528
+ else {
529
+ var numAlign = Math.floor(this.version / 7) + 2;
530
+ var step = Math.floor((this.version * 8 + numAlign * 3 + 5) / (numAlign * 4 - 4)) * 2;
531
+ var result = [6];
532
+ for (var pos = this.size - 7; result.length < numAlign; pos -= step)
533
+ result.splice(1, 0, pos);
602
534
  return result;
603
- };
604
- // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
605
- // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
606
- QrCode.reedSolomonMultiply = function (x, y) {
607
- if (x >>> 8 != 0 || y >>> 8 != 0)
608
- throw new RangeError("Byte out of range");
609
- // Russian peasant multiplication
610
- var z = 0;
611
- for (var i = 7; i >= 0; i--) {
612
- z = (z << 1) ^ ((z >>> 7) * 0x11D);
613
- z ^= ((y >>> i) & 1) * x;
535
+ }
536
+ };
537
+ // Returns the number of data bits that can be stored in a QR Code of the given version number, after
538
+ // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
539
+ // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
540
+ QrCode.getNumRawDataModules = function (ver) {
541
+ if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
542
+ throw new RangeError("Version number out of range");
543
+ var result = (16 * ver + 128) * ver + 64;
544
+ if (ver >= 2) {
545
+ var numAlign = Math.floor(ver / 7) + 2;
546
+ result -= (25 * numAlign - 10) * numAlign - 55;
547
+ if (ver >= 7)
548
+ result -= 36;
549
+ }
550
+ assert(208 <= result && result <= 29648);
551
+ return result;
552
+ };
553
+ // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
554
+ // QR Code of the given version number and error correction level, with remainder bits discarded.
555
+ // This stateless pure function could be implemented as a (40*4)-cell lookup table.
556
+ QrCode.getNumDataCodewords = function (ver, ecl) {
557
+ return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
558
+ QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *
559
+ QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
560
+ };
561
+ // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
562
+ // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
563
+ QrCode.reedSolomonComputeDivisor = function (degree) {
564
+ if (degree < 1 || degree > 255)
565
+ throw new RangeError("Degree out of range");
566
+ // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
567
+ // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
568
+ var result = [];
569
+ for (var i = 0; i < degree - 1; i++)
570
+ result.push(0);
571
+ result.push(1); // Start off with the monomial x^0
572
+ // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
573
+ // and drop the highest monomial term which is always 1x^degree.
574
+ // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
575
+ var root = 1;
576
+ for (var i = 0; i < degree; i++) {
577
+ // Multiply the current product by (x - r^i)
578
+ for (var j = 0; j < result.length; j++) {
579
+ result[j] = QrCode.reedSolomonMultiply(result[j], root);
580
+ if (j + 1 < result.length)
581
+ result[j] ^= result[j + 1];
614
582
  }
615
- assert(z >>> 8 == 0);
616
- return z;
617
- };
618
- // Can only be called immediately after a light run is added, and
619
- // returns either 0, 1, or 2. A helper function for getPenaltyScore().
620
- QrCode.prototype.finderPenaltyCountPatterns = function (runHistory) {
621
- var n = runHistory[1];
622
- assert(n <= this.size * 3);
623
- var core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
624
- return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
625
- + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
583
+ root = QrCode.reedSolomonMultiply(root, 0x02);
584
+ }
585
+ return result;
586
+ };
587
+ // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
588
+ QrCode.reedSolomonComputeRemainder = function (data, divisor) {
589
+ var result = divisor.map(function (_) { return 0; });
590
+ var _loop_2 = function (b) {
591
+ var factor = b ^ result.shift();
592
+ result.push(0);
593
+ divisor.forEach(function (coef, i) {
594
+ return result[i] ^= QrCode.reedSolomonMultiply(coef, factor);
595
+ });
626
596
  };
627
- // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
628
- QrCode.prototype.finderPenaltyTerminateAndCount = function (currentRunColor, currentRunLength, runHistory) {
629
- if (currentRunColor) { // Terminate dark run
630
- this.finderPenaltyAddHistory(currentRunLength, runHistory);
631
- currentRunLength = 0;
632
- }
633
- currentRunLength += this.size; // Add light border to final run
597
+ for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
598
+ var b = data_1[_i];
599
+ _loop_2(b);
600
+ }
601
+ return result;
602
+ };
603
+ // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
604
+ // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
605
+ QrCode.reedSolomonMultiply = function (x, y) {
606
+ if (x >>> 8 != 0 || y >>> 8 != 0)
607
+ throw new RangeError("Byte out of range");
608
+ // Russian peasant multiplication
609
+ var z = 0;
610
+ for (var i = 7; i >= 0; i--) {
611
+ z = (z << 1) ^ ((z >>> 7) * 0x11D);
612
+ z ^= ((y >>> i) & 1) * x;
613
+ }
614
+ assert(z >>> 8 == 0);
615
+ return z;
616
+ };
617
+ // Can only be called immediately after a light run is added, and
618
+ // returns either 0, 1, or 2. A helper function for getPenaltyScore().
619
+ QrCode.prototype.finderPenaltyCountPatterns = function (runHistory) {
620
+ var n = runHistory[1];
621
+ assert(n <= this.size * 3);
622
+ var core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
623
+ return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
624
+ + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
625
+ };
626
+ // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
627
+ QrCode.prototype.finderPenaltyTerminateAndCount = function (currentRunColor, currentRunLength, runHistory) {
628
+ if (currentRunColor) { // Terminate dark run
634
629
  this.finderPenaltyAddHistory(currentRunLength, runHistory);
635
- return this.finderPenaltyCountPatterns(runHistory);
636
- };
637
- // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
638
- QrCode.prototype.finderPenaltyAddHistory = function (currentRunLength, runHistory) {
639
- if (runHistory[0] == 0)
640
- currentRunLength += this.size; // Add light border to initial run
641
- runHistory.pop();
642
- runHistory.unshift(currentRunLength);
643
- };
644
- /*-- Constants and tables --*/
645
- // The minimum version number supported in the QR Code Model 2 standard.
646
- QrCode.MIN_VERSION = 1;
647
- // The maximum version number supported in the QR Code Model 2 standard.
648
- QrCode.MAX_VERSION = 40;
649
- // For use in getPenaltyScore(), when evaluating which mask is best.
650
- QrCode.PENALTY_N1 = 3;
651
- QrCode.PENALTY_N2 = 3;
652
- QrCode.PENALTY_N3 = 40;
653
- QrCode.PENALTY_N4 = 10;
654
- QrCode.ECC_CODEWORDS_PER_BLOCK = [
655
- // Version: (note that index 0 is for padding, and is set to an illegal value)
656
- //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
657
- [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
658
- [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],
659
- [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],
660
- [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High
661
- ];
662
- QrCode.NUM_ERROR_CORRECTION_BLOCKS = [
663
- // Version: (note that index 0 is for padding, and is set to an illegal value)
664
- //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
665
- [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],
666
- [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],
667
- [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],
668
- [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High
669
- ];
670
- return QrCode;
671
- }());
672
- qrcodegen.QrCode = QrCode;
673
- // Appends the given number of low-order bits of the given value
674
- // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
675
- function appendBits(val, len, bb) {
676
- if (len < 0 || len > 31 || val >>> len != 0)
677
- throw new RangeError("Value out of range");
678
- for (var i = len - 1; i >= 0; i--) // Append bit by bit
679
- bb.push((val >>> i) & 1);
680
- }
681
- // Returns true iff the i'th bit of x is set to 1.
682
- function getBit(x, i) {
683
- return ((x >>> i) & 1) != 0;
684
- }
685
- // Throws an exception if the given condition is false.
686
- function assert(cond) {
687
- if (!cond)
688
- throw new Error("Assertion error");
630
+ currentRunLength = 0;
631
+ }
632
+ currentRunLength += this.size; // Add light border to final run
633
+ this.finderPenaltyAddHistory(currentRunLength, runHistory);
634
+ return this.finderPenaltyCountPatterns(runHistory);
635
+ };
636
+ // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
637
+ QrCode.prototype.finderPenaltyAddHistory = function (currentRunLength, runHistory) {
638
+ if (runHistory[0] == 0)
639
+ currentRunLength += this.size; // Add light border to initial run
640
+ runHistory.pop();
641
+ runHistory.unshift(currentRunLength);
642
+ };
643
+ /*-- Constants and tables --*/
644
+ // The minimum version number supported in the QR Code Model 2 standard.
645
+ QrCode.MIN_VERSION = 1;
646
+ // The maximum version number supported in the QR Code Model 2 standard.
647
+ QrCode.MAX_VERSION = 40;
648
+ // For use in getPenaltyScore(), when evaluating which mask is best.
649
+ QrCode.PENALTY_N1 = 3;
650
+ QrCode.PENALTY_N2 = 3;
651
+ QrCode.PENALTY_N3 = 40;
652
+ QrCode.PENALTY_N4 = 10;
653
+ QrCode.ECC_CODEWORDS_PER_BLOCK = [
654
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
655
+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
656
+ [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low
657
+ [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium
658
+ [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile
659
+ [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High
660
+ ];
661
+ QrCode.NUM_ERROR_CORRECTION_BLOCKS = [
662
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
663
+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
664
+ [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low
665
+ [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium
666
+ [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile
667
+ [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High
668
+ ];
669
+ return QrCode;
670
+ }());
671
+ qrcodegen.QrCode = QrCode;
672
+ // Appends the given number of low-order bits of the given value
673
+ // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
674
+ function appendBits(val, len, bb) {
675
+ if (len < 0 || len > 31 || val >>> len != 0)
676
+ throw new RangeError("Value out of range");
677
+ for (var i = len - 1; i >= 0; i--) // Append bit by bit
678
+ bb.push((val >>> i) & 1);
679
+ }
680
+ // Returns true iff the i'th bit of x is set to 1.
681
+ function getBit(x, i) {
682
+ return ((x >>> i) & 1) != 0;
683
+ }
684
+ // Throws an exception if the given condition is false.
685
+ function assert(cond) {
686
+ if (!cond)
687
+ throw new Error("Assertion error");
688
+ }
689
+ /*---- Data segment class ----*/
690
+ /*
691
+ * A segment of character/binary/control data in a QR Code symbol.
692
+ * Instances of this class are immutable.
693
+ * The mid-level way to create a segment is to take the payload data
694
+ * and call a static factory function such as QrSegment.makeNumeric().
695
+ * The low-level way to create a segment is to custom-make the bit buffer
696
+ * and call the QrSegment() constructor with appropriate values.
697
+ * This segment class imposes no length restrictions, but QR Codes have restrictions.
698
+ * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
699
+ * Any segment longer than this is meaningless for the purpose of generating QR Codes.
700
+ */
701
+ var QrSegment = /** @class */ (function () {
702
+ /*-- Constructor (low level) and fields --*/
703
+ // Creates a new QR Code segment with the given attributes and data.
704
+ // The character count (numChars) must agree with the mode and the bit buffer length,
705
+ // but the constraint isn't checked. The given bit buffer is cloned and stored.
706
+ function QrSegment(
707
+ // The mode indicator of this segment.
708
+ mode,
709
+ // The length of this segment's unencoded data. Measured in characters for
710
+ // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
711
+ // Always zero or positive. Not the same as the data's bit length.
712
+ numChars,
713
+ // The data bits of this segment. Accessed through getData().
714
+ bitData) {
715
+ this.mode = mode;
716
+ this.numChars = numChars;
717
+ this.bitData = bitData;
718
+ if (numChars < 0)
719
+ throw new RangeError("Invalid argument");
720
+ this.bitData = bitData.slice(); // Make defensive copy
689
721
  }
690
- /*---- Data segment class ----*/
722
+ /*-- Static factory functions (mid level) --*/
723
+ // Returns a segment representing the given binary data encoded in
724
+ // byte mode. All input byte arrays are acceptable. Any text string
725
+ // can be converted to UTF-8 bytes and encoded as a byte mode segment.
726
+ QrSegment.makeBytes = function (data) {
727
+ var bb = [];
728
+ for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
729
+ var b = data_2[_i];
730
+ appendBits(b, 8, bb);
731
+ }
732
+ return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
733
+ };
734
+ // Returns a segment representing the given string of decimal digits encoded in numeric mode.
735
+ QrSegment.makeNumeric = function (digits) {
736
+ if (!QrSegment.isNumeric(digits))
737
+ throw new RangeError("String contains non-numeric characters");
738
+ var bb = [];
739
+ for (var i = 0; i < digits.length;) { // Consume up to 3 digits per iteration
740
+ var n = Math.min(digits.length - i, 3);
741
+ appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
742
+ i += n;
743
+ }
744
+ return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
745
+ };
746
+ // Returns a segment representing the given text string encoded in alphanumeric mode.
747
+ // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
748
+ // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
749
+ QrSegment.makeAlphanumeric = function (text) {
750
+ if (!QrSegment.isAlphanumeric(text))
751
+ throw new RangeError("String contains unencodable characters in alphanumeric mode");
752
+ var bb = [];
753
+ var i;
754
+ for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2
755
+ var temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
756
+ temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
757
+ appendBits(temp, 11, bb);
758
+ }
759
+ if (i < text.length) // 1 character remaining
760
+ appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
761
+ return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
762
+ };
763
+ // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
764
+ // The result may use various segment modes and switch modes to optimize the length of the bit stream.
765
+ QrSegment.makeSegments = function (text) {
766
+ // Select the most efficient segment encoding automatically
767
+ if (text == "")
768
+ return [];
769
+ else if (QrSegment.isNumeric(text))
770
+ return [QrSegment.makeNumeric(text)];
771
+ else if (QrSegment.isAlphanumeric(text))
772
+ return [QrSegment.makeAlphanumeric(text)];
773
+ else
774
+ return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
775
+ };
776
+ // Returns a segment representing an Extended Channel Interpretation
777
+ // (ECI) designator with the given assignment value.
778
+ QrSegment.makeEci = function (assignVal) {
779
+ var bb = [];
780
+ if (assignVal < 0)
781
+ throw new RangeError("ECI assignment value out of range");
782
+ else if (assignVal < (1 << 7))
783
+ appendBits(assignVal, 8, bb);
784
+ else if (assignVal < (1 << 14)) {
785
+ appendBits(2, 2, bb);
786
+ appendBits(assignVal, 14, bb);
787
+ }
788
+ else if (assignVal < 1000000) {
789
+ appendBits(6, 3, bb);
790
+ appendBits(assignVal, 21, bb);
791
+ }
792
+ else
793
+ throw new RangeError("ECI assignment value out of range");
794
+ return new QrSegment(QrSegment.Mode.ECI, 0, bb);
795
+ };
796
+ // Tests whether the given string can be encoded as a segment in numeric mode.
797
+ // A string is encodable iff each character is in the range 0 to 9.
798
+ QrSegment.isNumeric = function (text) {
799
+ return QrSegment.NUMERIC_REGEX.test(text);
800
+ };
801
+ // Tests whether the given string can be encoded as a segment in alphanumeric mode.
802
+ // A string is encodable iff each character is in the following set: 0 to 9, A to Z
803
+ // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
804
+ QrSegment.isAlphanumeric = function (text) {
805
+ return QrSegment.ALPHANUMERIC_REGEX.test(text);
806
+ };
807
+ /*-- Methods --*/
808
+ // Returns a new copy of the data bits of this segment.
809
+ QrSegment.prototype.getData = function () {
810
+ return this.bitData.slice(); // Make defensive copy
811
+ };
812
+ // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
813
+ // the given version. The result is infinity if a segment has too many characters to fit its length field.
814
+ QrSegment.getTotalBits = function (segs, version) {
815
+ var result = 0;
816
+ for (var _i = 0, segs_2 = segs; _i < segs_2.length; _i++) {
817
+ var seg = segs_2[_i];
818
+ var ccbits = seg.mode.numCharCountBits(version);
819
+ if (seg.numChars >= (1 << ccbits))
820
+ return Infinity; // The segment's length doesn't fit the field's bit width
821
+ result += 4 + ccbits + seg.bitData.length;
822
+ }
823
+ return result;
824
+ };
825
+ // Returns a new array of bytes representing the given string encoded in UTF-8.
826
+ QrSegment.toUtf8ByteArray = function (str) {
827
+ str = encodeURI(str);
828
+ var result = [];
829
+ for (var i = 0; i < str.length; i++) {
830
+ if (str.charAt(i) != "%")
831
+ result.push(str.charCodeAt(i));
832
+ else {
833
+ result.push(parseInt(str.substring(i + 1, i + 3), 16));
834
+ i += 2;
835
+ }
836
+ }
837
+ return result;
838
+ };
839
+ /*-- Constants --*/
840
+ // Describes precisely all strings that are encodable in numeric mode.
841
+ QrSegment.NUMERIC_REGEX = /^[0-9]*$/;
842
+ // Describes precisely all strings that are encodable in alphanumeric mode.
843
+ QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
844
+ // The set of all legal characters in alphanumeric mode,
845
+ // where each character value maps to the index in the string.
846
+ QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
847
+ return QrSegment;
848
+ }());
849
+ qrcodegen.QrSegment = QrSegment;
850
+ })(qrcodegen || (qrcodegen = {}));
851
+ /*---- Public helper enumeration ----*/
852
+ (function (qrcodegen) {
853
+ (function (QrCode) {
691
854
  /*
692
- * A segment of character/binary/control data in a QR Code symbol.
693
- * Instances of this class are immutable.
694
- * The mid-level way to create a segment is to take the payload data
695
- * and call a static factory function such as QrSegment.makeNumeric().
696
- * The low-level way to create a segment is to custom-make the bit buffer
697
- * and call the QrSegment() constructor with appropriate values.
698
- * This segment class imposes no length restrictions, but QR Codes have restrictions.
699
- * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
700
- * Any segment longer than this is meaningless for the purpose of generating QR Codes.
855
+ * The error correction level in a QR Code symbol. Immutable.
701
856
  */
702
- var QrSegment = /** @class */ (function () {
703
- /*-- Constructor (low level) and fields --*/
704
- // Creates a new QR Code segment with the given attributes and data.
705
- // The character count (numChars) must agree with the mode and the bit buffer length,
706
- // but the constraint isn't checked. The given bit buffer is cloned and stored.
707
- function QrSegment(
708
- // The mode indicator of this segment.
709
- mode,
710
- // The length of this segment's unencoded data. Measured in characters for
711
- // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.
712
- // Always zero or positive. Not the same as the data's bit length.
713
- numChars,
714
- // The data bits of this segment. Accessed through getData().
715
- bitData) {
716
- this.mode = mode;
717
- this.numChars = numChars;
718
- this.bitData = bitData;
719
- if (numChars < 0)
720
- throw new RangeError("Invalid argument");
721
- this.bitData = bitData.slice(); // Make defensive copy
857
+ var Ecc = /** @class */ (function () {
858
+ /*-- Constructor and fields --*/
859
+ function Ecc(
860
+ // In the range 0 to 3 (unsigned 2-bit integer).
861
+ ordinal,
862
+ // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
863
+ formatBits) {
864
+ this.ordinal = ordinal;
865
+ this.formatBits = formatBits;
722
866
  }
723
- /*-- Static factory functions (mid level) --*/
724
- // Returns a segment representing the given binary data encoded in
725
- // byte mode. All input byte arrays are acceptable. Any text string
726
- // can be converted to UTF-8 bytes and encoded as a byte mode segment.
727
- QrSegment.makeBytes = function (data) {
728
- var bb = [];
729
- for (var _i = 0, data_2 = data; _i < data_2.length; _i++) {
730
- var b = data_2[_i];
731
- appendBits(b, 8, bb);
732
- }
733
- return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);
734
- };
735
- // Returns a segment representing the given string of decimal digits encoded in numeric mode.
736
- QrSegment.makeNumeric = function (digits) {
737
- if (!QrSegment.isNumeric(digits))
738
- throw new RangeError("String contains non-numeric characters");
739
- var bb = [];
740
- for (var i = 0; i < digits.length;) { // Consume up to 3 digits per iteration
741
- var n = Math.min(digits.length - i, 3);
742
- appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
743
- i += n;
744
- }
745
- return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);
746
- };
747
- // Returns a segment representing the given text string encoded in alphanumeric mode.
748
- // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
749
- // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
750
- QrSegment.makeAlphanumeric = function (text) {
751
- if (!QrSegment.isAlphanumeric(text))
752
- throw new RangeError("String contains unencodable characters in alphanumeric mode");
753
- var bb = [];
754
- var i;
755
- for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2
756
- var temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
757
- temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
758
- appendBits(temp, 11, bb);
759
- }
760
- if (i < text.length) // 1 character remaining
761
- appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
762
- return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);
763
- };
764
- // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
765
- // The result may use various segment modes and switch modes to optimize the length of the bit stream.
766
- QrSegment.makeSegments = function (text) {
767
- // Select the most efficient segment encoding automatically
768
- if (text == "")
769
- return [];
770
- else if (QrSegment.isNumeric(text))
771
- return [QrSegment.makeNumeric(text)];
772
- else if (QrSegment.isAlphanumeric(text))
773
- return [QrSegment.makeAlphanumeric(text)];
774
- else
775
- return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
776
- };
777
- // Returns a segment representing an Extended Channel Interpretation
778
- // (ECI) designator with the given assignment value.
779
- QrSegment.makeEci = function (assignVal) {
780
- var bb = [];
781
- if (assignVal < 0)
782
- throw new RangeError("ECI assignment value out of range");
783
- else if (assignVal < (1 << 7))
784
- appendBits(assignVal, 8, bb);
785
- else if (assignVal < (1 << 14)) {
786
- appendBits(2, 2, bb);
787
- appendBits(assignVal, 14, bb);
788
- }
789
- else if (assignVal < 1000000) {
790
- appendBits(6, 3, bb);
791
- appendBits(assignVal, 21, bb);
792
- }
793
- else
794
- throw new RangeError("ECI assignment value out of range");
795
- return new QrSegment(QrSegment.Mode.ECI, 0, bb);
796
- };
797
- // Tests whether the given string can be encoded as a segment in numeric mode.
798
- // A string is encodable iff each character is in the range 0 to 9.
799
- QrSegment.isNumeric = function (text) {
800
- return QrSegment.NUMERIC_REGEX.test(text);
801
- };
802
- // Tests whether the given string can be encoded as a segment in alphanumeric mode.
803
- // A string is encodable iff each character is in the following set: 0 to 9, A to Z
804
- // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
805
- QrSegment.isAlphanumeric = function (text) {
806
- return QrSegment.ALPHANUMERIC_REGEX.test(text);
807
- };
808
- /*-- Methods --*/
809
- // Returns a new copy of the data bits of this segment.
810
- QrSegment.prototype.getData = function () {
811
- return this.bitData.slice(); // Make defensive copy
812
- };
813
- // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
814
- // the given version. The result is infinity if a segment has too many characters to fit its length field.
815
- QrSegment.getTotalBits = function (segs, version) {
816
- var result = 0;
817
- for (var _i = 0, segs_2 = segs; _i < segs_2.length; _i++) {
818
- var seg = segs_2[_i];
819
- var ccbits = seg.mode.numCharCountBits(version);
820
- if (seg.numChars >= (1 << ccbits))
821
- return Infinity; // The segment's length doesn't fit the field's bit width
822
- result += 4 + ccbits + seg.bitData.length;
823
- }
824
- return result;
825
- };
826
- // Returns a new array of bytes representing the given string encoded in UTF-8.
827
- QrSegment.toUtf8ByteArray = function (str) {
828
- str = encodeURI(str);
829
- var result = [];
830
- for (var i = 0; i < str.length; i++) {
831
- if (str.charAt(i) != "%")
832
- result.push(str.charCodeAt(i));
833
- else {
834
- result.push(parseInt(str.substring(i + 1, i + 3), 16));
835
- i += 2;
836
- }
837
- }
838
- return result;
867
+ /*-- Constants --*/
868
+ Ecc.LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
869
+ Ecc.MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
870
+ Ecc.QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
871
+ Ecc.HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
872
+ return Ecc;
873
+ }());
874
+ QrCode.Ecc = Ecc;
875
+ })(qrcodegen.QrCode || (qrcodegen.QrCode = {}));
876
+ })(qrcodegen || (qrcodegen = {}));
877
+ /*---- Public helper enumeration ----*/
878
+ (function (qrcodegen) {
879
+ (function (QrSegment) {
880
+ /*
881
+ * Describes how a segment's data bits are interpreted. Immutable.
882
+ */
883
+ var Mode = /** @class */ (function () {
884
+ /*-- Constructor and fields --*/
885
+ function Mode(
886
+ // The mode indicator bits, which is a uint4 value (range 0 to 15).
887
+ modeBits,
888
+ // Number of character count bits for three different version ranges.
889
+ numBitsCharCount) {
890
+ this.modeBits = modeBits;
891
+ this.numBitsCharCount = numBitsCharCount;
892
+ }
893
+ /*-- Method --*/
894
+ // (Package-private) Returns the bit width of the character count field for a segment in
895
+ // this mode in a QR Code at the given version number. The result is in the range [0, 16].
896
+ Mode.prototype.numCharCountBits = function (ver) {
897
+ return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
839
898
  };
840
899
  /*-- Constants --*/
841
- // Describes precisely all strings that are encodable in numeric mode.
842
- QrSegment.NUMERIC_REGEX = /^[0-9]*$/;
843
- // Describes precisely all strings that are encodable in alphanumeric mode.
844
- QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
845
- // The set of all legal characters in alphanumeric mode,
846
- // where each character value maps to the index in the string.
847
- QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
848
- return QrSegment;
900
+ Mode.NUMERIC = new Mode(0x1, [10, 12, 14]);
901
+ Mode.ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);
902
+ Mode.BYTE = new Mode(0x4, [8, 16, 16]);
903
+ Mode.KANJI = new Mode(0x8, [8, 10, 12]);
904
+ Mode.ECI = new Mode(0x7, [0, 0, 0]);
905
+ return Mode;
849
906
  }());
850
- qrcodegen.QrSegment = QrSegment;
851
- })(qrcodegen || (qrcodegen = {}));
852
- /*---- Public helper enumeration ----*/
853
- (function (qrcodegen) {
854
- (function (QrCode) {
855
- /*
856
- * The error correction level in a QR Code symbol. Immutable.
857
- */
858
- var Ecc = /** @class */ (function () {
859
- /*-- Constructor and fields --*/
860
- function Ecc(
861
- // In the range 0 to 3 (unsigned 2-bit integer).
862
- ordinal,
863
- // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).
864
- formatBits) {
865
- this.ordinal = ordinal;
866
- this.formatBits = formatBits;
867
- }
868
- /*-- Constants --*/
869
- Ecc.LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
870
- Ecc.MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
871
- Ecc.QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
872
- Ecc.HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
873
- return Ecc;
874
- }());
875
- QrCode.Ecc = Ecc;
876
- })(qrcodegen.QrCode || (qrcodegen.QrCode = {}));
877
- })(qrcodegen || (qrcodegen = {}));
878
- /*---- Public helper enumeration ----*/
879
- (function (qrcodegen) {
880
- (function (QrSegment) {
881
- /*
882
- * Describes how a segment's data bits are interpreted. Immutable.
883
- */
884
- var Mode = /** @class */ (function () {
885
- /*-- Constructor and fields --*/
886
- function Mode(
887
- // The mode indicator bits, which is a uint4 value (range 0 to 15).
888
- modeBits,
889
- // Number of character count bits for three different version ranges.
890
- numBitsCharCount) {
891
- this.modeBits = modeBits;
892
- this.numBitsCharCount = numBitsCharCount;
893
- }
894
- /*-- Method --*/
895
- // (Package-private) Returns the bit width of the character count field for a segment in
896
- // this mode in a QR Code at the given version number. The result is in the range [0, 16].
897
- Mode.prototype.numCharCountBits = function (ver) {
898
- return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
899
- };
900
- /*-- Constants --*/
901
- Mode.NUMERIC = new Mode(0x1, [10, 12, 14]);
902
- Mode.ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);
903
- Mode.BYTE = new Mode(0x4, [8, 16, 16]);
904
- Mode.KANJI = new Mode(0x8, [8, 10, 12]);
905
- Mode.ECI = new Mode(0x7, [0, 0, 0]);
906
- return Mode;
907
- }());
908
- QrSegment.Mode = Mode;
909
- })(qrcodegen.QrSegment || (qrcodegen.QrSegment = {}));
910
- })(qrcodegen || (qrcodegen = {}));
911
- var QR = qrcodegen;
907
+ QrSegment.Mode = Mode;
908
+ })(qrcodegen.QrSegment || (qrcodegen.QrSegment = {}));
909
+ })(qrcodegen || (qrcodegen = {}));
910
+ var QR = qrcodegen;
912
911
 
913
- var defaultErrorCorrectLevel = 'H';
914
- var ErrorCorrectLevelMap = {
915
- L: QR.QrCode.Ecc.LOW,
916
- M: QR.QrCode.Ecc.MEDIUM,
917
- Q: QR.QrCode.Ecc.QUARTILE,
918
- H: QR.QrCode.Ecc.HIGH,
919
- };
920
- // Thanks the `qrcode.react`
921
- var SUPPORTS_PATH2D = (function () {
922
- try {
923
- new Path2D().addPath(new Path2D());
924
- }
925
- catch (e) {
926
- return false;
927
- }
928
- return true;
929
- })();
930
- function validErrorCorrectLevel(level) {
931
- return level in ErrorCorrectLevelMap;
912
+ var defaultErrorCorrectLevel = 'L';
913
+ var ErrorCorrectLevelMap = {
914
+ L: QR.QrCode.Ecc.LOW,
915
+ M: QR.QrCode.Ecc.MEDIUM,
916
+ Q: QR.QrCode.Ecc.QUARTILE,
917
+ H: QR.QrCode.Ecc.HIGH,
918
+ };
919
+ // Thanks the `qrcode.react`
920
+ var SUPPORTS_PATH2D = (function () {
921
+ try {
922
+ new Path2D().addPath(new Path2D());
923
+ }
924
+ catch (e) {
925
+ return false;
932
926
  }
933
- function generatePath(modules, margin) {
934
- if (margin === void 0) { margin = 0; }
935
- var ops = [];
936
- modules.forEach(function (row, y) {
937
- var start = null;
938
- row.forEach(function (cell, x) {
939
- if (!cell && start !== null) {
940
- // M0 0h7v1H0z injects the space with the move and drops the comma,
941
- // saving a char per operation
942
- ops.push("M".concat(start + margin, " ").concat(y + margin, "h").concat(x - start, "v1H").concat(start + margin, "z"));
943
- start = null;
927
+ return true;
928
+ })();
929
+ function validErrorCorrectLevel(level) {
930
+ return level in ErrorCorrectLevelMap;
931
+ }
932
+ function generatePath(modules, margin) {
933
+ if (margin === void 0) { margin = 0; }
934
+ var ops = [];
935
+ modules.forEach(function (row, y) {
936
+ var start = null;
937
+ row.forEach(function (cell, x) {
938
+ if (!cell && start !== null) {
939
+ // M0 0h7v1H0z injects the space with the move and drops the comma,
940
+ // saving a char per operation
941
+ ops.push("M".concat(start + margin, " ").concat(y + margin, "h").concat(x - start, "v1H").concat(start + margin, "z"));
942
+ start = null;
943
+ return;
944
+ }
945
+ // end of row, clean up or skip
946
+ if (x === row.length - 1) {
947
+ if (!cell) {
948
+ // We would have closed the op above already so this can only mean
949
+ // 2+ light modules in a row.
944
950
  return;
945
951
  }
946
- // end of row, clean up or skip
947
- if (x === row.length - 1) {
948
- if (!cell) {
949
- // We would have closed the op above already so this can only mean
950
- // 2+ light modules in a row.
951
- return;
952
- }
953
- if (start === null) {
954
- // Just a single dark module.
955
- ops.push("M".concat(x + margin, ",").concat(y + margin, " h1v1H").concat(x + margin, "z"));
956
- }
957
- else {
958
- // Otherwise finish the current line.
959
- ops.push("M".concat(start + margin, ",").concat(y + margin, " h").concat(x + 1 - start, "v1H").concat(start + margin, "z"));
960
- }
961
- return;
952
+ if (start === null) {
953
+ // Just a single dark module.
954
+ ops.push("M".concat(x + margin, ",").concat(y + margin, " h1v1H").concat(x + margin, "z"));
962
955
  }
963
- if (cell && start === null) {
964
- start = x;
956
+ else {
957
+ // Otherwise finish the current line.
958
+ ops.push("M".concat(start + margin, ",").concat(y + margin, " h").concat(x + 1 - start, "v1H").concat(start + margin, "z"));
965
959
  }
966
- });
960
+ return;
961
+ }
962
+ if (cell && start === null) {
963
+ start = x;
964
+ }
967
965
  });
968
- return ops.join('');
966
+ });
967
+ return ops.join('');
968
+ }
969
+ function getImageSettings(cells, size, margin, imageSettings) {
970
+ var width = imageSettings.width, height = imageSettings.height, imageX = imageSettings.x, imageY = imageSettings.y;
971
+ var numCells = cells.length + margin * 2;
972
+ var defaultSize = Math.floor(size * 0.1);
973
+ var scale = numCells / size;
974
+ var w = (width || defaultSize) * scale;
975
+ var h = (height || defaultSize) * scale;
976
+ var x = imageX == null ? cells.length / 2 - w / 2 : imageX * scale;
977
+ var y = imageY == null ? cells.length / 2 - h / 2 : imageY * scale;
978
+ var excavation = null;
979
+ if (imageSettings.excavate) {
980
+ var floorX = Math.floor(x);
981
+ var floorY = Math.floor(y);
982
+ var ceilW = Math.ceil(w + x - floorX);
983
+ var ceilH = Math.ceil(h + y - floorY);
984
+ excavation = { x: floorX, y: floorY, w: ceilW, h: ceilH };
969
985
  }
970
- var QRCodeProps = {
971
- value: {
972
- type: String,
973
- required: true,
974
- default: '',
975
- },
976
- size: {
977
- type: Number,
978
- default: 100,
979
- },
980
- level: {
981
- type: String,
982
- default: defaultErrorCorrectLevel,
983
- validator: function (l) { return validErrorCorrectLevel(l); },
984
- },
985
- background: {
986
- type: String,
987
- default: '#fff',
988
- },
989
- foreground: {
990
- type: String,
991
- default: '#000',
992
- },
993
- margin: {
994
- type: Number,
995
- required: false,
996
- default: 0,
997
- },
998
- };
999
- var QRCodeVueProps = __assign(__assign({}, QRCodeProps), { renderAs: {
1000
- type: String,
1001
- required: false,
1002
- default: 'canvas',
1003
- validator: function (as) { return ['canvas', 'svg'].indexOf(as) > -1; },
1004
- } });
1005
- var QRCodeSvg = vue.defineComponent({
1006
- name: 'QRCodeSvg',
1007
- props: QRCodeProps,
1008
- setup: function (props) {
1009
- var numCells = vue.ref(0);
1010
- var fgPath = vue.ref('');
1011
- var generate = function () {
1012
- var value = props.value, level = props.level, margin = props.margin;
1013
- var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
1014
- numCells.value = cells.length + margin * 2;
1015
- // Drawing strategy: instead of a rect per module, we're going to create a
1016
- // single path for the dark modules and layer that on top of a light rect,
1017
- // for a total of 2 DOM nodes. We pay a bit more in string concat but that's
1018
- // way faster than DOM ops.
1019
- // For level 1, 441 nodes -> 2
1020
- // For level 40, 31329 -> 2
1021
- fgPath.value = generatePath(cells, margin);
1022
- };
1023
- generate();
1024
- vue.onUpdated(generate);
1025
- return function () { return vue.h('svg', {
1026
- width: props.size,
1027
- height: props.size,
1028
- 'shape-rendering': "crispEdges",
1029
- xmlns: 'http://www.w3.org/2000/svg',
1030
- viewBox: "0 0 ".concat(numCells.value, " ").concat(numCells.value),
1031
- }, [
1032
- vue.h('path', {
1033
- fill: props.background,
1034
- d: "M0,0 h".concat(numCells.value, "v").concat(numCells.value, "H0z"),
1035
- }),
1036
- vue.h('path', { fill: props.foreground, d: fgPath.value }),
1037
- ]); };
1038
- },
986
+ return { x: x, y: y, h: h, w: w, excavation: excavation };
987
+ }
988
+ function excavateModules(modules, excavation) {
989
+ return modules.slice().map(function (row, y) {
990
+ if (y < excavation.y || y >= excavation.y + excavation.h) {
991
+ return row;
992
+ }
993
+ return row.map(function (cell, x) {
994
+ if (x < excavation.x || x >= excavation.x + excavation.w) {
995
+ return cell;
996
+ }
997
+ return false;
998
+ });
1039
999
  });
1040
- var QRCodeCanvas = vue.defineComponent({
1041
- name: 'QRCodeCanvas',
1042
- props: QRCodeProps,
1043
- setup: function (props) {
1044
- var canvasEl = vue.ref(null);
1045
- var generate = function () {
1046
- var value = props.value, level = props.level, size = props.size, margin = props.margin, background = props.background, foreground = props.foreground;
1047
- var canvas = canvasEl.value;
1048
- if (!canvas) {
1049
- return;
1050
- }
1051
- var ctx = canvas.getContext('2d');
1052
- if (!ctx) {
1053
- return;
1000
+ }
1001
+ var QRCodeProps = {
1002
+ value: {
1003
+ type: String,
1004
+ required: true,
1005
+ default: '',
1006
+ },
1007
+ size: {
1008
+ type: Number,
1009
+ default: 100,
1010
+ },
1011
+ level: {
1012
+ type: String,
1013
+ default: defaultErrorCorrectLevel,
1014
+ validator: function (l) { return validErrorCorrectLevel(l); },
1015
+ },
1016
+ background: {
1017
+ type: String,
1018
+ default: '#fff',
1019
+ },
1020
+ foreground: {
1021
+ type: String,
1022
+ default: '#000',
1023
+ },
1024
+ margin: {
1025
+ type: Number,
1026
+ required: false,
1027
+ default: 0,
1028
+ },
1029
+ imageSettings: {
1030
+ type: Object,
1031
+ required: false,
1032
+ default: function () { return ({}); },
1033
+ },
1034
+ };
1035
+ var QRCodeVueProps = __assign(__assign({}, QRCodeProps), { renderAs: {
1036
+ type: String,
1037
+ required: false,
1038
+ default: 'canvas',
1039
+ validator: function (as) { return ['canvas', 'svg'].indexOf(as) > -1; },
1040
+ } });
1041
+ var QrcodeSvg = vue.defineComponent({
1042
+ name: 'QRCodeSvg',
1043
+ props: QRCodeProps,
1044
+ setup: function (props) {
1045
+ var numCells = vue.ref(0);
1046
+ var fgPath = vue.ref('');
1047
+ var imageProps;
1048
+ var generate = function () {
1049
+ var value = props.value, level = props.level, margin = props.margin;
1050
+ var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
1051
+ numCells.value = cells.length + margin * 2;
1052
+ if (props.imageSettings.src) {
1053
+ var imageSettings = getImageSettings(cells, props.size, margin, props.imageSettings);
1054
+ imageProps = {
1055
+ x: imageSettings.x + margin,
1056
+ y: imageSettings.y + margin,
1057
+ width: imageSettings.w,
1058
+ height: imageSettings.h,
1059
+ };
1060
+ if (imageSettings.excavation) {
1061
+ cells = excavateModules(cells, imageSettings.excavation);
1054
1062
  }
1055
- var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
1056
- var numCells = cells.length + margin * 2;
1057
- var devicePixelRatio = window.devicePixelRatio || 1;
1058
- var scale = (size / numCells) * devicePixelRatio;
1059
- canvas.height = canvas.width = size * devicePixelRatio;
1060
- ctx.scale(scale, scale);
1061
- ctx.fillStyle = background;
1062
- ctx.fillRect(0, 0, numCells, numCells);
1063
- ctx.fillStyle = foreground;
1064
- if (SUPPORTS_PATH2D) {
1065
- ctx.fill(new Path2D(generatePath(cells, margin)));
1063
+ }
1064
+ // Drawing strategy: instead of a rect per module, we're going to create a
1065
+ // single path for the dark modules and layer that on top of a light rect,
1066
+ // for a total of 2 DOM nodes. We pay a bit more in string concat but that's
1067
+ // way faster than DOM ops.
1068
+ // For level 1, 441 nodes -> 2
1069
+ // For level 40, 31329 -> 2
1070
+ fgPath.value = generatePath(cells, margin);
1071
+ };
1072
+ generate();
1073
+ vue.onUpdated(generate);
1074
+ return function () { return vue.h('svg', {
1075
+ width: props.size,
1076
+ height: props.size,
1077
+ 'shape-rendering': "crispEdges",
1078
+ xmlns: 'http://www.w3.org/2000/svg',
1079
+ viewBox: "0 0 ".concat(numCells.value, " ").concat(numCells.value),
1080
+ }, [
1081
+ vue.h('path', {
1082
+ fill: props.background,
1083
+ d: "M0,0 h".concat(numCells.value, "v").concat(numCells.value, "H0z"),
1084
+ }),
1085
+ vue.h('path', { fill: props.foreground, d: fgPath.value }),
1086
+ props.imageSettings.src && vue.h('image', __assign({ href: props.imageSettings.src }, imageProps)),
1087
+ ]); };
1088
+ },
1089
+ });
1090
+ var QrcodeCanvas = vue.defineComponent({
1091
+ name: 'QRCodeCanvas',
1092
+ props: QRCodeProps,
1093
+ setup: function (props, ctx) {
1094
+ var canvasEl = vue.ref(null);
1095
+ var imageRef = vue.ref(null);
1096
+ var generate = function () {
1097
+ var value = props.value, level = props.level, size = props.size, margin = props.margin, background = props.background, foreground = props.foreground;
1098
+ var canvas = canvasEl.value;
1099
+ if (!canvas) {
1100
+ return;
1101
+ }
1102
+ var ctx = canvas.getContext('2d');
1103
+ if (!ctx) {
1104
+ return;
1105
+ }
1106
+ var cells = QR.QrCode.encodeText(value, ErrorCorrectLevelMap[level]).getModules();
1107
+ var numCells = cells.length + margin * 2;
1108
+ var image = imageRef.value;
1109
+ var imageProps = { x: 0, y: 0, width: 0, height: 0 };
1110
+ var showImage = props.imageSettings.src && image != null && image.naturalWidth !== 0 && image.naturalHeight !== 0;
1111
+ if (showImage) {
1112
+ var imageSettings = getImageSettings(cells, props.size, margin, props.imageSettings);
1113
+ imageProps = {
1114
+ x: imageSettings.x + margin,
1115
+ y: imageSettings.y + margin,
1116
+ width: imageSettings.w,
1117
+ height: imageSettings.h,
1118
+ };
1119
+ if (imageSettings.excavation) {
1120
+ cells = excavateModules(cells, imageSettings.excavation);
1066
1121
  }
1067
- else {
1068
- cells.forEach(function (row, rdx) {
1069
- row.forEach(function (cell, cdx) {
1070
- if (cell) {
1071
- ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
1072
- }
1073
- });
1122
+ }
1123
+ var devicePixelRatio = window.devicePixelRatio || 1;
1124
+ var scale = (size / numCells) * devicePixelRatio;
1125
+ canvas.height = canvas.width = size * devicePixelRatio;
1126
+ ctx.scale(scale, scale);
1127
+ ctx.fillStyle = background;
1128
+ ctx.fillRect(0, 0, numCells, numCells);
1129
+ ctx.fillStyle = foreground;
1130
+ if (SUPPORTS_PATH2D) {
1131
+ ctx.fill(new Path2D(generatePath(cells, margin)));
1132
+ }
1133
+ else {
1134
+ cells.forEach(function (row, rdx) {
1135
+ row.forEach(function (cell, cdx) {
1136
+ if (cell) {
1137
+ ctx.fillRect(cdx + margin, rdx + margin, 1, 1);
1138
+ }
1074
1139
  });
1075
- }
1076
- };
1077
- vue.onMounted(generate);
1078
- vue.onUpdated(generate);
1079
- return function () { return vue.h('canvas', {
1080
- ref: canvasEl,
1081
- style: { width: "".concat(props.size, "px"), height: "".concat(props.size, "px") },
1082
- }); };
1083
- },
1084
- });
1085
- var QrcodeVue = vue.defineComponent({
1086
- name: 'Qrcode',
1087
- render: function () {
1088
- var _a = this.$props, renderAs = _a.renderAs, value = _a.value, _size = _a.size, _margin = _a.margin, _level = _a.level, background = _a.background, foreground = _a.foreground;
1089
- var size = _size >>> 0;
1090
- var margin = _margin >>> 0;
1091
- var level = validErrorCorrectLevel(_level) ? _level : defaultErrorCorrectLevel;
1092
- return vue.h(renderAs === 'svg' ? QRCodeSvg : QRCodeCanvas, { value: value, size: size, margin: margin, level: level, background: background, foreground: foreground });
1093
- },
1094
- props: QRCodeVueProps,
1095
- });
1140
+ });
1141
+ }
1142
+ if (showImage) {
1143
+ ctx.drawImage(image, imageProps.x, imageProps.y, imageProps.width, imageProps.height);
1144
+ }
1145
+ };
1146
+ vue.onMounted(generate);
1147
+ vue.onUpdated(generate);
1148
+ var style = ctx.attrs.style;
1149
+ return function () { return vue.h(vue.Fragment, [
1150
+ vue.h('canvas', __assign(__assign({}, ctx.attrs), { ref: canvasEl, style: __assign(__assign({}, style), { width: "".concat(props.size, "px"), height: "".concat(props.size, "px") }) })),
1151
+ props.imageSettings.src && vue.h('img', {
1152
+ ref: imageRef,
1153
+ src: props.imageSettings.src,
1154
+ style: { display: 'none' },
1155
+ onLoad: generate,
1156
+ })
1157
+ ]); };
1158
+ },
1159
+ });
1160
+ var QrcodeVue = vue.defineComponent({
1161
+ name: 'Qrcode',
1162
+ render: function () {
1163
+ var _a = this.$props, renderAs = _a.renderAs, value = _a.value, _size = _a.size, _margin = _a.margin, _level = _a.level, background = _a.background, foreground = _a.foreground, imageSettings = _a.imageSettings;
1164
+ var size = _size >>> 0;
1165
+ var margin = _margin >>> 0;
1166
+ var level = validErrorCorrectLevel(_level) ? _level : defaultErrorCorrectLevel;
1167
+ return vue.h(renderAs === 'svg' ? QrcodeSvg : QrcodeCanvas, { value: value, size: size, margin: margin, level: level, background: background, foreground: foreground, imageSettings: imageSettings });
1168
+ },
1169
+ props: QRCodeVueProps,
1170
+ });
1171
+
1172
+ exports.QrcodeCanvas = QrcodeCanvas;
1173
+ exports.QrcodeSvg = QrcodeSvg;
1174
+ exports.default = QrcodeVue;
1096
1175
 
1097
- return QrcodeVue;
1176
+ Object.defineProperty(exports, '__esModule', { value: true });
1098
1177
 
1099
1178
  }));