crewbus 10.0.11 → 10.0.12

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.
@@ -0,0 +1,2971 @@
1
+ // Self-contained zero-dependency QR code SVG generator
2
+ const modules = {};
3
+ const cache = {};
4
+ function requireMod(from, reqPath) {
5
+ let target = reqPath.replace(/\.js$/, "");
6
+ if (target === "dijkstrajs") { target = "dijkstrajs"; }
7
+ else if (target.startsWith("./") || target.startsWith("../")) {
8
+ const fromDir = from.includes("/") ? from.slice(0, from.lastIndexOf("/")) : "";
9
+ const parts = (fromDir ? fromDir + "/" + target : target).split("/");
10
+ const resolved = [];
11
+ for (const p of parts) {
12
+ if (p === "..") resolved.pop();
13
+ else if (p !== "." && p !== "") resolved.push(p);
14
+ }
15
+ target = resolved.join("/");
16
+ }
17
+ const fullKey = target + ".js";
18
+ if (cache[fullKey]) return cache[fullKey].exports;
19
+ if (!modules[fullKey]) throw new Error("Module not found: " + fullKey + " from " + from);
20
+ const mod = { exports: {} };
21
+ cache[fullKey] = mod;
22
+ modules[fullKey](mod, mod.exports, (p) => requireMod(fullKey, p));
23
+ return mod.exports;
24
+ }
25
+
26
+ modules["browser.js"] = function(module, exports, require) {
27
+
28
+ const canPromise = require('./can-promise')
29
+
30
+ const QRCode = require('./core/qrcode')
31
+ const CanvasRenderer = require('./renderer/canvas')
32
+ const SvgRenderer = require('./renderer/svg-tag.js')
33
+
34
+ function renderCanvas (renderFunc, canvas, text, opts, cb) {
35
+ const args = [].slice.call(arguments, 1)
36
+ const argsNum = args.length
37
+ const isLastArgCb = typeof args[argsNum - 1] === 'function'
38
+
39
+ if (!isLastArgCb && !canPromise()) {
40
+ throw new Error('Callback required as last argument')
41
+ }
42
+
43
+ if (isLastArgCb) {
44
+ if (argsNum < 2) {
45
+ throw new Error('Too few arguments provided')
46
+ }
47
+
48
+ if (argsNum === 2) {
49
+ cb = text
50
+ text = canvas
51
+ canvas = opts = undefined
52
+ } else if (argsNum === 3) {
53
+ if (canvas.getContext && typeof cb === 'undefined') {
54
+ cb = opts
55
+ opts = undefined
56
+ } else {
57
+ cb = opts
58
+ opts = text
59
+ text = canvas
60
+ canvas = undefined
61
+ }
62
+ }
63
+ } else {
64
+ if (argsNum < 1) {
65
+ throw new Error('Too few arguments provided')
66
+ }
67
+
68
+ if (argsNum === 1) {
69
+ text = canvas
70
+ canvas = opts = undefined
71
+ } else if (argsNum === 2 && !canvas.getContext) {
72
+ opts = text
73
+ text = canvas
74
+ canvas = undefined
75
+ }
76
+
77
+ return new Promise(function (resolve, reject) {
78
+ try {
79
+ const data = QRCode.create(text, opts)
80
+ resolve(renderFunc(data, canvas, opts))
81
+ } catch (e) {
82
+ reject(e)
83
+ }
84
+ })
85
+ }
86
+
87
+ try {
88
+ const data = QRCode.create(text, opts)
89
+ cb(null, renderFunc(data, canvas, opts))
90
+ } catch (e) {
91
+ cb(e)
92
+ }
93
+ }
94
+
95
+ exports.create = QRCode.create
96
+ exports.toCanvas = renderCanvas.bind(null, CanvasRenderer.render)
97
+ exports.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL)
98
+
99
+ // only svg for now.
100
+ exports.toString = renderCanvas.bind(null, function (data, _, opts) {
101
+ return SvgRenderer.render(data, opts)
102
+ })
103
+
104
+ };
105
+
106
+ modules["can-promise.js"] = function(module, exports, require) {
107
+ // can-promise has a crash in some versions of react native that dont have
108
+ // standard global objects
109
+ // https://github.com/soldair/node-qrcode/issues/157
110
+
111
+ module.exports = function () {
112
+ return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
113
+ }
114
+
115
+ };
116
+
117
+ modules["core/alignment-pattern.js"] = function(module, exports, require) {
118
+ /**
119
+ * Alignment pattern are fixed reference pattern in defined positions
120
+ * in a matrix symbology, which enables the decode software to re-synchronise
121
+ * the coordinate mapping of the image modules in the event of moderate amounts
122
+ * of distortion of the image.
123
+ *
124
+ * Alignment patterns are present only in QR Code symbols of version 2 or larger
125
+ * and their number depends on the symbol version.
126
+ */
127
+
128
+ const getSymbolSize = require('./utils').getSymbolSize
129
+
130
+ /**
131
+ * Calculate the row/column coordinates of the center module of each alignment pattern
132
+ * for the specified QR Code version.
133
+ *
134
+ * The alignment patterns are positioned symmetrically on either side of the diagonal
135
+ * running from the top left corner of the symbol to the bottom right corner.
136
+ *
137
+ * Since positions are simmetrical only half of the coordinates are returned.
138
+ * Each item of the array will represent in turn the x and y coordinate.
139
+ * @see {@link getPositions}
140
+ *
141
+ * @param {Number} version QR Code version
142
+ * @return {Array} Array of coordinate
143
+ */
144
+ exports.getRowColCoords = function getRowColCoords (version) {
145
+ if (version === 1) return []
146
+
147
+ const posCount = Math.floor(version / 7) + 2
148
+ const size = getSymbolSize(version)
149
+ const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2
150
+ const positions = [size - 7] // Last coord is always (size - 7)
151
+
152
+ for (let i = 1; i < posCount - 1; i++) {
153
+ positions[i] = positions[i - 1] - intervals
154
+ }
155
+
156
+ positions.push(6) // First coord is always 6
157
+
158
+ return positions.reverse()
159
+ }
160
+
161
+ /**
162
+ * Returns an array containing the positions of each alignment pattern.
163
+ * Each array's element represent the center point of the pattern as (x, y) coordinates
164
+ *
165
+ * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
166
+ * and filtering out the items that overlaps with finder pattern
167
+ *
168
+ * @example
169
+ * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
170
+ * The alignment patterns, therefore, are to be centered on (row, column)
171
+ * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
172
+ * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
173
+ * and are not therefore used for alignment patterns.
174
+ *
175
+ * let pos = getPositions(7)
176
+ * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
177
+ *
178
+ * @param {Number} version QR Code version
179
+ * @return {Array} Array of coordinates
180
+ */
181
+ exports.getPositions = function getPositions (version) {
182
+ const coords = []
183
+ const pos = exports.getRowColCoords(version)
184
+ const posLength = pos.length
185
+
186
+ for (let i = 0; i < posLength; i++) {
187
+ for (let j = 0; j < posLength; j++) {
188
+ // Skip if position is occupied by finder patterns
189
+ if ((i === 0 && j === 0) || // top-left
190
+ (i === 0 && j === posLength - 1) || // bottom-left
191
+ (i === posLength - 1 && j === 0)) { // top-right
192
+ continue
193
+ }
194
+
195
+ coords.push([pos[i], pos[j]])
196
+ }
197
+ }
198
+
199
+ return coords
200
+ }
201
+
202
+ };
203
+
204
+ modules["core/alphanumeric-data.js"] = function(module, exports, require) {
205
+ const Mode = require('./mode')
206
+
207
+ /**
208
+ * Array of characters available in alphanumeric mode
209
+ *
210
+ * As per QR Code specification, to each character
211
+ * is assigned a value from 0 to 44 which in this case coincides
212
+ * with the array index
213
+ *
214
+ * @type {Array}
215
+ */
216
+ const ALPHA_NUM_CHARS = [
217
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
218
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
219
+ 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
220
+ ' ', '$', '%', '*', '+', '-', '.', '/', ':'
221
+ ]
222
+
223
+ function AlphanumericData (data) {
224
+ this.mode = Mode.ALPHANUMERIC
225
+ this.data = data
226
+ }
227
+
228
+ AlphanumericData.getBitsLength = function getBitsLength (length) {
229
+ return 11 * Math.floor(length / 2) + 6 * (length % 2)
230
+ }
231
+
232
+ AlphanumericData.prototype.getLength = function getLength () {
233
+ return this.data.length
234
+ }
235
+
236
+ AlphanumericData.prototype.getBitsLength = function getBitsLength () {
237
+ return AlphanumericData.getBitsLength(this.data.length)
238
+ }
239
+
240
+ AlphanumericData.prototype.write = function write (bitBuffer) {
241
+ let i
242
+
243
+ // Input data characters are divided into groups of two characters
244
+ // and encoded as 11-bit binary codes.
245
+ for (i = 0; i + 2 <= this.data.length; i += 2) {
246
+ // The character value of the first character is multiplied by 45
247
+ let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45
248
+
249
+ // The character value of the second digit is added to the product
250
+ value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1])
251
+
252
+ // The sum is then stored as 11-bit binary number
253
+ bitBuffer.put(value, 11)
254
+ }
255
+
256
+ // If the number of input data characters is not a multiple of two,
257
+ // the character value of the final character is encoded as a 6-bit binary number.
258
+ if (this.data.length % 2) {
259
+ bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6)
260
+ }
261
+ }
262
+
263
+ module.exports = AlphanumericData
264
+
265
+ };
266
+
267
+ modules["core/bit-buffer.js"] = function(module, exports, require) {
268
+ function BitBuffer () {
269
+ this.buffer = []
270
+ this.length = 0
271
+ }
272
+
273
+ BitBuffer.prototype = {
274
+
275
+ get: function (index) {
276
+ const bufIndex = Math.floor(index / 8)
277
+ return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
278
+ },
279
+
280
+ put: function (num, length) {
281
+ for (let i = 0; i < length; i++) {
282
+ this.putBit(((num >>> (length - i - 1)) & 1) === 1)
283
+ }
284
+ },
285
+
286
+ getLengthInBits: function () {
287
+ return this.length
288
+ },
289
+
290
+ putBit: function (bit) {
291
+ const bufIndex = Math.floor(this.length / 8)
292
+ if (this.buffer.length <= bufIndex) {
293
+ this.buffer.push(0)
294
+ }
295
+
296
+ if (bit) {
297
+ this.buffer[bufIndex] |= (0x80 >>> (this.length % 8))
298
+ }
299
+
300
+ this.length++
301
+ }
302
+ }
303
+
304
+ module.exports = BitBuffer
305
+
306
+ };
307
+
308
+ modules["core/bit-matrix.js"] = function(module, exports, require) {
309
+ /**
310
+ * Helper class to handle QR Code symbol modules
311
+ *
312
+ * @param {Number} size Symbol size
313
+ */
314
+ function BitMatrix (size) {
315
+ if (!size || size < 1) {
316
+ throw new Error('BitMatrix size must be defined and greater than 0')
317
+ }
318
+
319
+ this.size = size
320
+ this.data = new Uint8Array(size * size)
321
+ this.reservedBit = new Uint8Array(size * size)
322
+ }
323
+
324
+ /**
325
+ * Set bit value at specified location
326
+ * If reserved flag is set, this bit will be ignored during masking process
327
+ *
328
+ * @param {Number} row
329
+ * @param {Number} col
330
+ * @param {Boolean} value
331
+ * @param {Boolean} reserved
332
+ */
333
+ BitMatrix.prototype.set = function (row, col, value, reserved) {
334
+ const index = row * this.size + col
335
+ this.data[index] = value
336
+ if (reserved) this.reservedBit[index] = true
337
+ }
338
+
339
+ /**
340
+ * Returns bit value at specified location
341
+ *
342
+ * @param {Number} row
343
+ * @param {Number} col
344
+ * @return {Boolean}
345
+ */
346
+ BitMatrix.prototype.get = function (row, col) {
347
+ return this.data[row * this.size + col]
348
+ }
349
+
350
+ /**
351
+ * Applies xor operator at specified location
352
+ * (used during masking process)
353
+ *
354
+ * @param {Number} row
355
+ * @param {Number} col
356
+ * @param {Boolean} value
357
+ */
358
+ BitMatrix.prototype.xor = function (row, col, value) {
359
+ this.data[row * this.size + col] ^= value
360
+ }
361
+
362
+ /**
363
+ * Check if bit at specified location is reserved
364
+ *
365
+ * @param {Number} row
366
+ * @param {Number} col
367
+ * @return {Boolean}
368
+ */
369
+ BitMatrix.prototype.isReserved = function (row, col) {
370
+ return this.reservedBit[row * this.size + col]
371
+ }
372
+
373
+ module.exports = BitMatrix
374
+
375
+ };
376
+
377
+ modules["core/byte-data.js"] = function(module, exports, require) {
378
+ const Mode = require('./mode')
379
+
380
+ function ByteData (data) {
381
+ this.mode = Mode.BYTE
382
+ if (typeof (data) === 'string') {
383
+ this.data = new TextEncoder().encode(data)
384
+ } else {
385
+ this.data = new Uint8Array(data)
386
+ }
387
+ }
388
+
389
+ ByteData.getBitsLength = function getBitsLength (length) {
390
+ return length * 8
391
+ }
392
+
393
+ ByteData.prototype.getLength = function getLength () {
394
+ return this.data.length
395
+ }
396
+
397
+ ByteData.prototype.getBitsLength = function getBitsLength () {
398
+ return ByteData.getBitsLength(this.data.length)
399
+ }
400
+
401
+ ByteData.prototype.write = function (bitBuffer) {
402
+ for (let i = 0, l = this.data.length; i < l; i++) {
403
+ bitBuffer.put(this.data[i], 8)
404
+ }
405
+ }
406
+
407
+ module.exports = ByteData
408
+
409
+ };
410
+
411
+ modules["core/error-correction-code.js"] = function(module, exports, require) {
412
+ const ECLevel = require('./error-correction-level')
413
+
414
+ const EC_BLOCKS_TABLE = [
415
+ // L M Q H
416
+ 1, 1, 1, 1,
417
+ 1, 1, 1, 1,
418
+ 1, 1, 2, 2,
419
+ 1, 2, 2, 4,
420
+ 1, 2, 4, 4,
421
+ 2, 4, 4, 4,
422
+ 2, 4, 6, 5,
423
+ 2, 4, 6, 6,
424
+ 2, 5, 8, 8,
425
+ 4, 5, 8, 8,
426
+ 4, 5, 8, 11,
427
+ 4, 8, 10, 11,
428
+ 4, 9, 12, 16,
429
+ 4, 9, 16, 16,
430
+ 6, 10, 12, 18,
431
+ 6, 10, 17, 16,
432
+ 6, 11, 16, 19,
433
+ 6, 13, 18, 21,
434
+ 7, 14, 21, 25,
435
+ 8, 16, 20, 25,
436
+ 8, 17, 23, 25,
437
+ 9, 17, 23, 34,
438
+ 9, 18, 25, 30,
439
+ 10, 20, 27, 32,
440
+ 12, 21, 29, 35,
441
+ 12, 23, 34, 37,
442
+ 12, 25, 34, 40,
443
+ 13, 26, 35, 42,
444
+ 14, 28, 38, 45,
445
+ 15, 29, 40, 48,
446
+ 16, 31, 43, 51,
447
+ 17, 33, 45, 54,
448
+ 18, 35, 48, 57,
449
+ 19, 37, 51, 60,
450
+ 19, 38, 53, 63,
451
+ 20, 40, 56, 66,
452
+ 21, 43, 59, 70,
453
+ 22, 45, 62, 74,
454
+ 24, 47, 65, 77,
455
+ 25, 49, 68, 81
456
+ ]
457
+
458
+ const EC_CODEWORDS_TABLE = [
459
+ // L M Q H
460
+ 7, 10, 13, 17,
461
+ 10, 16, 22, 28,
462
+ 15, 26, 36, 44,
463
+ 20, 36, 52, 64,
464
+ 26, 48, 72, 88,
465
+ 36, 64, 96, 112,
466
+ 40, 72, 108, 130,
467
+ 48, 88, 132, 156,
468
+ 60, 110, 160, 192,
469
+ 72, 130, 192, 224,
470
+ 80, 150, 224, 264,
471
+ 96, 176, 260, 308,
472
+ 104, 198, 288, 352,
473
+ 120, 216, 320, 384,
474
+ 132, 240, 360, 432,
475
+ 144, 280, 408, 480,
476
+ 168, 308, 448, 532,
477
+ 180, 338, 504, 588,
478
+ 196, 364, 546, 650,
479
+ 224, 416, 600, 700,
480
+ 224, 442, 644, 750,
481
+ 252, 476, 690, 816,
482
+ 270, 504, 750, 900,
483
+ 300, 560, 810, 960,
484
+ 312, 588, 870, 1050,
485
+ 336, 644, 952, 1110,
486
+ 360, 700, 1020, 1200,
487
+ 390, 728, 1050, 1260,
488
+ 420, 784, 1140, 1350,
489
+ 450, 812, 1200, 1440,
490
+ 480, 868, 1290, 1530,
491
+ 510, 924, 1350, 1620,
492
+ 540, 980, 1440, 1710,
493
+ 570, 1036, 1530, 1800,
494
+ 570, 1064, 1590, 1890,
495
+ 600, 1120, 1680, 1980,
496
+ 630, 1204, 1770, 2100,
497
+ 660, 1260, 1860, 2220,
498
+ 720, 1316, 1950, 2310,
499
+ 750, 1372, 2040, 2430
500
+ ]
501
+
502
+ /**
503
+ * Returns the number of error correction block that the QR Code should contain
504
+ * for the specified version and error correction level.
505
+ *
506
+ * @param {Number} version QR Code version
507
+ * @param {Number} errorCorrectionLevel Error correction level
508
+ * @return {Number} Number of error correction blocks
509
+ */
510
+ exports.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {
511
+ switch (errorCorrectionLevel) {
512
+ case ECLevel.L:
513
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]
514
+ case ECLevel.M:
515
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]
516
+ case ECLevel.Q:
517
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]
518
+ case ECLevel.H:
519
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]
520
+ default:
521
+ return undefined
522
+ }
523
+ }
524
+
525
+ /**
526
+ * Returns the number of error correction codewords to use for the specified
527
+ * version and error correction level.
528
+ *
529
+ * @param {Number} version QR Code version
530
+ * @param {Number} errorCorrectionLevel Error correction level
531
+ * @return {Number} Number of error correction codewords
532
+ */
533
+ exports.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {
534
+ switch (errorCorrectionLevel) {
535
+ case ECLevel.L:
536
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]
537
+ case ECLevel.M:
538
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]
539
+ case ECLevel.Q:
540
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]
541
+ case ECLevel.H:
542
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]
543
+ default:
544
+ return undefined
545
+ }
546
+ }
547
+
548
+ };
549
+
550
+ modules["core/error-correction-level.js"] = function(module, exports, require) {
551
+ exports.L = { bit: 1 }
552
+ exports.M = { bit: 0 }
553
+ exports.Q = { bit: 3 }
554
+ exports.H = { bit: 2 }
555
+
556
+ function fromString (string) {
557
+ if (typeof string !== 'string') {
558
+ throw new Error('Param is not a string')
559
+ }
560
+
561
+ const lcStr = string.toLowerCase()
562
+
563
+ switch (lcStr) {
564
+ case 'l':
565
+ case 'low':
566
+ return exports.L
567
+
568
+ case 'm':
569
+ case 'medium':
570
+ return exports.M
571
+
572
+ case 'q':
573
+ case 'quartile':
574
+ return exports.Q
575
+
576
+ case 'h':
577
+ case 'high':
578
+ return exports.H
579
+
580
+ default:
581
+ throw new Error('Unknown EC Level: ' + string)
582
+ }
583
+ }
584
+
585
+ exports.isValid = function isValid (level) {
586
+ return level && typeof level.bit !== 'undefined' &&
587
+ level.bit >= 0 && level.bit < 4
588
+ }
589
+
590
+ exports.from = function from (value, defaultValue) {
591
+ if (exports.isValid(value)) {
592
+ return value
593
+ }
594
+
595
+ try {
596
+ return fromString(value)
597
+ } catch (e) {
598
+ return defaultValue
599
+ }
600
+ }
601
+
602
+ };
603
+
604
+ modules["core/finder-pattern.js"] = function(module, exports, require) {
605
+ const getSymbolSize = require('./utils').getSymbolSize
606
+ const FINDER_PATTERN_SIZE = 7
607
+
608
+ /**
609
+ * Returns an array containing the positions of each finder pattern.
610
+ * Each array's element represent the top-left point of the pattern as (x, y) coordinates
611
+ *
612
+ * @param {Number} version QR Code version
613
+ * @return {Array} Array of coordinates
614
+ */
615
+ exports.getPositions = function getPositions (version) {
616
+ const size = getSymbolSize(version)
617
+
618
+ return [
619
+ // top-left
620
+ [0, 0],
621
+ // top-right
622
+ [size - FINDER_PATTERN_SIZE, 0],
623
+ // bottom-left
624
+ [0, size - FINDER_PATTERN_SIZE]
625
+ ]
626
+ }
627
+
628
+ };
629
+
630
+ modules["core/format-info.js"] = function(module, exports, require) {
631
+ const Utils = require('./utils')
632
+
633
+ const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0)
634
+ const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1)
635
+ const G15_BCH = Utils.getBCHDigit(G15)
636
+
637
+ /**
638
+ * Returns format information with relative error correction bits
639
+ *
640
+ * The format information is a 15-bit sequence containing 5 data bits,
641
+ * with 10 error correction bits calculated using the (15, 5) BCH code.
642
+ *
643
+ * @param {Number} errorCorrectionLevel Error correction level
644
+ * @param {Number} mask Mask pattern
645
+ * @return {Number} Encoded format information bits
646
+ */
647
+ exports.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
648
+ const data = ((errorCorrectionLevel.bit << 3) | mask)
649
+ let d = data << 10
650
+
651
+ while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
652
+ d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH))
653
+ }
654
+
655
+ // xor final data with mask pattern in order to ensure that
656
+ // no combination of Error Correction Level and data mask pattern
657
+ // will result in an all-zero data string
658
+ return ((data << 10) | d) ^ G15_MASK
659
+ }
660
+
661
+ };
662
+
663
+ modules["core/galois-field.js"] = function(module, exports, require) {
664
+ const EXP_TABLE = new Uint8Array(512)
665
+ const LOG_TABLE = new Uint8Array(256)
666
+ /**
667
+ * Precompute the log and anti-log tables for faster computation later
668
+ *
669
+ * For each possible value in the galois field 2^8, we will pre-compute
670
+ * the logarithm and anti-logarithm (exponential) of this value
671
+ *
672
+ * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
673
+ */
674
+ ;(function initTables () {
675
+ let x = 1
676
+ for (let i = 0; i < 255; i++) {
677
+ EXP_TABLE[i] = x
678
+ LOG_TABLE[x] = i
679
+
680
+ x <<= 1 // multiply by 2
681
+
682
+ // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
683
+ // This means that when a number is 256 or larger, it should be XORed with 0x11D.
684
+ if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
685
+ x ^= 0x11D
686
+ }
687
+ }
688
+
689
+ // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
690
+ // stay inside the bounds (because we will mainly use this table for the multiplication of
691
+ // two GF numbers, no more).
692
+ // @see {@link mul}
693
+ for (let i = 255; i < 512; i++) {
694
+ EXP_TABLE[i] = EXP_TABLE[i - 255]
695
+ }
696
+ }())
697
+
698
+ /**
699
+ * Returns log value of n inside Galois Field
700
+ *
701
+ * @param {Number} n
702
+ * @return {Number}
703
+ */
704
+ exports.log = function log (n) {
705
+ if (n < 1) throw new Error('log(' + n + ')')
706
+ return LOG_TABLE[n]
707
+ }
708
+
709
+ /**
710
+ * Returns anti-log value of n inside Galois Field
711
+ *
712
+ * @param {Number} n
713
+ * @return {Number}
714
+ */
715
+ exports.exp = function exp (n) {
716
+ return EXP_TABLE[n]
717
+ }
718
+
719
+ /**
720
+ * Multiplies two number inside Galois Field
721
+ *
722
+ * @param {Number} x
723
+ * @param {Number} y
724
+ * @return {Number}
725
+ */
726
+ exports.mul = function mul (x, y) {
727
+ if (x === 0 || y === 0) return 0
728
+
729
+ // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
730
+ // @see {@link initTables}
731
+ return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
732
+ }
733
+
734
+ };
735
+
736
+ modules["core/kanji-data.js"] = function(module, exports, require) {
737
+ const Mode = require('./mode')
738
+ const Utils = require('./utils')
739
+
740
+ function KanjiData (data) {
741
+ this.mode = Mode.KANJI
742
+ this.data = data
743
+ }
744
+
745
+ KanjiData.getBitsLength = function getBitsLength (length) {
746
+ return length * 13
747
+ }
748
+
749
+ KanjiData.prototype.getLength = function getLength () {
750
+ return this.data.length
751
+ }
752
+
753
+ KanjiData.prototype.getBitsLength = function getBitsLength () {
754
+ return KanjiData.getBitsLength(this.data.length)
755
+ }
756
+
757
+ KanjiData.prototype.write = function (bitBuffer) {
758
+ let i
759
+
760
+ // In the Shift JIS system, Kanji characters are represented by a two byte combination.
761
+ // These byte values are shifted from the JIS X 0208 values.
762
+ // JIS X 0208 gives details of the shift coded representation.
763
+ for (i = 0; i < this.data.length; i++) {
764
+ let value = Utils.toSJIS(this.data[i])
765
+
766
+ // For characters with Shift JIS values from 0x8140 to 0x9FFC:
767
+ if (value >= 0x8140 && value <= 0x9FFC) {
768
+ // Subtract 0x8140 from Shift JIS value
769
+ value -= 0x8140
770
+
771
+ // For characters with Shift JIS values from 0xE040 to 0xEBBF
772
+ } else if (value >= 0xE040 && value <= 0xEBBF) {
773
+ // Subtract 0xC140 from Shift JIS value
774
+ value -= 0xC140
775
+ } else {
776
+ throw new Error(
777
+ 'Invalid SJIS character: ' + this.data[i] + '\n' +
778
+ 'Make sure your charset is UTF-8')
779
+ }
780
+
781
+ // Multiply most significant byte of result by 0xC0
782
+ // and add least significant byte to product
783
+ value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff)
784
+
785
+ // Convert result to a 13-bit binary string
786
+ bitBuffer.put(value, 13)
787
+ }
788
+ }
789
+
790
+ module.exports = KanjiData
791
+
792
+ };
793
+
794
+ modules["core/mask-pattern.js"] = function(module, exports, require) {
795
+ /**
796
+ * Data mask pattern reference
797
+ * @type {Object}
798
+ */
799
+ exports.Patterns = {
800
+ PATTERN000: 0,
801
+ PATTERN001: 1,
802
+ PATTERN010: 2,
803
+ PATTERN011: 3,
804
+ PATTERN100: 4,
805
+ PATTERN101: 5,
806
+ PATTERN110: 6,
807
+ PATTERN111: 7
808
+ }
809
+
810
+ /**
811
+ * Weighted penalty scores for the undesirable features
812
+ * @type {Object}
813
+ */
814
+ const PenaltyScores = {
815
+ N1: 3,
816
+ N2: 3,
817
+ N3: 40,
818
+ N4: 10
819
+ }
820
+
821
+ /**
822
+ * Check if mask pattern value is valid
823
+ *
824
+ * @param {Number} mask Mask pattern
825
+ * @return {Boolean} true if valid, false otherwise
826
+ */
827
+ exports.isValid = function isValid (mask) {
828
+ return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
829
+ }
830
+
831
+ /**
832
+ * Returns mask pattern from a value.
833
+ * If value is not valid, returns undefined
834
+ *
835
+ * @param {Number|String} value Mask pattern value
836
+ * @return {Number} Valid mask pattern or undefined
837
+ */
838
+ exports.from = function from (value) {
839
+ return exports.isValid(value) ? parseInt(value, 10) : undefined
840
+ }
841
+
842
+ /**
843
+ * Find adjacent modules in row/column with the same color
844
+ * and assign a penalty value.
845
+ *
846
+ * Points: N1 + i
847
+ * i is the amount by which the number of adjacent modules of the same color exceeds 5
848
+ */
849
+ exports.getPenaltyN1 = function getPenaltyN1 (data) {
850
+ const size = data.size
851
+ let points = 0
852
+ let sameCountCol = 0
853
+ let sameCountRow = 0
854
+ let lastCol = null
855
+ let lastRow = null
856
+
857
+ for (let row = 0; row < size; row++) {
858
+ sameCountCol = sameCountRow = 0
859
+ lastCol = lastRow = null
860
+
861
+ for (let col = 0; col < size; col++) {
862
+ let module = data.get(row, col)
863
+ if (module === lastCol) {
864
+ sameCountCol++
865
+ } else {
866
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)
867
+ lastCol = module
868
+ sameCountCol = 1
869
+ }
870
+
871
+ module = data.get(col, row)
872
+ if (module === lastRow) {
873
+ sameCountRow++
874
+ } else {
875
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)
876
+ lastRow = module
877
+ sameCountRow = 1
878
+ }
879
+ }
880
+
881
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5)
882
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5)
883
+ }
884
+
885
+ return points
886
+ }
887
+
888
+ /**
889
+ * Find 2x2 blocks with the same color and assign a penalty value
890
+ *
891
+ * Points: N2 * (m - 1) * (n - 1)
892
+ */
893
+ exports.getPenaltyN2 = function getPenaltyN2 (data) {
894
+ const size = data.size
895
+ let points = 0
896
+
897
+ for (let row = 0; row < size - 1; row++) {
898
+ for (let col = 0; col < size - 1; col++) {
899
+ const last = data.get(row, col) +
900
+ data.get(row, col + 1) +
901
+ data.get(row + 1, col) +
902
+ data.get(row + 1, col + 1)
903
+
904
+ if (last === 4 || last === 0) points++
905
+ }
906
+ }
907
+
908
+ return points * PenaltyScores.N2
909
+ }
910
+
911
+ /**
912
+ * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
913
+ * preceded or followed by light area 4 modules wide
914
+ *
915
+ * Points: N3 * number of pattern found
916
+ */
917
+ exports.getPenaltyN3 = function getPenaltyN3 (data) {
918
+ const size = data.size
919
+ let points = 0
920
+ let bitsCol = 0
921
+ let bitsRow = 0
922
+
923
+ for (let row = 0; row < size; row++) {
924
+ bitsCol = bitsRow = 0
925
+ for (let col = 0; col < size; col++) {
926
+ bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col)
927
+ if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++
928
+
929
+ bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row)
930
+ if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++
931
+ }
932
+ }
933
+
934
+ return points * PenaltyScores.N3
935
+ }
936
+
937
+ /**
938
+ * Calculate proportion of dark modules in entire symbol
939
+ *
940
+ * Points: N4 * k
941
+ *
942
+ * k is the rating of the deviation of the proportion of dark modules
943
+ * in the symbol from 50% in steps of 5%
944
+ */
945
+ exports.getPenaltyN4 = function getPenaltyN4 (data) {
946
+ let darkCount = 0
947
+ const modulesCount = data.data.length
948
+
949
+ for (let i = 0; i < modulesCount; i++) darkCount += data.data[i]
950
+
951
+ const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10)
952
+
953
+ return k * PenaltyScores.N4
954
+ }
955
+
956
+ /**
957
+ * Return mask value at given position
958
+ *
959
+ * @param {Number} maskPattern Pattern reference value
960
+ * @param {Number} i Row
961
+ * @param {Number} j Column
962
+ * @return {Boolean} Mask value
963
+ */
964
+ function getMaskAt (maskPattern, i, j) {
965
+ switch (maskPattern) {
966
+ case exports.Patterns.PATTERN000: return (i + j) % 2 === 0
967
+ case exports.Patterns.PATTERN001: return i % 2 === 0
968
+ case exports.Patterns.PATTERN010: return j % 3 === 0
969
+ case exports.Patterns.PATTERN011: return (i + j) % 3 === 0
970
+ case exports.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
971
+ case exports.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
972
+ case exports.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
973
+ case exports.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
974
+
975
+ default: throw new Error('bad maskPattern:' + maskPattern)
976
+ }
977
+ }
978
+
979
+ /**
980
+ * Apply a mask pattern to a BitMatrix
981
+ *
982
+ * @param {Number} pattern Pattern reference number
983
+ * @param {BitMatrix} data BitMatrix data
984
+ */
985
+ exports.applyMask = function applyMask (pattern, data) {
986
+ const size = data.size
987
+
988
+ for (let col = 0; col < size; col++) {
989
+ for (let row = 0; row < size; row++) {
990
+ if (data.isReserved(row, col)) continue
991
+ data.xor(row, col, getMaskAt(pattern, row, col))
992
+ }
993
+ }
994
+ }
995
+
996
+ /**
997
+ * Returns the best mask pattern for data
998
+ *
999
+ * @param {BitMatrix} data
1000
+ * @return {Number} Mask pattern reference number
1001
+ */
1002
+ exports.getBestMask = function getBestMask (data, setupFormatFunc) {
1003
+ const numPatterns = Object.keys(exports.Patterns).length
1004
+ let bestPattern = 0
1005
+ let lowerPenalty = Infinity
1006
+
1007
+ for (let p = 0; p < numPatterns; p++) {
1008
+ setupFormatFunc(p)
1009
+ exports.applyMask(p, data)
1010
+
1011
+ // Calculate penalty
1012
+ const penalty =
1013
+ exports.getPenaltyN1(data) +
1014
+ exports.getPenaltyN2(data) +
1015
+ exports.getPenaltyN3(data) +
1016
+ exports.getPenaltyN4(data)
1017
+
1018
+ // Undo previously applied mask
1019
+ exports.applyMask(p, data)
1020
+
1021
+ if (penalty < lowerPenalty) {
1022
+ lowerPenalty = penalty
1023
+ bestPattern = p
1024
+ }
1025
+ }
1026
+
1027
+ return bestPattern
1028
+ }
1029
+
1030
+ };
1031
+
1032
+ modules["core/mode.js"] = function(module, exports, require) {
1033
+ const VersionCheck = require('./version-check')
1034
+ const Regex = require('./regex')
1035
+
1036
+ /**
1037
+ * Numeric mode encodes data from the decimal digit set (0 - 9)
1038
+ * (byte values 30HEX to 39HEX).
1039
+ * Normally, 3 data characters are represented by 10 bits.
1040
+ *
1041
+ * @type {Object}
1042
+ */
1043
+ exports.NUMERIC = {
1044
+ id: 'Numeric',
1045
+ bit: 1 << 0,
1046
+ ccBits: [10, 12, 14]
1047
+ }
1048
+
1049
+ /**
1050
+ * Alphanumeric mode encodes data from a set of 45 characters,
1051
+ * i.e. 10 numeric digits (0 - 9),
1052
+ * 26 alphabetic characters (A - Z),
1053
+ * and 9 symbols (SP, $, %, *, +, -, ., /, :).
1054
+ * Normally, two input characters are represented by 11 bits.
1055
+ *
1056
+ * @type {Object}
1057
+ */
1058
+ exports.ALPHANUMERIC = {
1059
+ id: 'Alphanumeric',
1060
+ bit: 1 << 1,
1061
+ ccBits: [9, 11, 13]
1062
+ }
1063
+
1064
+ /**
1065
+ * In byte mode, data is encoded at 8 bits per character.
1066
+ *
1067
+ * @type {Object}
1068
+ */
1069
+ exports.BYTE = {
1070
+ id: 'Byte',
1071
+ bit: 1 << 2,
1072
+ ccBits: [8, 16, 16]
1073
+ }
1074
+
1075
+ /**
1076
+ * The Kanji mode efficiently encodes Kanji characters in accordance with
1077
+ * the Shift JIS system based on JIS X 0208.
1078
+ * The Shift JIS values are shifted from the JIS X 0208 values.
1079
+ * JIS X 0208 gives details of the shift coded representation.
1080
+ * Each two-byte character value is compacted to a 13-bit binary codeword.
1081
+ *
1082
+ * @type {Object}
1083
+ */
1084
+ exports.KANJI = {
1085
+ id: 'Kanji',
1086
+ bit: 1 << 3,
1087
+ ccBits: [8, 10, 12]
1088
+ }
1089
+
1090
+ /**
1091
+ * Mixed mode will contain a sequences of data in a combination of any of
1092
+ * the modes described above
1093
+ *
1094
+ * @type {Object}
1095
+ */
1096
+ exports.MIXED = {
1097
+ bit: -1
1098
+ }
1099
+
1100
+ /**
1101
+ * Returns the number of bits needed to store the data length
1102
+ * according to QR Code specifications.
1103
+ *
1104
+ * @param {Mode} mode Data mode
1105
+ * @param {Number} version QR Code version
1106
+ * @return {Number} Number of bits
1107
+ */
1108
+ exports.getCharCountIndicator = function getCharCountIndicator (mode, version) {
1109
+ if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
1110
+
1111
+ if (!VersionCheck.isValid(version)) {
1112
+ throw new Error('Invalid version: ' + version)
1113
+ }
1114
+
1115
+ if (version >= 1 && version < 10) return mode.ccBits[0]
1116
+ else if (version < 27) return mode.ccBits[1]
1117
+ return mode.ccBits[2]
1118
+ }
1119
+
1120
+ /**
1121
+ * Returns the most efficient mode to store the specified data
1122
+ *
1123
+ * @param {String} dataStr Input data string
1124
+ * @return {Mode} Best mode
1125
+ */
1126
+ exports.getBestModeForData = function getBestModeForData (dataStr) {
1127
+ if (Regex.testNumeric(dataStr)) return exports.NUMERIC
1128
+ else if (Regex.testAlphanumeric(dataStr)) return exports.ALPHANUMERIC
1129
+ else if (Regex.testKanji(dataStr)) return exports.KANJI
1130
+ else return exports.BYTE
1131
+ }
1132
+
1133
+ /**
1134
+ * Return mode name as string
1135
+ *
1136
+ * @param {Mode} mode Mode object
1137
+ * @returns {String} Mode name
1138
+ */
1139
+ exports.toString = function toString (mode) {
1140
+ if (mode && mode.id) return mode.id
1141
+ throw new Error('Invalid mode')
1142
+ }
1143
+
1144
+ /**
1145
+ * Check if input param is a valid mode object
1146
+ *
1147
+ * @param {Mode} mode Mode object
1148
+ * @returns {Boolean} True if valid mode, false otherwise
1149
+ */
1150
+ exports.isValid = function isValid (mode) {
1151
+ return mode && mode.bit && mode.ccBits
1152
+ }
1153
+
1154
+ /**
1155
+ * Get mode object from its name
1156
+ *
1157
+ * @param {String} string Mode name
1158
+ * @returns {Mode} Mode object
1159
+ */
1160
+ function fromString (string) {
1161
+ if (typeof string !== 'string') {
1162
+ throw new Error('Param is not a string')
1163
+ }
1164
+
1165
+ const lcStr = string.toLowerCase()
1166
+
1167
+ switch (lcStr) {
1168
+ case 'numeric':
1169
+ return exports.NUMERIC
1170
+ case 'alphanumeric':
1171
+ return exports.ALPHANUMERIC
1172
+ case 'kanji':
1173
+ return exports.KANJI
1174
+ case 'byte':
1175
+ return exports.BYTE
1176
+ default:
1177
+ throw new Error('Unknown mode: ' + string)
1178
+ }
1179
+ }
1180
+
1181
+ /**
1182
+ * Returns mode from a value.
1183
+ * If value is not a valid mode, returns defaultValue
1184
+ *
1185
+ * @param {Mode|String} value Encoding mode
1186
+ * @param {Mode} defaultValue Fallback value
1187
+ * @return {Mode} Encoding mode
1188
+ */
1189
+ exports.from = function from (value, defaultValue) {
1190
+ if (exports.isValid(value)) {
1191
+ return value
1192
+ }
1193
+
1194
+ try {
1195
+ return fromString(value)
1196
+ } catch (e) {
1197
+ return defaultValue
1198
+ }
1199
+ }
1200
+
1201
+ };
1202
+
1203
+ modules["core/numeric-data.js"] = function(module, exports, require) {
1204
+ const Mode = require('./mode')
1205
+
1206
+ function NumericData (data) {
1207
+ this.mode = Mode.NUMERIC
1208
+ this.data = data.toString()
1209
+ }
1210
+
1211
+ NumericData.getBitsLength = function getBitsLength (length) {
1212
+ return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
1213
+ }
1214
+
1215
+ NumericData.prototype.getLength = function getLength () {
1216
+ return this.data.length
1217
+ }
1218
+
1219
+ NumericData.prototype.getBitsLength = function getBitsLength () {
1220
+ return NumericData.getBitsLength(this.data.length)
1221
+ }
1222
+
1223
+ NumericData.prototype.write = function write (bitBuffer) {
1224
+ let i, group, value
1225
+
1226
+ // The input data string is divided into groups of three digits,
1227
+ // and each group is converted to its 10-bit binary equivalent.
1228
+ for (i = 0; i + 3 <= this.data.length; i += 3) {
1229
+ group = this.data.substr(i, 3)
1230
+ value = parseInt(group, 10)
1231
+
1232
+ bitBuffer.put(value, 10)
1233
+ }
1234
+
1235
+ // If the number of input digits is not an exact multiple of three,
1236
+ // the final one or two digits are converted to 4 or 7 bits respectively.
1237
+ const remainingNum = this.data.length - i
1238
+ if (remainingNum > 0) {
1239
+ group = this.data.substr(i)
1240
+ value = parseInt(group, 10)
1241
+
1242
+ bitBuffer.put(value, remainingNum * 3 + 1)
1243
+ }
1244
+ }
1245
+
1246
+ module.exports = NumericData
1247
+
1248
+ };
1249
+
1250
+ modules["core/polynomial.js"] = function(module, exports, require) {
1251
+ const GF = require('./galois-field')
1252
+
1253
+ /**
1254
+ * Multiplies two polynomials inside Galois Field
1255
+ *
1256
+ * @param {Uint8Array} p1 Polynomial
1257
+ * @param {Uint8Array} p2 Polynomial
1258
+ * @return {Uint8Array} Product of p1 and p2
1259
+ */
1260
+ exports.mul = function mul (p1, p2) {
1261
+ const coeff = new Uint8Array(p1.length + p2.length - 1)
1262
+
1263
+ for (let i = 0; i < p1.length; i++) {
1264
+ for (let j = 0; j < p2.length; j++) {
1265
+ coeff[i + j] ^= GF.mul(p1[i], p2[j])
1266
+ }
1267
+ }
1268
+
1269
+ return coeff
1270
+ }
1271
+
1272
+ /**
1273
+ * Calculate the remainder of polynomials division
1274
+ *
1275
+ * @param {Uint8Array} divident Polynomial
1276
+ * @param {Uint8Array} divisor Polynomial
1277
+ * @return {Uint8Array} Remainder
1278
+ */
1279
+ exports.mod = function mod (divident, divisor) {
1280
+ let result = new Uint8Array(divident)
1281
+
1282
+ while ((result.length - divisor.length) >= 0) {
1283
+ const coeff = result[0]
1284
+
1285
+ for (let i = 0; i < divisor.length; i++) {
1286
+ result[i] ^= GF.mul(divisor[i], coeff)
1287
+ }
1288
+
1289
+ // remove all zeros from buffer head
1290
+ let offset = 0
1291
+ while (offset < result.length && result[offset] === 0) offset++
1292
+ result = result.slice(offset)
1293
+ }
1294
+
1295
+ return result
1296
+ }
1297
+
1298
+ /**
1299
+ * Generate an irreducible generator polynomial of specified degree
1300
+ * (used by Reed-Solomon encoder)
1301
+ *
1302
+ * @param {Number} degree Degree of the generator polynomial
1303
+ * @return {Uint8Array} Buffer containing polynomial coefficients
1304
+ */
1305
+ exports.generateECPolynomial = function generateECPolynomial (degree) {
1306
+ let poly = new Uint8Array([1])
1307
+ for (let i = 0; i < degree; i++) {
1308
+ poly = exports.mul(poly, new Uint8Array([1, GF.exp(i)]))
1309
+ }
1310
+
1311
+ return poly
1312
+ }
1313
+
1314
+ };
1315
+
1316
+ modules["core/qrcode.js"] = function(module, exports, require) {
1317
+ const Utils = require('./utils')
1318
+ const ECLevel = require('./error-correction-level')
1319
+ const BitBuffer = require('./bit-buffer')
1320
+ const BitMatrix = require('./bit-matrix')
1321
+ const AlignmentPattern = require('./alignment-pattern')
1322
+ const FinderPattern = require('./finder-pattern')
1323
+ const MaskPattern = require('./mask-pattern')
1324
+ const ECCode = require('./error-correction-code')
1325
+ const ReedSolomonEncoder = require('./reed-solomon-encoder')
1326
+ const Version = require('./version')
1327
+ const FormatInfo = require('./format-info')
1328
+ const Mode = require('./mode')
1329
+ const Segments = require('./segments')
1330
+
1331
+ /**
1332
+ * QRCode for JavaScript
1333
+ *
1334
+ * modified by Ryan Day for nodejs support
1335
+ * Copyright (c) 2011 Ryan Day
1336
+ *
1337
+ * Licensed under the MIT license:
1338
+ * http://www.opensource.org/licenses/mit-license.php
1339
+ *
1340
+ //---------------------------------------------------------------------
1341
+ // QRCode for JavaScript
1342
+ //
1343
+ // Copyright (c) 2009 Kazuhiko Arase
1344
+ //
1345
+ // URL: http://www.d-project.com/
1346
+ //
1347
+ // Licensed under the MIT license:
1348
+ // http://www.opensource.org/licenses/mit-license.php
1349
+ //
1350
+ // The word "QR Code" is registered trademark of
1351
+ // DENSO WAVE INCORPORATED
1352
+ // http://www.denso-wave.com/qrcode/faqpatent-e.html
1353
+ //
1354
+ //---------------------------------------------------------------------
1355
+ */
1356
+
1357
+ /**
1358
+ * Add finder patterns bits to matrix
1359
+ *
1360
+ * @param {BitMatrix} matrix Modules matrix
1361
+ * @param {Number} version QR Code version
1362
+ */
1363
+ function setupFinderPattern (matrix, version) {
1364
+ const size = matrix.size
1365
+ const pos = FinderPattern.getPositions(version)
1366
+
1367
+ for (let i = 0; i < pos.length; i++) {
1368
+ const row = pos[i][0]
1369
+ const col = pos[i][1]
1370
+
1371
+ for (let r = -1; r <= 7; r++) {
1372
+ if (row + r <= -1 || size <= row + r) continue
1373
+
1374
+ for (let c = -1; c <= 7; c++) {
1375
+ if (col + c <= -1 || size <= col + c) continue
1376
+
1377
+ if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
1378
+ (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
1379
+ (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
1380
+ matrix.set(row + r, col + c, true, true)
1381
+ } else {
1382
+ matrix.set(row + r, col + c, false, true)
1383
+ }
1384
+ }
1385
+ }
1386
+ }
1387
+ }
1388
+
1389
+ /**
1390
+ * Add timing pattern bits to matrix
1391
+ *
1392
+ * Note: this function must be called before {@link setupAlignmentPattern}
1393
+ *
1394
+ * @param {BitMatrix} matrix Modules matrix
1395
+ */
1396
+ function setupTimingPattern (matrix) {
1397
+ const size = matrix.size
1398
+
1399
+ for (let r = 8; r < size - 8; r++) {
1400
+ const value = r % 2 === 0
1401
+ matrix.set(r, 6, value, true)
1402
+ matrix.set(6, r, value, true)
1403
+ }
1404
+ }
1405
+
1406
+ /**
1407
+ * Add alignment patterns bits to matrix
1408
+ *
1409
+ * Note: this function must be called after {@link setupTimingPattern}
1410
+ *
1411
+ * @param {BitMatrix} matrix Modules matrix
1412
+ * @param {Number} version QR Code version
1413
+ */
1414
+ function setupAlignmentPattern (matrix, version) {
1415
+ const pos = AlignmentPattern.getPositions(version)
1416
+
1417
+ for (let i = 0; i < pos.length; i++) {
1418
+ const row = pos[i][0]
1419
+ const col = pos[i][1]
1420
+
1421
+ for (let r = -2; r <= 2; r++) {
1422
+ for (let c = -2; c <= 2; c++) {
1423
+ if (r === -2 || r === 2 || c === -2 || c === 2 ||
1424
+ (r === 0 && c === 0)) {
1425
+ matrix.set(row + r, col + c, true, true)
1426
+ } else {
1427
+ matrix.set(row + r, col + c, false, true)
1428
+ }
1429
+ }
1430
+ }
1431
+ }
1432
+ }
1433
+
1434
+ /**
1435
+ * Add version info bits to matrix
1436
+ *
1437
+ * @param {BitMatrix} matrix Modules matrix
1438
+ * @param {Number} version QR Code version
1439
+ */
1440
+ function setupVersionInfo (matrix, version) {
1441
+ const size = matrix.size
1442
+ const bits = Version.getEncodedBits(version)
1443
+ let row, col, mod
1444
+
1445
+ for (let i = 0; i < 18; i++) {
1446
+ row = Math.floor(i / 3)
1447
+ col = i % 3 + size - 8 - 3
1448
+ mod = ((bits >> i) & 1) === 1
1449
+
1450
+ matrix.set(row, col, mod, true)
1451
+ matrix.set(col, row, mod, true)
1452
+ }
1453
+ }
1454
+
1455
+ /**
1456
+ * Add format info bits to matrix
1457
+ *
1458
+ * @param {BitMatrix} matrix Modules matrix
1459
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
1460
+ * @param {Number} maskPattern Mask pattern reference value
1461
+ */
1462
+ function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
1463
+ const size = matrix.size
1464
+ const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern)
1465
+ let i, mod
1466
+
1467
+ for (i = 0; i < 15; i++) {
1468
+ mod = ((bits >> i) & 1) === 1
1469
+
1470
+ // vertical
1471
+ if (i < 6) {
1472
+ matrix.set(i, 8, mod, true)
1473
+ } else if (i < 8) {
1474
+ matrix.set(i + 1, 8, mod, true)
1475
+ } else {
1476
+ matrix.set(size - 15 + i, 8, mod, true)
1477
+ }
1478
+
1479
+ // horizontal
1480
+ if (i < 8) {
1481
+ matrix.set(8, size - i - 1, mod, true)
1482
+ } else if (i < 9) {
1483
+ matrix.set(8, 15 - i - 1 + 1, mod, true)
1484
+ } else {
1485
+ matrix.set(8, 15 - i - 1, mod, true)
1486
+ }
1487
+ }
1488
+
1489
+ // fixed module
1490
+ matrix.set(size - 8, 8, 1, true)
1491
+ }
1492
+
1493
+ /**
1494
+ * Add encoded data bits to matrix
1495
+ *
1496
+ * @param {BitMatrix} matrix Modules matrix
1497
+ * @param {Uint8Array} data Data codewords
1498
+ */
1499
+ function setupData (matrix, data) {
1500
+ const size = matrix.size
1501
+ let inc = -1
1502
+ let row = size - 1
1503
+ let bitIndex = 7
1504
+ let byteIndex = 0
1505
+
1506
+ for (let col = size - 1; col > 0; col -= 2) {
1507
+ if (col === 6) col--
1508
+
1509
+ while (true) {
1510
+ for (let c = 0; c < 2; c++) {
1511
+ if (!matrix.isReserved(row, col - c)) {
1512
+ let dark = false
1513
+
1514
+ if (byteIndex < data.length) {
1515
+ dark = (((data[byteIndex] >>> bitIndex) & 1) === 1)
1516
+ }
1517
+
1518
+ matrix.set(row, col - c, dark)
1519
+ bitIndex--
1520
+
1521
+ if (bitIndex === -1) {
1522
+ byteIndex++
1523
+ bitIndex = 7
1524
+ }
1525
+ }
1526
+ }
1527
+
1528
+ row += inc
1529
+
1530
+ if (row < 0 || size <= row) {
1531
+ row -= inc
1532
+ inc = -inc
1533
+ break
1534
+ }
1535
+ }
1536
+ }
1537
+ }
1538
+
1539
+ /**
1540
+ * Create encoded codewords from data input
1541
+ *
1542
+ * @param {Number} version QR Code version
1543
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
1544
+ * @param {ByteData} data Data input
1545
+ * @return {Uint8Array} Buffer containing encoded codewords
1546
+ */
1547
+ function createData (version, errorCorrectionLevel, segments) {
1548
+ // Prepare data buffer
1549
+ const buffer = new BitBuffer()
1550
+
1551
+ segments.forEach(function (data) {
1552
+ // prefix data with mode indicator (4 bits)
1553
+ buffer.put(data.mode.bit, 4)
1554
+
1555
+ // Prefix data with character count indicator.
1556
+ // The character count indicator is a string of bits that represents the
1557
+ // number of characters that are being encoded.
1558
+ // The character count indicator must be placed after the mode indicator
1559
+ // and must be a certain number of bits long, depending on the QR version
1560
+ // and data mode
1561
+ // @see {@link Mode.getCharCountIndicator}.
1562
+ buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version))
1563
+
1564
+ // add binary data sequence to buffer
1565
+ data.write(buffer)
1566
+ })
1567
+
1568
+ // Calculate required number of bits
1569
+ const totalCodewords = Utils.getSymbolTotalCodewords(version)
1570
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
1571
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
1572
+
1573
+ // Add a terminator.
1574
+ // If the bit string is shorter than the total number of required bits,
1575
+ // a terminator of up to four 0s must be added to the right side of the string.
1576
+ // If the bit string is more than four bits shorter than the required number of bits,
1577
+ // add four 0s to the end.
1578
+ if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
1579
+ buffer.put(0, 4)
1580
+ }
1581
+
1582
+ // If the bit string is fewer than four bits shorter, add only the number of 0s that
1583
+ // are needed to reach the required number of bits.
1584
+
1585
+ // After adding the terminator, if the number of bits in the string is not a multiple of 8,
1586
+ // pad the string on the right with 0s to make the string's length a multiple of 8.
1587
+ while (buffer.getLengthInBits() % 8 !== 0) {
1588
+ buffer.putBit(0)
1589
+ }
1590
+
1591
+ // Add pad bytes if the string is still shorter than the total number of required bits.
1592
+ // Extend the buffer to fill the data capacity of the symbol corresponding to
1593
+ // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
1594
+ // and 00010001 (0x11) alternately.
1595
+ const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8
1596
+ for (let i = 0; i < remainingByte; i++) {
1597
+ buffer.put(i % 2 ? 0x11 : 0xEC, 8)
1598
+ }
1599
+
1600
+ return createCodewords(buffer, version, errorCorrectionLevel)
1601
+ }
1602
+
1603
+ /**
1604
+ * Encode input data with Reed-Solomon and return codewords with
1605
+ * relative error correction bits
1606
+ *
1607
+ * @param {BitBuffer} bitBuffer Data to encode
1608
+ * @param {Number} version QR Code version
1609
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
1610
+ * @return {Uint8Array} Buffer containing encoded codewords
1611
+ */
1612
+ function createCodewords (bitBuffer, version, errorCorrectionLevel) {
1613
+ // Total codewords for this QR code version (Data + Error correction)
1614
+ const totalCodewords = Utils.getSymbolTotalCodewords(version)
1615
+
1616
+ // Total number of error correction codewords
1617
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
1618
+
1619
+ // Total number of data codewords
1620
+ const dataTotalCodewords = totalCodewords - ecTotalCodewords
1621
+
1622
+ // Total number of blocks
1623
+ const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel)
1624
+
1625
+ // Calculate how many blocks each group should contain
1626
+ const blocksInGroup2 = totalCodewords % ecTotalBlocks
1627
+ const blocksInGroup1 = ecTotalBlocks - blocksInGroup2
1628
+
1629
+ const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks)
1630
+
1631
+ const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks)
1632
+ const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1
1633
+
1634
+ // Number of EC codewords is the same for both groups
1635
+ const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1
1636
+
1637
+ // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
1638
+ const rs = new ReedSolomonEncoder(ecCount)
1639
+
1640
+ let offset = 0
1641
+ const dcData = new Array(ecTotalBlocks)
1642
+ const ecData = new Array(ecTotalBlocks)
1643
+ let maxDataSize = 0
1644
+ const buffer = new Uint8Array(bitBuffer.buffer)
1645
+
1646
+ // Divide the buffer into the required number of blocks
1647
+ for (let b = 0; b < ecTotalBlocks; b++) {
1648
+ const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2
1649
+
1650
+ // extract a block of data from buffer
1651
+ dcData[b] = buffer.slice(offset, offset + dataSize)
1652
+
1653
+ // Calculate EC codewords for this data block
1654
+ ecData[b] = rs.encode(dcData[b])
1655
+
1656
+ offset += dataSize
1657
+ maxDataSize = Math.max(maxDataSize, dataSize)
1658
+ }
1659
+
1660
+ // Create final data
1661
+ // Interleave the data and error correction codewords from each block
1662
+ const data = new Uint8Array(totalCodewords)
1663
+ let index = 0
1664
+ let i, r
1665
+
1666
+ // Add data codewords
1667
+ for (i = 0; i < maxDataSize; i++) {
1668
+ for (r = 0; r < ecTotalBlocks; r++) {
1669
+ if (i < dcData[r].length) {
1670
+ data[index++] = dcData[r][i]
1671
+ }
1672
+ }
1673
+ }
1674
+
1675
+ // Apped EC codewords
1676
+ for (i = 0; i < ecCount; i++) {
1677
+ for (r = 0; r < ecTotalBlocks; r++) {
1678
+ data[index++] = ecData[r][i]
1679
+ }
1680
+ }
1681
+
1682
+ return data
1683
+ }
1684
+
1685
+ /**
1686
+ * Build QR Code symbol
1687
+ *
1688
+ * @param {String} data Input string
1689
+ * @param {Number} version QR Code version
1690
+ * @param {ErrorCorretionLevel} errorCorrectionLevel Error level
1691
+ * @param {MaskPattern} maskPattern Mask pattern
1692
+ * @return {Object} Object containing symbol data
1693
+ */
1694
+ function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
1695
+ let segments
1696
+
1697
+ if (Array.isArray(data)) {
1698
+ segments = Segments.fromArray(data)
1699
+ } else if (typeof data === 'string') {
1700
+ let estimatedVersion = version
1701
+
1702
+ if (!estimatedVersion) {
1703
+ const rawSegments = Segments.rawSplit(data)
1704
+
1705
+ // Estimate best version that can contain raw splitted segments
1706
+ estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel)
1707
+ }
1708
+
1709
+ // Build optimized segments
1710
+ // If estimated version is undefined, try with the highest version
1711
+ segments = Segments.fromString(data, estimatedVersion || 40)
1712
+ } else {
1713
+ throw new Error('Invalid data')
1714
+ }
1715
+
1716
+ // Get the min version that can contain data
1717
+ const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel)
1718
+
1719
+ // If no version is found, data cannot be stored
1720
+ if (!bestVersion) {
1721
+ throw new Error('The amount of data is too big to be stored in a QR Code')
1722
+ }
1723
+
1724
+ // If not specified, use min version as default
1725
+ if (!version) {
1726
+ version = bestVersion
1727
+
1728
+ // Check if the specified version can contain the data
1729
+ } else if (version < bestVersion) {
1730
+ throw new Error('\n' +
1731
+ 'The chosen QR Code version cannot contain this amount of data.\n' +
1732
+ 'Minimum version required to store current data is: ' + bestVersion + '.\n'
1733
+ )
1734
+ }
1735
+
1736
+ const dataBits = createData(version, errorCorrectionLevel, segments)
1737
+
1738
+ // Allocate matrix buffer
1739
+ const moduleCount = Utils.getSymbolSize(version)
1740
+ const modules = new BitMatrix(moduleCount)
1741
+
1742
+ // Add function modules
1743
+ setupFinderPattern(modules, version)
1744
+ setupTimingPattern(modules)
1745
+ setupAlignmentPattern(modules, version)
1746
+
1747
+ // Add temporary dummy bits for format info just to set them as reserved.
1748
+ // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
1749
+ // since the masking operation must be performed only on the encoding region.
1750
+ // These blocks will be replaced with correct values later in code.
1751
+ setupFormatInfo(modules, errorCorrectionLevel, 0)
1752
+
1753
+ if (version >= 7) {
1754
+ setupVersionInfo(modules, version)
1755
+ }
1756
+
1757
+ // Add data codewords
1758
+ setupData(modules, dataBits)
1759
+
1760
+ if (isNaN(maskPattern)) {
1761
+ // Find best mask pattern
1762
+ maskPattern = MaskPattern.getBestMask(modules,
1763
+ setupFormatInfo.bind(null, modules, errorCorrectionLevel))
1764
+ }
1765
+
1766
+ // Apply mask pattern
1767
+ MaskPattern.applyMask(maskPattern, modules)
1768
+
1769
+ // Replace format info bits with correct values
1770
+ setupFormatInfo(modules, errorCorrectionLevel, maskPattern)
1771
+
1772
+ return {
1773
+ modules: modules,
1774
+ version: version,
1775
+ errorCorrectionLevel: errorCorrectionLevel,
1776
+ maskPattern: maskPattern,
1777
+ segments: segments
1778
+ }
1779
+ }
1780
+
1781
+ /**
1782
+ * QR Code
1783
+ *
1784
+ * @param {String | Array} data Input data
1785
+ * @param {Object} options Optional configurations
1786
+ * @param {Number} options.version QR Code version
1787
+ * @param {String} options.errorCorrectionLevel Error correction level
1788
+ * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis
1789
+ */
1790
+ exports.create = function create (data, options) {
1791
+ if (typeof data === 'undefined' || data === '') {
1792
+ throw new Error('No input text')
1793
+ }
1794
+
1795
+ let errorCorrectionLevel = ECLevel.M
1796
+ let version
1797
+ let mask
1798
+
1799
+ if (typeof options !== 'undefined') {
1800
+ // Use higher error correction level as default
1801
+ errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M)
1802
+ version = Version.from(options.version)
1803
+ mask = MaskPattern.from(options.maskPattern)
1804
+
1805
+ if (options.toSJISFunc) {
1806
+ Utils.setToSJISFunction(options.toSJISFunc)
1807
+ }
1808
+ }
1809
+
1810
+ return createSymbol(data, version, errorCorrectionLevel, mask)
1811
+ }
1812
+
1813
+ };
1814
+
1815
+ modules["core/reed-solomon-encoder.js"] = function(module, exports, require) {
1816
+ const Polynomial = require('./polynomial')
1817
+
1818
+ function ReedSolomonEncoder (degree) {
1819
+ this.genPoly = undefined
1820
+ this.degree = degree
1821
+
1822
+ if (this.degree) this.initialize(this.degree)
1823
+ }
1824
+
1825
+ /**
1826
+ * Initialize the encoder.
1827
+ * The input param should correspond to the number of error correction codewords.
1828
+ *
1829
+ * @param {Number} degree
1830
+ */
1831
+ ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
1832
+ // create an irreducible generator polynomial
1833
+ this.degree = degree
1834
+ this.genPoly = Polynomial.generateECPolynomial(this.degree)
1835
+ }
1836
+
1837
+ /**
1838
+ * Encodes a chunk of data
1839
+ *
1840
+ * @param {Uint8Array} data Buffer containing input data
1841
+ * @return {Uint8Array} Buffer containing encoded data
1842
+ */
1843
+ ReedSolomonEncoder.prototype.encode = function encode (data) {
1844
+ if (!this.genPoly) {
1845
+ throw new Error('Encoder not initialized')
1846
+ }
1847
+
1848
+ // Calculate EC for this data block
1849
+ // extends data size to data+genPoly size
1850
+ const paddedData = new Uint8Array(data.length + this.degree)
1851
+ paddedData.set(data)
1852
+
1853
+ // The error correction codewords are the remainder after dividing the data codewords
1854
+ // by a generator polynomial
1855
+ const remainder = Polynomial.mod(paddedData, this.genPoly)
1856
+
1857
+ // return EC data blocks (last n byte, where n is the degree of genPoly)
1858
+ // If coefficients number in remainder are less than genPoly degree,
1859
+ // pad with 0s to the left to reach the needed number of coefficients
1860
+ const start = this.degree - remainder.length
1861
+ if (start > 0) {
1862
+ const buff = new Uint8Array(this.degree)
1863
+ buff.set(remainder, start)
1864
+
1865
+ return buff
1866
+ }
1867
+
1868
+ return remainder
1869
+ }
1870
+
1871
+ module.exports = ReedSolomonEncoder
1872
+
1873
+ };
1874
+
1875
+ modules["core/regex.js"] = function(module, exports, require) {
1876
+ const numeric = '[0-9]+'
1877
+ const alphanumeric = '[A-Z $%*+\\-./:]+'
1878
+ let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
1879
+ '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
1880
+ '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
1881
+ '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+'
1882
+ kanji = kanji.replace(/u/g, '\\u')
1883
+
1884
+ const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+'
1885
+
1886
+ exports.KANJI = new RegExp(kanji, 'g')
1887
+ exports.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g')
1888
+ exports.BYTE = new RegExp(byte, 'g')
1889
+ exports.NUMERIC = new RegExp(numeric, 'g')
1890
+ exports.ALPHANUMERIC = new RegExp(alphanumeric, 'g')
1891
+
1892
+ const TEST_KANJI = new RegExp('^' + kanji + '$')
1893
+ const TEST_NUMERIC = new RegExp('^' + numeric + '$')
1894
+ const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$')
1895
+
1896
+ exports.testKanji = function testKanji (str) {
1897
+ return TEST_KANJI.test(str)
1898
+ }
1899
+
1900
+ exports.testNumeric = function testNumeric (str) {
1901
+ return TEST_NUMERIC.test(str)
1902
+ }
1903
+
1904
+ exports.testAlphanumeric = function testAlphanumeric (str) {
1905
+ return TEST_ALPHANUMERIC.test(str)
1906
+ }
1907
+
1908
+ };
1909
+
1910
+ modules["core/segments.js"] = function(module, exports, require) {
1911
+ const Mode = require('./mode')
1912
+ const NumericData = require('./numeric-data')
1913
+ const AlphanumericData = require('./alphanumeric-data')
1914
+ const ByteData = require('./byte-data')
1915
+ const KanjiData = require('./kanji-data')
1916
+ const Regex = require('./regex')
1917
+ const Utils = require('./utils')
1918
+ const dijkstra = require('dijkstrajs')
1919
+
1920
+ /**
1921
+ * Returns UTF8 byte length
1922
+ *
1923
+ * @param {String} str Input string
1924
+ * @return {Number} Number of byte
1925
+ */
1926
+ function getStringByteLength (str) {
1927
+ return unescape(encodeURIComponent(str)).length
1928
+ }
1929
+
1930
+ /**
1931
+ * Get a list of segments of the specified mode
1932
+ * from a string
1933
+ *
1934
+ * @param {Mode} mode Segment mode
1935
+ * @param {String} str String to process
1936
+ * @return {Array} Array of object with segments data
1937
+ */
1938
+ function getSegments (regex, mode, str) {
1939
+ const segments = []
1940
+ let result
1941
+
1942
+ while ((result = regex.exec(str)) !== null) {
1943
+ segments.push({
1944
+ data: result[0],
1945
+ index: result.index,
1946
+ mode: mode,
1947
+ length: result[0].length
1948
+ })
1949
+ }
1950
+
1951
+ return segments
1952
+ }
1953
+
1954
+ /**
1955
+ * Extracts a series of segments with the appropriate
1956
+ * modes from a string
1957
+ *
1958
+ * @param {String} dataStr Input string
1959
+ * @return {Array} Array of object with segments data
1960
+ */
1961
+ function getSegmentsFromString (dataStr) {
1962
+ const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr)
1963
+ const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr)
1964
+ let byteSegs
1965
+ let kanjiSegs
1966
+
1967
+ if (Utils.isKanjiModeEnabled()) {
1968
+ byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr)
1969
+ kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr)
1970
+ } else {
1971
+ byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr)
1972
+ kanjiSegs = []
1973
+ }
1974
+
1975
+ const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs)
1976
+
1977
+ return segs
1978
+ .sort(function (s1, s2) {
1979
+ return s1.index - s2.index
1980
+ })
1981
+ .map(function (obj) {
1982
+ return {
1983
+ data: obj.data,
1984
+ mode: obj.mode,
1985
+ length: obj.length
1986
+ }
1987
+ })
1988
+ }
1989
+
1990
+ /**
1991
+ * Returns how many bits are needed to encode a string of
1992
+ * specified length with the specified mode
1993
+ *
1994
+ * @param {Number} length String length
1995
+ * @param {Mode} mode Segment mode
1996
+ * @return {Number} Bit length
1997
+ */
1998
+ function getSegmentBitsLength (length, mode) {
1999
+ switch (mode) {
2000
+ case Mode.NUMERIC:
2001
+ return NumericData.getBitsLength(length)
2002
+ case Mode.ALPHANUMERIC:
2003
+ return AlphanumericData.getBitsLength(length)
2004
+ case Mode.KANJI:
2005
+ return KanjiData.getBitsLength(length)
2006
+ case Mode.BYTE:
2007
+ return ByteData.getBitsLength(length)
2008
+ }
2009
+ }
2010
+
2011
+ /**
2012
+ * Merges adjacent segments which have the same mode
2013
+ *
2014
+ * @param {Array} segs Array of object with segments data
2015
+ * @return {Array} Array of object with segments data
2016
+ */
2017
+ function mergeSegments (segs) {
2018
+ return segs.reduce(function (acc, curr) {
2019
+ const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null
2020
+ if (prevSeg && prevSeg.mode === curr.mode) {
2021
+ acc[acc.length - 1].data += curr.data
2022
+ return acc
2023
+ }
2024
+
2025
+ acc.push(curr)
2026
+ return acc
2027
+ }, [])
2028
+ }
2029
+
2030
+ /**
2031
+ * Generates a list of all possible nodes combination which
2032
+ * will be used to build a segments graph.
2033
+ *
2034
+ * Nodes are divided by groups. Each group will contain a list of all the modes
2035
+ * in which is possible to encode the given text.
2036
+ *
2037
+ * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
2038
+ * The group for '12345' will contain then 3 objects, one for each
2039
+ * possible encoding mode.
2040
+ *
2041
+ * Each node represents a possible segment.
2042
+ *
2043
+ * @param {Array} segs Array of object with segments data
2044
+ * @return {Array} Array of object with segments data
2045
+ */
2046
+ function buildNodes (segs) {
2047
+ const nodes = []
2048
+ for (let i = 0; i < segs.length; i++) {
2049
+ const seg = segs[i]
2050
+
2051
+ switch (seg.mode) {
2052
+ case Mode.NUMERIC:
2053
+ nodes.push([seg,
2054
+ { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
2055
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
2056
+ ])
2057
+ break
2058
+ case Mode.ALPHANUMERIC:
2059
+ nodes.push([seg,
2060
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
2061
+ ])
2062
+ break
2063
+ case Mode.KANJI:
2064
+ nodes.push([seg,
2065
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
2066
+ ])
2067
+ break
2068
+ case Mode.BYTE:
2069
+ nodes.push([
2070
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
2071
+ ])
2072
+ }
2073
+ }
2074
+
2075
+ return nodes
2076
+ }
2077
+
2078
+ /**
2079
+ * Builds a graph from a list of nodes.
2080
+ * All segments in each node group will be connected with all the segments of
2081
+ * the next group and so on.
2082
+ *
2083
+ * At each connection will be assigned a weight depending on the
2084
+ * segment's byte length.
2085
+ *
2086
+ * @param {Array} nodes Array of object with segments data
2087
+ * @param {Number} version QR Code version
2088
+ * @return {Object} Graph of all possible segments
2089
+ */
2090
+ function buildGraph (nodes, version) {
2091
+ const table = {}
2092
+ const graph = { start: {} }
2093
+ let prevNodeIds = ['start']
2094
+
2095
+ for (let i = 0; i < nodes.length; i++) {
2096
+ const nodeGroup = nodes[i]
2097
+ const currentNodeIds = []
2098
+
2099
+ for (let j = 0; j < nodeGroup.length; j++) {
2100
+ const node = nodeGroup[j]
2101
+ const key = '' + i + j
2102
+
2103
+ currentNodeIds.push(key)
2104
+ table[key] = { node: node, lastCount: 0 }
2105
+ graph[key] = {}
2106
+
2107
+ for (let n = 0; n < prevNodeIds.length; n++) {
2108
+ const prevNodeId = prevNodeIds[n]
2109
+
2110
+ if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
2111
+ graph[prevNodeId][key] =
2112
+ getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
2113
+ getSegmentBitsLength(table[prevNodeId].lastCount, node.mode)
2114
+
2115
+ table[prevNodeId].lastCount += node.length
2116
+ } else {
2117
+ if (table[prevNodeId]) table[prevNodeId].lastCount = node.length
2118
+
2119
+ graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
2120
+ 4 + Mode.getCharCountIndicator(node.mode, version) // switch cost
2121
+ }
2122
+ }
2123
+ }
2124
+
2125
+ prevNodeIds = currentNodeIds
2126
+ }
2127
+
2128
+ for (let n = 0; n < prevNodeIds.length; n++) {
2129
+ graph[prevNodeIds[n]].end = 0
2130
+ }
2131
+
2132
+ return { map: graph, table: table }
2133
+ }
2134
+
2135
+ /**
2136
+ * Builds a segment from a specified data and mode.
2137
+ * If a mode is not specified, the more suitable will be used.
2138
+ *
2139
+ * @param {String} data Input data
2140
+ * @param {Mode | String} modesHint Data mode
2141
+ * @return {Segment} Segment
2142
+ */
2143
+ function buildSingleSegment (data, modesHint) {
2144
+ let mode
2145
+ const bestMode = Mode.getBestModeForData(data)
2146
+
2147
+ mode = Mode.from(modesHint, bestMode)
2148
+
2149
+ // Make sure data can be encoded
2150
+ if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
2151
+ throw new Error('"' + data + '"' +
2152
+ ' cannot be encoded with mode ' + Mode.toString(mode) +
2153
+ '.\n Suggested mode is: ' + Mode.toString(bestMode))
2154
+ }
2155
+
2156
+ // Use Mode.BYTE if Kanji support is disabled
2157
+ if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
2158
+ mode = Mode.BYTE
2159
+ }
2160
+
2161
+ switch (mode) {
2162
+ case Mode.NUMERIC:
2163
+ return new NumericData(data)
2164
+
2165
+ case Mode.ALPHANUMERIC:
2166
+ return new AlphanumericData(data)
2167
+
2168
+ case Mode.KANJI:
2169
+ return new KanjiData(data)
2170
+
2171
+ case Mode.BYTE:
2172
+ return new ByteData(data)
2173
+ }
2174
+ }
2175
+
2176
+ /**
2177
+ * Builds a list of segments from an array.
2178
+ * Array can contain Strings or Objects with segment's info.
2179
+ *
2180
+ * For each item which is a string, will be generated a segment with the given
2181
+ * string and the more appropriate encoding mode.
2182
+ *
2183
+ * For each item which is an object, will be generated a segment with the given
2184
+ * data and mode.
2185
+ * Objects must contain at least the property "data".
2186
+ * If property "mode" is not present, the more suitable mode will be used.
2187
+ *
2188
+ * @param {Array} array Array of objects with segments data
2189
+ * @return {Array} Array of Segments
2190
+ */
2191
+ exports.fromArray = function fromArray (array) {
2192
+ return array.reduce(function (acc, seg) {
2193
+ if (typeof seg === 'string') {
2194
+ acc.push(buildSingleSegment(seg, null))
2195
+ } else if (seg.data) {
2196
+ acc.push(buildSingleSegment(seg.data, seg.mode))
2197
+ }
2198
+
2199
+ return acc
2200
+ }, [])
2201
+ }
2202
+
2203
+ /**
2204
+ * Builds an optimized sequence of segments from a string,
2205
+ * which will produce the shortest possible bitstream.
2206
+ *
2207
+ * @param {String} data Input string
2208
+ * @param {Number} version QR Code version
2209
+ * @return {Array} Array of segments
2210
+ */
2211
+ exports.fromString = function fromString (data, version) {
2212
+ const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled())
2213
+
2214
+ const nodes = buildNodes(segs)
2215
+ const graph = buildGraph(nodes, version)
2216
+ const path = dijkstra.find_path(graph.map, 'start', 'end')
2217
+
2218
+ const optimizedSegs = []
2219
+ for (let i = 1; i < path.length - 1; i++) {
2220
+ optimizedSegs.push(graph.table[path[i]].node)
2221
+ }
2222
+
2223
+ return exports.fromArray(mergeSegments(optimizedSegs))
2224
+ }
2225
+
2226
+ /**
2227
+ * Splits a string in various segments with the modes which
2228
+ * best represent their content.
2229
+ * The produced segments are far from being optimized.
2230
+ * The output of this function is only used to estimate a QR Code version
2231
+ * which may contain the data.
2232
+ *
2233
+ * @param {string} data Input string
2234
+ * @return {Array} Array of segments
2235
+ */
2236
+ exports.rawSplit = function rawSplit (data) {
2237
+ return exports.fromArray(
2238
+ getSegmentsFromString(data, Utils.isKanjiModeEnabled())
2239
+ )
2240
+ }
2241
+
2242
+ };
2243
+
2244
+ modules["core/utils.js"] = function(module, exports, require) {
2245
+ let toSJISFunction
2246
+ const CODEWORDS_COUNT = [
2247
+ 0, // Not used
2248
+ 26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
2249
+ 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
2250
+ 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
2251
+ 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
2252
+ ]
2253
+
2254
+ /**
2255
+ * Returns the QR Code size for the specified version
2256
+ *
2257
+ * @param {Number} version QR Code version
2258
+ * @return {Number} size of QR code
2259
+ */
2260
+ exports.getSymbolSize = function getSymbolSize (version) {
2261
+ if (!version) throw new Error('"version" cannot be null or undefined')
2262
+ if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
2263
+ return version * 4 + 17
2264
+ }
2265
+
2266
+ /**
2267
+ * Returns the total number of codewords used to store data and EC information.
2268
+ *
2269
+ * @param {Number} version QR Code version
2270
+ * @return {Number} Data length in bits
2271
+ */
2272
+ exports.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
2273
+ return CODEWORDS_COUNT[version]
2274
+ }
2275
+
2276
+ /**
2277
+ * Encode data with Bose-Chaudhuri-Hocquenghem
2278
+ *
2279
+ * @param {Number} data Value to encode
2280
+ * @return {Number} Encoded value
2281
+ */
2282
+ exports.getBCHDigit = function (data) {
2283
+ let digit = 0
2284
+
2285
+ while (data !== 0) {
2286
+ digit++
2287
+ data >>>= 1
2288
+ }
2289
+
2290
+ return digit
2291
+ }
2292
+
2293
+ exports.setToSJISFunction = function setToSJISFunction (f) {
2294
+ if (typeof f !== 'function') {
2295
+ throw new Error('"toSJISFunc" is not a valid function.')
2296
+ }
2297
+
2298
+ toSJISFunction = f
2299
+ }
2300
+
2301
+ exports.isKanjiModeEnabled = function () {
2302
+ return typeof toSJISFunction !== 'undefined'
2303
+ }
2304
+
2305
+ exports.toSJIS = function toSJIS (kanji) {
2306
+ return toSJISFunction(kanji)
2307
+ }
2308
+
2309
+ };
2310
+
2311
+ modules["core/version-check.js"] = function(module, exports, require) {
2312
+ /**
2313
+ * Check if QR Code version is valid
2314
+ *
2315
+ * @param {Number} version QR Code version
2316
+ * @return {Boolean} true if valid version, false otherwise
2317
+ */
2318
+ exports.isValid = function isValid (version) {
2319
+ return !isNaN(version) && version >= 1 && version <= 40
2320
+ }
2321
+
2322
+ };
2323
+
2324
+ modules["core/version.js"] = function(module, exports, require) {
2325
+ const Utils = require('./utils')
2326
+ const ECCode = require('./error-correction-code')
2327
+ const ECLevel = require('./error-correction-level')
2328
+ const Mode = require('./mode')
2329
+ const VersionCheck = require('./version-check')
2330
+
2331
+ // Generator polynomial used to encode version information
2332
+ const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0)
2333
+ const G18_BCH = Utils.getBCHDigit(G18)
2334
+
2335
+ function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
2336
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
2337
+ if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
2338
+ return currentVersion
2339
+ }
2340
+ }
2341
+
2342
+ return undefined
2343
+ }
2344
+
2345
+ function getReservedBitsCount (mode, version) {
2346
+ // Character count indicator + mode indicator bits
2347
+ return Mode.getCharCountIndicator(mode, version) + 4
2348
+ }
2349
+
2350
+ function getTotalBitsFromDataArray (segments, version) {
2351
+ let totalBits = 0
2352
+
2353
+ segments.forEach(function (data) {
2354
+ const reservedBits = getReservedBitsCount(data.mode, version)
2355
+ totalBits += reservedBits + data.getBitsLength()
2356
+ })
2357
+
2358
+ return totalBits
2359
+ }
2360
+
2361
+ function getBestVersionForMixedData (segments, errorCorrectionLevel) {
2362
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
2363
+ const length = getTotalBitsFromDataArray(segments, currentVersion)
2364
+ if (length <= exports.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
2365
+ return currentVersion
2366
+ }
2367
+ }
2368
+
2369
+ return undefined
2370
+ }
2371
+
2372
+ /**
2373
+ * Returns version number from a value.
2374
+ * If value is not a valid version, returns defaultValue
2375
+ *
2376
+ * @param {Number|String} value QR Code version
2377
+ * @param {Number} defaultValue Fallback value
2378
+ * @return {Number} QR Code version number
2379
+ */
2380
+ exports.from = function from (value, defaultValue) {
2381
+ if (VersionCheck.isValid(value)) {
2382
+ return parseInt(value, 10)
2383
+ }
2384
+
2385
+ return defaultValue
2386
+ }
2387
+
2388
+ /**
2389
+ * Returns how much data can be stored with the specified QR code version
2390
+ * and error correction level
2391
+ *
2392
+ * @param {Number} version QR Code version (1-40)
2393
+ * @param {Number} errorCorrectionLevel Error correction level
2394
+ * @param {Mode} mode Data mode
2395
+ * @return {Number} Quantity of storable data
2396
+ */
2397
+ exports.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
2398
+ if (!VersionCheck.isValid(version)) {
2399
+ throw new Error('Invalid QR Code version')
2400
+ }
2401
+
2402
+ // Use Byte mode as default
2403
+ if (typeof mode === 'undefined') mode = Mode.BYTE
2404
+
2405
+ // Total codewords for this QR code version (Data + Error correction)
2406
+ const totalCodewords = Utils.getSymbolTotalCodewords(version)
2407
+
2408
+ // Total number of error correction codewords
2409
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel)
2410
+
2411
+ // Total number of data codewords
2412
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8
2413
+
2414
+ if (mode === Mode.MIXED) return dataTotalCodewordsBits
2415
+
2416
+ const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version)
2417
+
2418
+ // Return max number of storable codewords
2419
+ switch (mode) {
2420
+ case Mode.NUMERIC:
2421
+ return Math.floor((usableBits / 10) * 3)
2422
+
2423
+ case Mode.ALPHANUMERIC:
2424
+ return Math.floor((usableBits / 11) * 2)
2425
+
2426
+ case Mode.KANJI:
2427
+ return Math.floor(usableBits / 13)
2428
+
2429
+ case Mode.BYTE:
2430
+ default:
2431
+ return Math.floor(usableBits / 8)
2432
+ }
2433
+ }
2434
+
2435
+ /**
2436
+ * Returns the minimum version needed to contain the amount of data
2437
+ *
2438
+ * @param {Segment} data Segment of data
2439
+ * @param {Number} [errorCorrectionLevel=H] Error correction level
2440
+ * @param {Mode} mode Data mode
2441
+ * @return {Number} QR Code version
2442
+ */
2443
+ exports.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
2444
+ let seg
2445
+
2446
+ const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M)
2447
+
2448
+ if (Array.isArray(data)) {
2449
+ if (data.length > 1) {
2450
+ return getBestVersionForMixedData(data, ecl)
2451
+ }
2452
+
2453
+ if (data.length === 0) {
2454
+ return 1
2455
+ }
2456
+
2457
+ seg = data[0]
2458
+ } else {
2459
+ seg = data
2460
+ }
2461
+
2462
+ return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
2463
+ }
2464
+
2465
+ /**
2466
+ * Returns version information with relative error correction bits
2467
+ *
2468
+ * The version information is included in QR Code symbols of version 7 or larger.
2469
+ * It consists of an 18-bit sequence containing 6 data bits,
2470
+ * with 12 error correction bits calculated using the (18, 6) Golay code.
2471
+ *
2472
+ * @param {Number} version QR Code version
2473
+ * @return {Number} Encoded version info bits
2474
+ */
2475
+ exports.getEncodedBits = function getEncodedBits (version) {
2476
+ if (!VersionCheck.isValid(version) || version < 7) {
2477
+ throw new Error('Invalid QR Code version')
2478
+ }
2479
+
2480
+ let d = version << 12
2481
+
2482
+ while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
2483
+ d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH))
2484
+ }
2485
+
2486
+ return (version << 12) | d
2487
+ }
2488
+
2489
+ };
2490
+
2491
+ modules["index.js"] = function(module, exports, require) {
2492
+ /*
2493
+ *copyright Ryan Day 2012
2494
+ *
2495
+ * Licensed under the MIT license:
2496
+ * http://www.opensource.org/licenses/mit-license.php
2497
+ *
2498
+ * this is the main server side application file for node-qrcode.
2499
+ * these exports use serverside canvas api methods for file IO and buffers
2500
+ *
2501
+ */
2502
+
2503
+ module.exports = require('./server')
2504
+
2505
+ };
2506
+
2507
+ modules["renderer/svg-tag.js"] = function(module, exports, require) {
2508
+ const Utils = require('./utils')
2509
+
2510
+ function getColorAttrib (color, attrib) {
2511
+ const alpha = color.a / 255
2512
+ const str = attrib + '="' + color.hex + '"'
2513
+
2514
+ return alpha < 1
2515
+ ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
2516
+ : str
2517
+ }
2518
+
2519
+ function svgCmd (cmd, x, y) {
2520
+ let str = cmd + x
2521
+ if (typeof y !== 'undefined') str += ' ' + y
2522
+
2523
+ return str
2524
+ }
2525
+
2526
+ function qrToPath (data, size, margin) {
2527
+ let path = ''
2528
+ let moveBy = 0
2529
+ let newRow = false
2530
+ let lineLength = 0
2531
+
2532
+ for (let i = 0; i < data.length; i++) {
2533
+ const col = Math.floor(i % size)
2534
+ const row = Math.floor(i / size)
2535
+
2536
+ if (!col && !newRow) newRow = true
2537
+
2538
+ if (data[i]) {
2539
+ lineLength++
2540
+
2541
+ if (!(i > 0 && col > 0 && data[i - 1])) {
2542
+ path += newRow
2543
+ ? svgCmd('M', col + margin, 0.5 + row + margin)
2544
+ : svgCmd('m', moveBy, 0)
2545
+
2546
+ moveBy = 0
2547
+ newRow = false
2548
+ }
2549
+
2550
+ if (!(col + 1 < size && data[i + 1])) {
2551
+ path += svgCmd('h', lineLength)
2552
+ lineLength = 0
2553
+ }
2554
+ } else {
2555
+ moveBy++
2556
+ }
2557
+ }
2558
+
2559
+ return path
2560
+ }
2561
+
2562
+ exports.render = function render (qrData, options, cb) {
2563
+ const opts = Utils.getOptions(options)
2564
+ const size = qrData.modules.size
2565
+ const data = qrData.modules.data
2566
+ const qrcodesize = size + opts.margin * 2
2567
+
2568
+ const bg = !opts.color.light.a
2569
+ ? ''
2570
+ : '<path ' + getColorAttrib(opts.color.light, 'fill') +
2571
+ ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>'
2572
+
2573
+ const path =
2574
+ '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
2575
+ ' d="' + qrToPath(data, size, opts.margin) + '"/>'
2576
+
2577
+ const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"'
2578
+
2579
+ const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" '
2580
+
2581
+ const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n'
2582
+
2583
+ if (typeof cb === 'function') {
2584
+ cb(null, svgTag)
2585
+ }
2586
+
2587
+ return svgTag
2588
+ }
2589
+
2590
+ };
2591
+
2592
+ modules["renderer/svg.js"] = function(module, exports, require) {
2593
+ const svgTagRenderer = require('./svg-tag')
2594
+
2595
+ exports.render = svgTagRenderer.render
2596
+
2597
+ exports.renderToFile = function renderToFile (path, qrData, options, cb) {
2598
+ if (typeof cb === 'undefined') {
2599
+ cb = options
2600
+ options = undefined
2601
+ }
2602
+
2603
+ const fs = require('fs')
2604
+ const svgTag = exports.render(qrData, options)
2605
+
2606
+ const xmlStr = '<?xml version="1.0" encoding="utf-8"?>' +
2607
+ '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' +
2608
+ svgTag
2609
+
2610
+ fs.writeFile(path, xmlStr, cb)
2611
+ }
2612
+
2613
+ };
2614
+
2615
+ modules["renderer/utf8.js"] = function(module, exports, require) {
2616
+ const Utils = require('./utils')
2617
+
2618
+ const BLOCK_CHAR = {
2619
+ WW: ' ',
2620
+ WB: '▄',
2621
+ BB: '█',
2622
+ BW: '▀'
2623
+ }
2624
+
2625
+ const INVERTED_BLOCK_CHAR = {
2626
+ BB: ' ',
2627
+ BW: '▄',
2628
+ WW: '█',
2629
+ WB: '▀'
2630
+ }
2631
+
2632
+ function getBlockChar (top, bottom, blocks) {
2633
+ if (top && bottom) return blocks.BB
2634
+ if (top && !bottom) return blocks.BW
2635
+ if (!top && bottom) return blocks.WB
2636
+ return blocks.WW
2637
+ }
2638
+
2639
+ exports.render = function (qrData, options, cb) {
2640
+ const opts = Utils.getOptions(options)
2641
+ let blocks = BLOCK_CHAR
2642
+ if (opts.color.dark.hex === '#ffffff' || opts.color.light.hex === '#000000') {
2643
+ blocks = INVERTED_BLOCK_CHAR
2644
+ }
2645
+
2646
+ const size = qrData.modules.size
2647
+ const data = qrData.modules.data
2648
+
2649
+ let output = ''
2650
+ let hMargin = Array(size + (opts.margin * 2) + 1).join(blocks.WW)
2651
+ hMargin = Array((opts.margin / 2) + 1).join(hMargin + '\n')
2652
+
2653
+ const vMargin = Array(opts.margin + 1).join(blocks.WW)
2654
+
2655
+ output += hMargin
2656
+ for (let i = 0; i < size; i += 2) {
2657
+ output += vMargin
2658
+ for (let j = 0; j < size; j++) {
2659
+ const topModule = data[i * size + j]
2660
+ const bottomModule = data[(i + 1) * size + j]
2661
+
2662
+ output += getBlockChar(topModule, bottomModule, blocks)
2663
+ }
2664
+
2665
+ output += vMargin + '\n'
2666
+ }
2667
+
2668
+ output += hMargin.slice(0, -1)
2669
+
2670
+ if (typeof cb === 'function') {
2671
+ cb(null, output)
2672
+ }
2673
+
2674
+ return output
2675
+ }
2676
+
2677
+ exports.renderToFile = function renderToFile (path, qrData, options, cb) {
2678
+ if (typeof cb === 'undefined') {
2679
+ cb = options
2680
+ options = undefined
2681
+ }
2682
+
2683
+ const fs = require('fs')
2684
+ const utf8 = exports.render(qrData, options)
2685
+ fs.writeFile(path, utf8, cb)
2686
+ }
2687
+
2688
+ };
2689
+
2690
+ modules["renderer/utils.js"] = function(module, exports, require) {
2691
+ function hex2rgba (hex) {
2692
+ if (typeof hex === 'number') {
2693
+ hex = hex.toString()
2694
+ }
2695
+
2696
+ if (typeof hex !== 'string') {
2697
+ throw new Error('Color should be defined as hex string')
2698
+ }
2699
+
2700
+ let hexCode = hex.slice().replace('#', '').split('')
2701
+ if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
2702
+ throw new Error('Invalid hex color: ' + hex)
2703
+ }
2704
+
2705
+ // Convert from short to long form (fff -> ffffff)
2706
+ if (hexCode.length === 3 || hexCode.length === 4) {
2707
+ hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
2708
+ return [c, c]
2709
+ }))
2710
+ }
2711
+
2712
+ // Add default alpha value
2713
+ if (hexCode.length === 6) hexCode.push('F', 'F')
2714
+
2715
+ const hexValue = parseInt(hexCode.join(''), 16)
2716
+
2717
+ return {
2718
+ r: (hexValue >> 24) & 255,
2719
+ g: (hexValue >> 16) & 255,
2720
+ b: (hexValue >> 8) & 255,
2721
+ a: hexValue & 255,
2722
+ hex: '#' + hexCode.slice(0, 6).join('')
2723
+ }
2724
+ }
2725
+
2726
+ exports.getOptions = function getOptions (options) {
2727
+ if (!options) options = {}
2728
+ if (!options.color) options.color = {}
2729
+
2730
+ const margin = typeof options.margin === 'undefined' ||
2731
+ options.margin === null ||
2732
+ options.margin < 0
2733
+ ? 4
2734
+ : options.margin
2735
+
2736
+ const width = options.width && options.width >= 21 ? options.width : undefined
2737
+ const scale = options.scale || 4
2738
+
2739
+ return {
2740
+ width: width,
2741
+ scale: width ? 4 : scale,
2742
+ margin: margin,
2743
+ color: {
2744
+ dark: hex2rgba(options.color.dark || '#000000ff'),
2745
+ light: hex2rgba(options.color.light || '#ffffffff')
2746
+ },
2747
+ type: options.type,
2748
+ rendererOpts: options.rendererOpts || {}
2749
+ }
2750
+ }
2751
+
2752
+ exports.getScale = function getScale (qrSize, opts) {
2753
+ return opts.width && opts.width >= qrSize + opts.margin * 2
2754
+ ? opts.width / (qrSize + opts.margin * 2)
2755
+ : opts.scale
2756
+ }
2757
+
2758
+ exports.getImageWidth = function getImageWidth (qrSize, opts) {
2759
+ const scale = exports.getScale(qrSize, opts)
2760
+ return Math.floor((qrSize + opts.margin * 2) * scale)
2761
+ }
2762
+
2763
+ exports.qrToImageData = function qrToImageData (imgData, qr, opts) {
2764
+ const size = qr.modules.size
2765
+ const data = qr.modules.data
2766
+ const scale = exports.getScale(size, opts)
2767
+ const symbolSize = Math.floor((size + opts.margin * 2) * scale)
2768
+ const scaledMargin = opts.margin * scale
2769
+ const palette = [opts.color.light, opts.color.dark]
2770
+
2771
+ for (let i = 0; i < symbolSize; i++) {
2772
+ for (let j = 0; j < symbolSize; j++) {
2773
+ let posDst = (i * symbolSize + j) * 4
2774
+ let pxColor = opts.color.light
2775
+
2776
+ if (i >= scaledMargin && j >= scaledMargin &&
2777
+ i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
2778
+ const iSrc = Math.floor((i - scaledMargin) / scale)
2779
+ const jSrc = Math.floor((j - scaledMargin) / scale)
2780
+ pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0]
2781
+ }
2782
+
2783
+ imgData[posDst++] = pxColor.r
2784
+ imgData[posDst++] = pxColor.g
2785
+ imgData[posDst++] = pxColor.b
2786
+ imgData[posDst] = pxColor.a
2787
+ }
2788
+ }
2789
+ }
2790
+
2791
+ };
2792
+
2793
+ modules["dijkstrajs.js"] = function(module, exports, require) {
2794
+ 'use strict';
2795
+
2796
+ /******************************************************************************
2797
+ * Created 2008-08-19.
2798
+ *
2799
+ * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
2800
+ *
2801
+ * Copyright (C) 2008
2802
+ * Wyatt Baldwin <self@wyattbaldwin.com>
2803
+ * All rights reserved
2804
+ *
2805
+ * Licensed under the MIT license.
2806
+ *
2807
+ * http://www.opensource.org/licenses/mit-license.php
2808
+ *
2809
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
2810
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
2811
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
2812
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2813
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2814
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2815
+ * THE SOFTWARE.
2816
+ *****************************************************************************/
2817
+ var dijkstra = {
2818
+ single_source_shortest_paths: function(graph, s, d) {
2819
+ // Predecessor map for each node that has been encountered.
2820
+ // node ID => predecessor node ID
2821
+ var predecessors = {};
2822
+
2823
+ // Costs of shortest paths from s to all nodes encountered.
2824
+ // node ID => cost
2825
+ var costs = {};
2826
+ costs[s] = 0;
2827
+
2828
+ // Costs of shortest paths from s to all nodes encountered; differs from
2829
+ // `costs` in that it provides easy access to the node that currently has
2830
+ // the known shortest path from s.
2831
+ // XXX: Do we actually need both `costs` and `open`?
2832
+ var open = dijkstra.PriorityQueue.make();
2833
+ open.push(s, 0);
2834
+
2835
+ var closest,
2836
+ u, v,
2837
+ cost_of_s_to_u,
2838
+ adjacent_nodes,
2839
+ cost_of_e,
2840
+ cost_of_s_to_u_plus_cost_of_e,
2841
+ cost_of_s_to_v,
2842
+ first_visit;
2843
+ while (!open.empty()) {
2844
+ // In the nodes remaining in graph that have a known cost from s,
2845
+ // find the node, u, that currently has the shortest path from s.
2846
+ closest = open.pop();
2847
+ u = closest.value;
2848
+ cost_of_s_to_u = closest.cost;
2849
+
2850
+ // Get nodes adjacent to u...
2851
+ adjacent_nodes = graph[u] || {};
2852
+
2853
+ // ...and explore the edges that connect u to those nodes, updating
2854
+ // the cost of the shortest paths to any or all of those nodes as
2855
+ // necessary. v is the node across the current edge from u.
2856
+ for (v in adjacent_nodes) {
2857
+ if (adjacent_nodes.hasOwnProperty(v)) {
2858
+ // Get the cost of the edge running from u to v.
2859
+ cost_of_e = adjacent_nodes[v];
2860
+
2861
+ // Cost of s to u plus the cost of u to v across e--this is *a*
2862
+ // cost from s to v that may or may not be less than the current
2863
+ // known cost to v.
2864
+ cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
2865
+
2866
+ // If we haven't visited v yet OR if the current known cost from s to
2867
+ // v is greater than the new cost we just found (cost of s to u plus
2868
+ // cost of u to v across e), update v's cost in the cost list and
2869
+ // update v's predecessor in the predecessor list (it's now u).
2870
+ cost_of_s_to_v = costs[v];
2871
+ first_visit = (typeof costs[v] === 'undefined');
2872
+ if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
2873
+ costs[v] = cost_of_s_to_u_plus_cost_of_e;
2874
+ open.push(v, cost_of_s_to_u_plus_cost_of_e);
2875
+ predecessors[v] = u;
2876
+ }
2877
+ }
2878
+ }
2879
+ }
2880
+
2881
+ if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
2882
+ var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
2883
+ throw new Error(msg);
2884
+ }
2885
+
2886
+ return predecessors;
2887
+ },
2888
+
2889
+ extract_shortest_path_from_predecessor_list: function(predecessors, d) {
2890
+ var nodes = [];
2891
+ var u = d;
2892
+ var predecessor;
2893
+ while (u) {
2894
+ nodes.push(u);
2895
+ predecessor = predecessors[u];
2896
+ u = predecessors[u];
2897
+ }
2898
+ nodes.reverse();
2899
+ return nodes;
2900
+ },
2901
+
2902
+ find_path: function(graph, s, d) {
2903
+ var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
2904
+ return dijkstra.extract_shortest_path_from_predecessor_list(
2905
+ predecessors, d);
2906
+ },
2907
+
2908
+ /**
2909
+ * A very naive priority queue implementation.
2910
+ */
2911
+ PriorityQueue: {
2912
+ make: function (opts) {
2913
+ var T = dijkstra.PriorityQueue,
2914
+ t = {},
2915
+ key;
2916
+ opts = opts || {};
2917
+ for (key in T) {
2918
+ if (T.hasOwnProperty(key)) {
2919
+ t[key] = T[key];
2920
+ }
2921
+ }
2922
+ t.queue = [];
2923
+ t.sorter = opts.sorter || T.default_sorter;
2924
+ return t;
2925
+ },
2926
+
2927
+ default_sorter: function (a, b) {
2928
+ return a.cost - b.cost;
2929
+ },
2930
+
2931
+ /**
2932
+ * Add a new item to the queue and ensure the highest priority element
2933
+ * is at the front of the queue.
2934
+ */
2935
+ push: function (value, cost) {
2936
+ var item = {value: value, cost: cost};
2937
+ this.queue.push(item);
2938
+ this.queue.sort(this.sorter);
2939
+ },
2940
+
2941
+ /**
2942
+ * Return the highest priority element in the queue.
2943
+ */
2944
+ pop: function () {
2945
+ return this.queue.shift();
2946
+ },
2947
+
2948
+ empty: function () {
2949
+ return this.queue.length === 0;
2950
+ }
2951
+ }
2952
+ };
2953
+
2954
+
2955
+ // node.js module exports
2956
+ if (typeof module !== 'undefined') {
2957
+ module.exports = dijkstra;
2958
+ }
2959
+
2960
+ };
2961
+
2962
+ export function renderQrSvg(text, options = {}) {
2963
+ const SvgRenderer = requireMod("browser.js", "./renderer/svg-tag");
2964
+ const QRCode = requireMod("browser.js", "./core/qrcode");
2965
+ const data = QRCode.create(text, options);
2966
+ return SvgRenderer.render(data, options);
2967
+ }
2968
+
2969
+ if (typeof window !== "undefined") {
2970
+ window.renderQrSvg = renderQrSvg;
2971
+ }