@bounded-sh/client 0.0.1

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.
Files changed (65) hide show
  1. package/README.md +298 -0
  2. package/dist/auth/hooks/useAuth.d.ts +8 -0
  3. package/dist/auth/index.d.ts +73 -0
  4. package/dist/auth/oidc-auth.d.ts +27 -0
  5. package/dist/auth/providers/email-auth-provider.d.ts +38 -0
  6. package/dist/auth/providers/guest-auth-provider.d.ts +14 -0
  7. package/dist/auth/providers/guest-keystore.d.ts +12 -0
  8. package/dist/auth/providers/mock-auth-provider.d.ts +49 -0
  9. package/dist/auth/providers/offchain-auth-provider.d.ts +56 -0
  10. package/dist/auth/providers/phantom-wallet-provider.d.ts +117 -0
  11. package/dist/auth/providers/privy-expo-provider.d.ts +115 -0
  12. package/dist/auth/providers/privy-wallet-provider.d.ts +80 -0
  13. package/dist/auth/providers/sol/sol-utils.d.ts +2 -0
  14. package/dist/auth/providers/solana-mobile-wallet-provider.d.ts +155 -0
  15. package/dist/auth/providers/transaction-utils.d.ts +10 -0
  16. package/dist/global.d.ts +13 -0
  17. package/dist/index-BHTfW8CV.esm.js +16091 -0
  18. package/dist/index-BHTfW8CV.esm.js.map +1 -0
  19. package/dist/index-C1VOdmRN.js +16130 -0
  20. package/dist/index-C1VOdmRN.js.map +1 -0
  21. package/dist/index-CT2j1oic.esm.js +16089 -0
  22. package/dist/index-CT2j1oic.esm.js.map +1 -0
  23. package/dist/index-VGx-869x.js +23572 -0
  24. package/dist/index-VGx-869x.js.map +1 -0
  25. package/dist/index-o5Hv9pfS.esm.js +23456 -0
  26. package/dist/index-o5Hv9pfS.esm.js.map +1 -0
  27. package/dist/index-sKqrgk0t.js +16132 -0
  28. package/dist/index-sKqrgk0t.js.map +1 -0
  29. package/dist/index.browser-BJZ7fYwv.js +5081 -0
  30. package/dist/index.browser-BJZ7fYwv.js.map +1 -0
  31. package/dist/index.browser-DaNhOhkQ.esm.js +4220 -0
  32. package/dist/index.browser-DaNhOhkQ.esm.js.map +1 -0
  33. package/dist/index.browser-DhAcjdpV.esm.js +5071 -0
  34. package/dist/index.browser-DhAcjdpV.esm.js.map +1 -0
  35. package/dist/index.browser-utVKQsEC.js +4225 -0
  36. package/dist/index.browser-utVKQsEC.js.map +1 -0
  37. package/dist/index.d.ts +21 -0
  38. package/dist/index.esm.js +8 -0
  39. package/dist/index.esm.js.map +1 -0
  40. package/dist/index.js +105 -0
  41. package/dist/index.js.map +1 -0
  42. package/dist/index.native-B5IBOdv_.js +19684 -0
  43. package/dist/index.native-B5IBOdv_.js.map +1 -0
  44. package/dist/index.native-JPUkdHJj.esm.js +19565 -0
  45. package/dist/index.native-JPUkdHJj.esm.js.map +1 -0
  46. package/dist/index.native.d.ts +26 -0
  47. package/dist/index.native.esm.js +6 -0
  48. package/dist/index.native.esm.js.map +1 -0
  49. package/dist/index.native.js +98 -0
  50. package/dist/index.native.js.map +1 -0
  51. package/dist/phantom-wallet-provider-CDLyxrih.js +1466 -0
  52. package/dist/phantom-wallet-provider-CDLyxrih.js.map +1 -0
  53. package/dist/phantom-wallet-provider-DMlaSrAl.esm.js +1445 -0
  54. package/dist/phantom-wallet-provider-DMlaSrAl.esm.js.map +1 -0
  55. package/dist/platform.d.ts +81 -0
  56. package/dist/privy-wallet-provider-DiHHTDbZ.js +956 -0
  57. package/dist/privy-wallet-provider-DiHHTDbZ.js.map +1 -0
  58. package/dist/privy-wallet-provider-nR52lXzI.esm.js +933 -0
  59. package/dist/privy-wallet-provider-nR52lXzI.esm.js.map +1 -0
  60. package/dist/solana-mobile-wallet-provider-B4CeMMQd.esm.js +1460 -0
  61. package/dist/solana-mobile-wallet-provider-B4CeMMQd.esm.js.map +1 -0
  62. package/dist/solana-mobile-wallet-provider-BYMfFjZb.js +1481 -0
  63. package/dist/solana-mobile-wallet-provider-BYMfFjZb.js.map +1 -0
  64. package/dist/utils.d.ts +1 -0
  65. package/package.json +100 -0
@@ -0,0 +1,4220 @@
1
+ import { startScenario, SolanaMobileWalletAdapterError, SolanaMobileWalletAdapterErrorCode } from '@solana-mobile/mobile-wallet-adapter-protocol';
2
+ import { o as base58 } from './index.native-JPUkdHJj.esm.js';
3
+ import 'axios';
4
+ import '@solana/web3.js';
5
+ import '@coral-xyz/anchor';
6
+ import 'react';
7
+
8
+ /** Name of the feature. */
9
+ const SolanaSignAndSendTransaction = 'solana:signAndSendTransaction';
10
+
11
+ /** Name of the feature. */
12
+ const SolanaSignIn = 'solana:signIn';
13
+
14
+ /** Name of the feature. */
15
+ const SolanaSignMessage = 'solana:signMessage';
16
+
17
+ /** Name of the feature. */
18
+ const SolanaSignTransaction = 'solana:signTransaction';
19
+
20
+ /** Name of the feature. */
21
+ const StandardConnect = 'standard:connect';
22
+
23
+ /** Name of the feature. */
24
+ const StandardDisconnect = 'standard:disconnect';
25
+
26
+ /** Name of the feature. */
27
+ const StandardEvents = 'standard:events';
28
+
29
+ var browser = {};
30
+
31
+ var canPromise;
32
+ var hasRequiredCanPromise;
33
+
34
+ function requireCanPromise () {
35
+ if (hasRequiredCanPromise) return canPromise;
36
+ hasRequiredCanPromise = 1;
37
+ // can-promise has a crash in some versions of react native that dont have
38
+ // standard global objects
39
+ // https://github.com/soldair/node-qrcode/issues/157
40
+
41
+ canPromise = function () {
42
+ return typeof Promise === 'function' && Promise.prototype && Promise.prototype.then
43
+ };
44
+ return canPromise;
45
+ }
46
+
47
+ var qrcode = {};
48
+
49
+ var utils$1 = {};
50
+
51
+ var hasRequiredUtils$1;
52
+
53
+ function requireUtils$1 () {
54
+ if (hasRequiredUtils$1) return utils$1;
55
+ hasRequiredUtils$1 = 1;
56
+ let toSJISFunction;
57
+ const CODEWORDS_COUNT = [
58
+ 0, // Not used
59
+ 26, 44, 70, 100, 134, 172, 196, 242, 292, 346,
60
+ 404, 466, 532, 581, 655, 733, 815, 901, 991, 1085,
61
+ 1156, 1258, 1364, 1474, 1588, 1706, 1828, 1921, 2051, 2185,
62
+ 2323, 2465, 2611, 2761, 2876, 3034, 3196, 3362, 3532, 3706
63
+ ];
64
+
65
+ /**
66
+ * Returns the QR Code size for the specified version
67
+ *
68
+ * @param {Number} version QR Code version
69
+ * @return {Number} size of QR code
70
+ */
71
+ utils$1.getSymbolSize = function getSymbolSize (version) {
72
+ if (!version) throw new Error('"version" cannot be null or undefined')
73
+ if (version < 1 || version > 40) throw new Error('"version" should be in range from 1 to 40')
74
+ return version * 4 + 17
75
+ };
76
+
77
+ /**
78
+ * Returns the total number of codewords used to store data and EC information.
79
+ *
80
+ * @param {Number} version QR Code version
81
+ * @return {Number} Data length in bits
82
+ */
83
+ utils$1.getSymbolTotalCodewords = function getSymbolTotalCodewords (version) {
84
+ return CODEWORDS_COUNT[version]
85
+ };
86
+
87
+ /**
88
+ * Encode data with Bose-Chaudhuri-Hocquenghem
89
+ *
90
+ * @param {Number} data Value to encode
91
+ * @return {Number} Encoded value
92
+ */
93
+ utils$1.getBCHDigit = function (data) {
94
+ let digit = 0;
95
+
96
+ while (data !== 0) {
97
+ digit++;
98
+ data >>>= 1;
99
+ }
100
+
101
+ return digit
102
+ };
103
+
104
+ utils$1.setToSJISFunction = function setToSJISFunction (f) {
105
+ if (typeof f !== 'function') {
106
+ throw new Error('"toSJISFunc" is not a valid function.')
107
+ }
108
+
109
+ toSJISFunction = f;
110
+ };
111
+
112
+ utils$1.isKanjiModeEnabled = function () {
113
+ return typeof toSJISFunction !== 'undefined'
114
+ };
115
+
116
+ utils$1.toSJIS = function toSJIS (kanji) {
117
+ return toSJISFunction(kanji)
118
+ };
119
+ return utils$1;
120
+ }
121
+
122
+ var errorCorrectionLevel = {};
123
+
124
+ var hasRequiredErrorCorrectionLevel;
125
+
126
+ function requireErrorCorrectionLevel () {
127
+ if (hasRequiredErrorCorrectionLevel) return errorCorrectionLevel;
128
+ hasRequiredErrorCorrectionLevel = 1;
129
+ (function (exports$1) {
130
+ exports$1.L = { bit: 1 };
131
+ exports$1.M = { bit: 0 };
132
+ exports$1.Q = { bit: 3 };
133
+ exports$1.H = { bit: 2 };
134
+
135
+ function fromString (string) {
136
+ if (typeof string !== 'string') {
137
+ throw new Error('Param is not a string')
138
+ }
139
+
140
+ const lcStr = string.toLowerCase();
141
+
142
+ switch (lcStr) {
143
+ case 'l':
144
+ case 'low':
145
+ return exports$1.L
146
+
147
+ case 'm':
148
+ case 'medium':
149
+ return exports$1.M
150
+
151
+ case 'q':
152
+ case 'quartile':
153
+ return exports$1.Q
154
+
155
+ case 'h':
156
+ case 'high':
157
+ return exports$1.H
158
+
159
+ default:
160
+ throw new Error('Unknown EC Level: ' + string)
161
+ }
162
+ }
163
+
164
+ exports$1.isValid = function isValid (level) {
165
+ return level && typeof level.bit !== 'undefined' &&
166
+ level.bit >= 0 && level.bit < 4
167
+ };
168
+
169
+ exports$1.from = function from (value, defaultValue) {
170
+ if (exports$1.isValid(value)) {
171
+ return value
172
+ }
173
+
174
+ try {
175
+ return fromString(value)
176
+ } catch (e) {
177
+ return defaultValue
178
+ }
179
+ };
180
+ } (errorCorrectionLevel));
181
+ return errorCorrectionLevel;
182
+ }
183
+
184
+ var bitBuffer;
185
+ var hasRequiredBitBuffer;
186
+
187
+ function requireBitBuffer () {
188
+ if (hasRequiredBitBuffer) return bitBuffer;
189
+ hasRequiredBitBuffer = 1;
190
+ function BitBuffer () {
191
+ this.buffer = [];
192
+ this.length = 0;
193
+ }
194
+
195
+ BitBuffer.prototype = {
196
+
197
+ get: function (index) {
198
+ const bufIndex = Math.floor(index / 8);
199
+ return ((this.buffer[bufIndex] >>> (7 - index % 8)) & 1) === 1
200
+ },
201
+
202
+ put: function (num, length) {
203
+ for (let i = 0; i < length; i++) {
204
+ this.putBit(((num >>> (length - i - 1)) & 1) === 1);
205
+ }
206
+ },
207
+
208
+ getLengthInBits: function () {
209
+ return this.length
210
+ },
211
+
212
+ putBit: function (bit) {
213
+ const bufIndex = Math.floor(this.length / 8);
214
+ if (this.buffer.length <= bufIndex) {
215
+ this.buffer.push(0);
216
+ }
217
+
218
+ if (bit) {
219
+ this.buffer[bufIndex] |= (0x80 >>> (this.length % 8));
220
+ }
221
+
222
+ this.length++;
223
+ }
224
+ };
225
+
226
+ bitBuffer = BitBuffer;
227
+ return bitBuffer;
228
+ }
229
+
230
+ /**
231
+ * Helper class to handle QR Code symbol modules
232
+ *
233
+ * @param {Number} size Symbol size
234
+ */
235
+
236
+ var bitMatrix;
237
+ var hasRequiredBitMatrix;
238
+
239
+ function requireBitMatrix () {
240
+ if (hasRequiredBitMatrix) return bitMatrix;
241
+ hasRequiredBitMatrix = 1;
242
+ function BitMatrix (size) {
243
+ if (!size || size < 1) {
244
+ throw new Error('BitMatrix size must be defined and greater than 0')
245
+ }
246
+
247
+ this.size = size;
248
+ this.data = new Uint8Array(size * size);
249
+ this.reservedBit = new Uint8Array(size * size);
250
+ }
251
+
252
+ /**
253
+ * Set bit value at specified location
254
+ * If reserved flag is set, this bit will be ignored during masking process
255
+ *
256
+ * @param {Number} row
257
+ * @param {Number} col
258
+ * @param {Boolean} value
259
+ * @param {Boolean} reserved
260
+ */
261
+ BitMatrix.prototype.set = function (row, col, value, reserved) {
262
+ const index = row * this.size + col;
263
+ this.data[index] = value;
264
+ if (reserved) this.reservedBit[index] = true;
265
+ };
266
+
267
+ /**
268
+ * Returns bit value at specified location
269
+ *
270
+ * @param {Number} row
271
+ * @param {Number} col
272
+ * @return {Boolean}
273
+ */
274
+ BitMatrix.prototype.get = function (row, col) {
275
+ return this.data[row * this.size + col]
276
+ };
277
+
278
+ /**
279
+ * Applies xor operator at specified location
280
+ * (used during masking process)
281
+ *
282
+ * @param {Number} row
283
+ * @param {Number} col
284
+ * @param {Boolean} value
285
+ */
286
+ BitMatrix.prototype.xor = function (row, col, value) {
287
+ this.data[row * this.size + col] ^= value;
288
+ };
289
+
290
+ /**
291
+ * Check if bit at specified location is reserved
292
+ *
293
+ * @param {Number} row
294
+ * @param {Number} col
295
+ * @return {Boolean}
296
+ */
297
+ BitMatrix.prototype.isReserved = function (row, col) {
298
+ return this.reservedBit[row * this.size + col]
299
+ };
300
+
301
+ bitMatrix = BitMatrix;
302
+ return bitMatrix;
303
+ }
304
+
305
+ var alignmentPattern = {};
306
+
307
+ /**
308
+ * Alignment pattern are fixed reference pattern in defined positions
309
+ * in a matrix symbology, which enables the decode software to re-synchronise
310
+ * the coordinate mapping of the image modules in the event of moderate amounts
311
+ * of distortion of the image.
312
+ *
313
+ * Alignment patterns are present only in QR Code symbols of version 2 or larger
314
+ * and their number depends on the symbol version.
315
+ */
316
+
317
+ var hasRequiredAlignmentPattern;
318
+
319
+ function requireAlignmentPattern () {
320
+ if (hasRequiredAlignmentPattern) return alignmentPattern;
321
+ hasRequiredAlignmentPattern = 1;
322
+ (function (exports$1) {
323
+ const getSymbolSize = requireUtils$1().getSymbolSize;
324
+
325
+ /**
326
+ * Calculate the row/column coordinates of the center module of each alignment pattern
327
+ * for the specified QR Code version.
328
+ *
329
+ * The alignment patterns are positioned symmetrically on either side of the diagonal
330
+ * running from the top left corner of the symbol to the bottom right corner.
331
+ *
332
+ * Since positions are simmetrical only half of the coordinates are returned.
333
+ * Each item of the array will represent in turn the x and y coordinate.
334
+ * @see {@link getPositions}
335
+ *
336
+ * @param {Number} version QR Code version
337
+ * @return {Array} Array of coordinate
338
+ */
339
+ exports$1.getRowColCoords = function getRowColCoords (version) {
340
+ if (version === 1) return []
341
+
342
+ const posCount = Math.floor(version / 7) + 2;
343
+ const size = getSymbolSize(version);
344
+ const intervals = size === 145 ? 26 : Math.ceil((size - 13) / (2 * posCount - 2)) * 2;
345
+ const positions = [size - 7]; // Last coord is always (size - 7)
346
+
347
+ for (let i = 1; i < posCount - 1; i++) {
348
+ positions[i] = positions[i - 1] - intervals;
349
+ }
350
+
351
+ positions.push(6); // First coord is always 6
352
+
353
+ return positions.reverse()
354
+ };
355
+
356
+ /**
357
+ * Returns an array containing the positions of each alignment pattern.
358
+ * Each array's element represent the center point of the pattern as (x, y) coordinates
359
+ *
360
+ * Coordinates are calculated expanding the row/column coordinates returned by {@link getRowColCoords}
361
+ * and filtering out the items that overlaps with finder pattern
362
+ *
363
+ * @example
364
+ * For a Version 7 symbol {@link getRowColCoords} returns values 6, 22 and 38.
365
+ * The alignment patterns, therefore, are to be centered on (row, column)
366
+ * positions (6,22), (22,6), (22,22), (22,38), (38,22), (38,38).
367
+ * Note that the coordinates (6,6), (6,38), (38,6) are occupied by finder patterns
368
+ * and are not therefore used for alignment patterns.
369
+ *
370
+ * let pos = getPositions(7)
371
+ * // [[6,22], [22,6], [22,22], [22,38], [38,22], [38,38]]
372
+ *
373
+ * @param {Number} version QR Code version
374
+ * @return {Array} Array of coordinates
375
+ */
376
+ exports$1.getPositions = function getPositions (version) {
377
+ const coords = [];
378
+ const pos = exports$1.getRowColCoords(version);
379
+ const posLength = pos.length;
380
+
381
+ for (let i = 0; i < posLength; i++) {
382
+ for (let j = 0; j < posLength; j++) {
383
+ // Skip if position is occupied by finder patterns
384
+ if ((i === 0 && j === 0) || // top-left
385
+ (i === 0 && j === posLength - 1) || // bottom-left
386
+ (i === posLength - 1 && j === 0)) { // top-right
387
+ continue
388
+ }
389
+
390
+ coords.push([pos[i], pos[j]]);
391
+ }
392
+ }
393
+
394
+ return coords
395
+ };
396
+ } (alignmentPattern));
397
+ return alignmentPattern;
398
+ }
399
+
400
+ var finderPattern = {};
401
+
402
+ var hasRequiredFinderPattern;
403
+
404
+ function requireFinderPattern () {
405
+ if (hasRequiredFinderPattern) return finderPattern;
406
+ hasRequiredFinderPattern = 1;
407
+ const getSymbolSize = requireUtils$1().getSymbolSize;
408
+ const FINDER_PATTERN_SIZE = 7;
409
+
410
+ /**
411
+ * Returns an array containing the positions of each finder pattern.
412
+ * Each array's element represent the top-left point of the pattern as (x, y) coordinates
413
+ *
414
+ * @param {Number} version QR Code version
415
+ * @return {Array} Array of coordinates
416
+ */
417
+ finderPattern.getPositions = function getPositions (version) {
418
+ const size = getSymbolSize(version);
419
+
420
+ return [
421
+ // top-left
422
+ [0, 0],
423
+ // top-right
424
+ [size - FINDER_PATTERN_SIZE, 0],
425
+ // bottom-left
426
+ [0, size - FINDER_PATTERN_SIZE]
427
+ ]
428
+ };
429
+ return finderPattern;
430
+ }
431
+
432
+ var maskPattern = {};
433
+
434
+ /**
435
+ * Data mask pattern reference
436
+ * @type {Object}
437
+ */
438
+
439
+ var hasRequiredMaskPattern;
440
+
441
+ function requireMaskPattern () {
442
+ if (hasRequiredMaskPattern) return maskPattern;
443
+ hasRequiredMaskPattern = 1;
444
+ (function (exports$1) {
445
+ exports$1.Patterns = {
446
+ PATTERN000: 0,
447
+ PATTERN001: 1,
448
+ PATTERN010: 2,
449
+ PATTERN011: 3,
450
+ PATTERN100: 4,
451
+ PATTERN101: 5,
452
+ PATTERN110: 6,
453
+ PATTERN111: 7
454
+ };
455
+
456
+ /**
457
+ * Weighted penalty scores for the undesirable features
458
+ * @type {Object}
459
+ */
460
+ const PenaltyScores = {
461
+ N1: 3,
462
+ N2: 3,
463
+ N3: 40,
464
+ N4: 10
465
+ };
466
+
467
+ /**
468
+ * Check if mask pattern value is valid
469
+ *
470
+ * @param {Number} mask Mask pattern
471
+ * @return {Boolean} true if valid, false otherwise
472
+ */
473
+ exports$1.isValid = function isValid (mask) {
474
+ return mask != null && mask !== '' && !isNaN(mask) && mask >= 0 && mask <= 7
475
+ };
476
+
477
+ /**
478
+ * Returns mask pattern from a value.
479
+ * If value is not valid, returns undefined
480
+ *
481
+ * @param {Number|String} value Mask pattern value
482
+ * @return {Number} Valid mask pattern or undefined
483
+ */
484
+ exports$1.from = function from (value) {
485
+ return exports$1.isValid(value) ? parseInt(value, 10) : undefined
486
+ };
487
+
488
+ /**
489
+ * Find adjacent modules in row/column with the same color
490
+ * and assign a penalty value.
491
+ *
492
+ * Points: N1 + i
493
+ * i is the amount by which the number of adjacent modules of the same color exceeds 5
494
+ */
495
+ exports$1.getPenaltyN1 = function getPenaltyN1 (data) {
496
+ const size = data.size;
497
+ let points = 0;
498
+ let sameCountCol = 0;
499
+ let sameCountRow = 0;
500
+ let lastCol = null;
501
+ let lastRow = null;
502
+
503
+ for (let row = 0; row < size; row++) {
504
+ sameCountCol = sameCountRow = 0;
505
+ lastCol = lastRow = null;
506
+
507
+ for (let col = 0; col < size; col++) {
508
+ let module = data.get(row, col);
509
+ if (module === lastCol) {
510
+ sameCountCol++;
511
+ } else {
512
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
513
+ lastCol = module;
514
+ sameCountCol = 1;
515
+ }
516
+
517
+ module = data.get(col, row);
518
+ if (module === lastRow) {
519
+ sameCountRow++;
520
+ } else {
521
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
522
+ lastRow = module;
523
+ sameCountRow = 1;
524
+ }
525
+ }
526
+
527
+ if (sameCountCol >= 5) points += PenaltyScores.N1 + (sameCountCol - 5);
528
+ if (sameCountRow >= 5) points += PenaltyScores.N1 + (sameCountRow - 5);
529
+ }
530
+
531
+ return points
532
+ };
533
+
534
+ /**
535
+ * Find 2x2 blocks with the same color and assign a penalty value
536
+ *
537
+ * Points: N2 * (m - 1) * (n - 1)
538
+ */
539
+ exports$1.getPenaltyN2 = function getPenaltyN2 (data) {
540
+ const size = data.size;
541
+ let points = 0;
542
+
543
+ for (let row = 0; row < size - 1; row++) {
544
+ for (let col = 0; col < size - 1; col++) {
545
+ const last = data.get(row, col) +
546
+ data.get(row, col + 1) +
547
+ data.get(row + 1, col) +
548
+ data.get(row + 1, col + 1);
549
+
550
+ if (last === 4 || last === 0) points++;
551
+ }
552
+ }
553
+
554
+ return points * PenaltyScores.N2
555
+ };
556
+
557
+ /**
558
+ * Find 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column,
559
+ * preceded or followed by light area 4 modules wide
560
+ *
561
+ * Points: N3 * number of pattern found
562
+ */
563
+ exports$1.getPenaltyN3 = function getPenaltyN3 (data) {
564
+ const size = data.size;
565
+ let points = 0;
566
+ let bitsCol = 0;
567
+ let bitsRow = 0;
568
+
569
+ for (let row = 0; row < size; row++) {
570
+ bitsCol = bitsRow = 0;
571
+ for (let col = 0; col < size; col++) {
572
+ bitsCol = ((bitsCol << 1) & 0x7FF) | data.get(row, col);
573
+ if (col >= 10 && (bitsCol === 0x5D0 || bitsCol === 0x05D)) points++;
574
+
575
+ bitsRow = ((bitsRow << 1) & 0x7FF) | data.get(col, row);
576
+ if (col >= 10 && (bitsRow === 0x5D0 || bitsRow === 0x05D)) points++;
577
+ }
578
+ }
579
+
580
+ return points * PenaltyScores.N3
581
+ };
582
+
583
+ /**
584
+ * Calculate proportion of dark modules in entire symbol
585
+ *
586
+ * Points: N4 * k
587
+ *
588
+ * k is the rating of the deviation of the proportion of dark modules
589
+ * in the symbol from 50% in steps of 5%
590
+ */
591
+ exports$1.getPenaltyN4 = function getPenaltyN4 (data) {
592
+ let darkCount = 0;
593
+ const modulesCount = data.data.length;
594
+
595
+ for (let i = 0; i < modulesCount; i++) darkCount += data.data[i];
596
+
597
+ const k = Math.abs(Math.ceil((darkCount * 100 / modulesCount) / 5) - 10);
598
+
599
+ return k * PenaltyScores.N4
600
+ };
601
+
602
+ /**
603
+ * Return mask value at given position
604
+ *
605
+ * @param {Number} maskPattern Pattern reference value
606
+ * @param {Number} i Row
607
+ * @param {Number} j Column
608
+ * @return {Boolean} Mask value
609
+ */
610
+ function getMaskAt (maskPattern, i, j) {
611
+ switch (maskPattern) {
612
+ case exports$1.Patterns.PATTERN000: return (i + j) % 2 === 0
613
+ case exports$1.Patterns.PATTERN001: return i % 2 === 0
614
+ case exports$1.Patterns.PATTERN010: return j % 3 === 0
615
+ case exports$1.Patterns.PATTERN011: return (i + j) % 3 === 0
616
+ case exports$1.Patterns.PATTERN100: return (Math.floor(i / 2) + Math.floor(j / 3)) % 2 === 0
617
+ case exports$1.Patterns.PATTERN101: return (i * j) % 2 + (i * j) % 3 === 0
618
+ case exports$1.Patterns.PATTERN110: return ((i * j) % 2 + (i * j) % 3) % 2 === 0
619
+ case exports$1.Patterns.PATTERN111: return ((i * j) % 3 + (i + j) % 2) % 2 === 0
620
+
621
+ default: throw new Error('bad maskPattern:' + maskPattern)
622
+ }
623
+ }
624
+
625
+ /**
626
+ * Apply a mask pattern to a BitMatrix
627
+ *
628
+ * @param {Number} pattern Pattern reference number
629
+ * @param {BitMatrix} data BitMatrix data
630
+ */
631
+ exports$1.applyMask = function applyMask (pattern, data) {
632
+ const size = data.size;
633
+
634
+ for (let col = 0; col < size; col++) {
635
+ for (let row = 0; row < size; row++) {
636
+ if (data.isReserved(row, col)) continue
637
+ data.xor(row, col, getMaskAt(pattern, row, col));
638
+ }
639
+ }
640
+ };
641
+
642
+ /**
643
+ * Returns the best mask pattern for data
644
+ *
645
+ * @param {BitMatrix} data
646
+ * @return {Number} Mask pattern reference number
647
+ */
648
+ exports$1.getBestMask = function getBestMask (data, setupFormatFunc) {
649
+ const numPatterns = Object.keys(exports$1.Patterns).length;
650
+ let bestPattern = 0;
651
+ let lowerPenalty = Infinity;
652
+
653
+ for (let p = 0; p < numPatterns; p++) {
654
+ setupFormatFunc(p);
655
+ exports$1.applyMask(p, data);
656
+
657
+ // Calculate penalty
658
+ const penalty =
659
+ exports$1.getPenaltyN1(data) +
660
+ exports$1.getPenaltyN2(data) +
661
+ exports$1.getPenaltyN3(data) +
662
+ exports$1.getPenaltyN4(data);
663
+
664
+ // Undo previously applied mask
665
+ exports$1.applyMask(p, data);
666
+
667
+ if (penalty < lowerPenalty) {
668
+ lowerPenalty = penalty;
669
+ bestPattern = p;
670
+ }
671
+ }
672
+
673
+ return bestPattern
674
+ };
675
+ } (maskPattern));
676
+ return maskPattern;
677
+ }
678
+
679
+ var errorCorrectionCode = {};
680
+
681
+ var hasRequiredErrorCorrectionCode;
682
+
683
+ function requireErrorCorrectionCode () {
684
+ if (hasRequiredErrorCorrectionCode) return errorCorrectionCode;
685
+ hasRequiredErrorCorrectionCode = 1;
686
+ const ECLevel = requireErrorCorrectionLevel();
687
+
688
+ const EC_BLOCKS_TABLE = [
689
+ // L M Q H
690
+ 1, 1, 1, 1,
691
+ 1, 1, 1, 1,
692
+ 1, 1, 2, 2,
693
+ 1, 2, 2, 4,
694
+ 1, 2, 4, 4,
695
+ 2, 4, 4, 4,
696
+ 2, 4, 6, 5,
697
+ 2, 4, 6, 6,
698
+ 2, 5, 8, 8,
699
+ 4, 5, 8, 8,
700
+ 4, 5, 8, 11,
701
+ 4, 8, 10, 11,
702
+ 4, 9, 12, 16,
703
+ 4, 9, 16, 16,
704
+ 6, 10, 12, 18,
705
+ 6, 10, 17, 16,
706
+ 6, 11, 16, 19,
707
+ 6, 13, 18, 21,
708
+ 7, 14, 21, 25,
709
+ 8, 16, 20, 25,
710
+ 8, 17, 23, 25,
711
+ 9, 17, 23, 34,
712
+ 9, 18, 25, 30,
713
+ 10, 20, 27, 32,
714
+ 12, 21, 29, 35,
715
+ 12, 23, 34, 37,
716
+ 12, 25, 34, 40,
717
+ 13, 26, 35, 42,
718
+ 14, 28, 38, 45,
719
+ 15, 29, 40, 48,
720
+ 16, 31, 43, 51,
721
+ 17, 33, 45, 54,
722
+ 18, 35, 48, 57,
723
+ 19, 37, 51, 60,
724
+ 19, 38, 53, 63,
725
+ 20, 40, 56, 66,
726
+ 21, 43, 59, 70,
727
+ 22, 45, 62, 74,
728
+ 24, 47, 65, 77,
729
+ 25, 49, 68, 81
730
+ ];
731
+
732
+ const EC_CODEWORDS_TABLE = [
733
+ // L M Q H
734
+ 7, 10, 13, 17,
735
+ 10, 16, 22, 28,
736
+ 15, 26, 36, 44,
737
+ 20, 36, 52, 64,
738
+ 26, 48, 72, 88,
739
+ 36, 64, 96, 112,
740
+ 40, 72, 108, 130,
741
+ 48, 88, 132, 156,
742
+ 60, 110, 160, 192,
743
+ 72, 130, 192, 224,
744
+ 80, 150, 224, 264,
745
+ 96, 176, 260, 308,
746
+ 104, 198, 288, 352,
747
+ 120, 216, 320, 384,
748
+ 132, 240, 360, 432,
749
+ 144, 280, 408, 480,
750
+ 168, 308, 448, 532,
751
+ 180, 338, 504, 588,
752
+ 196, 364, 546, 650,
753
+ 224, 416, 600, 700,
754
+ 224, 442, 644, 750,
755
+ 252, 476, 690, 816,
756
+ 270, 504, 750, 900,
757
+ 300, 560, 810, 960,
758
+ 312, 588, 870, 1050,
759
+ 336, 644, 952, 1110,
760
+ 360, 700, 1020, 1200,
761
+ 390, 728, 1050, 1260,
762
+ 420, 784, 1140, 1350,
763
+ 450, 812, 1200, 1440,
764
+ 480, 868, 1290, 1530,
765
+ 510, 924, 1350, 1620,
766
+ 540, 980, 1440, 1710,
767
+ 570, 1036, 1530, 1800,
768
+ 570, 1064, 1590, 1890,
769
+ 600, 1120, 1680, 1980,
770
+ 630, 1204, 1770, 2100,
771
+ 660, 1260, 1860, 2220,
772
+ 720, 1316, 1950, 2310,
773
+ 750, 1372, 2040, 2430
774
+ ];
775
+
776
+ /**
777
+ * Returns the number of error correction block that the QR Code should contain
778
+ * for the specified version and error correction level.
779
+ *
780
+ * @param {Number} version QR Code version
781
+ * @param {Number} errorCorrectionLevel Error correction level
782
+ * @return {Number} Number of error correction blocks
783
+ */
784
+ errorCorrectionCode.getBlocksCount = function getBlocksCount (version, errorCorrectionLevel) {
785
+ switch (errorCorrectionLevel) {
786
+ case ECLevel.L:
787
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 0]
788
+ case ECLevel.M:
789
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 1]
790
+ case ECLevel.Q:
791
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 2]
792
+ case ECLevel.H:
793
+ return EC_BLOCKS_TABLE[(version - 1) * 4 + 3]
794
+ default:
795
+ return undefined
796
+ }
797
+ };
798
+
799
+ /**
800
+ * Returns the number of error correction codewords to use for the specified
801
+ * version and error correction level.
802
+ *
803
+ * @param {Number} version QR Code version
804
+ * @param {Number} errorCorrectionLevel Error correction level
805
+ * @return {Number} Number of error correction codewords
806
+ */
807
+ errorCorrectionCode.getTotalCodewordsCount = function getTotalCodewordsCount (version, errorCorrectionLevel) {
808
+ switch (errorCorrectionLevel) {
809
+ case ECLevel.L:
810
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 0]
811
+ case ECLevel.M:
812
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 1]
813
+ case ECLevel.Q:
814
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 2]
815
+ case ECLevel.H:
816
+ return EC_CODEWORDS_TABLE[(version - 1) * 4 + 3]
817
+ default:
818
+ return undefined
819
+ }
820
+ };
821
+ return errorCorrectionCode;
822
+ }
823
+
824
+ var polynomial = {};
825
+
826
+ var galoisField = {};
827
+
828
+ var hasRequiredGaloisField;
829
+
830
+ function requireGaloisField () {
831
+ if (hasRequiredGaloisField) return galoisField;
832
+ hasRequiredGaloisField = 1;
833
+ const EXP_TABLE = new Uint8Array(512);
834
+ const LOG_TABLE = new Uint8Array(256)
835
+ /**
836
+ * Precompute the log and anti-log tables for faster computation later
837
+ *
838
+ * For each possible value in the galois field 2^8, we will pre-compute
839
+ * the logarithm and anti-logarithm (exponential) of this value
840
+ *
841
+ * ref {@link https://en.wikiversity.org/wiki/Reed%E2%80%93Solomon_codes_for_coders#Introduction_to_mathematical_fields}
842
+ */
843
+ ;(function initTables () {
844
+ let x = 1;
845
+ for (let i = 0; i < 255; i++) {
846
+ EXP_TABLE[i] = x;
847
+ LOG_TABLE[x] = i;
848
+
849
+ x <<= 1; // multiply by 2
850
+
851
+ // The QR code specification says to use byte-wise modulo 100011101 arithmetic.
852
+ // This means that when a number is 256 or larger, it should be XORed with 0x11D.
853
+ if (x & 0x100) { // similar to x >= 256, but a lot faster (because 0x100 == 256)
854
+ x ^= 0x11D;
855
+ }
856
+ }
857
+
858
+ // Optimization: double the size of the anti-log table so that we don't need to mod 255 to
859
+ // stay inside the bounds (because we will mainly use this table for the multiplication of
860
+ // two GF numbers, no more).
861
+ // @see {@link mul}
862
+ for (let i = 255; i < 512; i++) {
863
+ EXP_TABLE[i] = EXP_TABLE[i - 255];
864
+ }
865
+ }());
866
+
867
+ /**
868
+ * Returns log value of n inside Galois Field
869
+ *
870
+ * @param {Number} n
871
+ * @return {Number}
872
+ */
873
+ galoisField.log = function log (n) {
874
+ if (n < 1) throw new Error('log(' + n + ')')
875
+ return LOG_TABLE[n]
876
+ };
877
+
878
+ /**
879
+ * Returns anti-log value of n inside Galois Field
880
+ *
881
+ * @param {Number} n
882
+ * @return {Number}
883
+ */
884
+ galoisField.exp = function exp (n) {
885
+ return EXP_TABLE[n]
886
+ };
887
+
888
+ /**
889
+ * Multiplies two number inside Galois Field
890
+ *
891
+ * @param {Number} x
892
+ * @param {Number} y
893
+ * @return {Number}
894
+ */
895
+ galoisField.mul = function mul (x, y) {
896
+ if (x === 0 || y === 0) return 0
897
+
898
+ // should be EXP_TABLE[(LOG_TABLE[x] + LOG_TABLE[y]) % 255] if EXP_TABLE wasn't oversized
899
+ // @see {@link initTables}
900
+ return EXP_TABLE[LOG_TABLE[x] + LOG_TABLE[y]]
901
+ };
902
+ return galoisField;
903
+ }
904
+
905
+ var hasRequiredPolynomial;
906
+
907
+ function requirePolynomial () {
908
+ if (hasRequiredPolynomial) return polynomial;
909
+ hasRequiredPolynomial = 1;
910
+ (function (exports$1) {
911
+ const GF = requireGaloisField();
912
+
913
+ /**
914
+ * Multiplies two polynomials inside Galois Field
915
+ *
916
+ * @param {Uint8Array} p1 Polynomial
917
+ * @param {Uint8Array} p2 Polynomial
918
+ * @return {Uint8Array} Product of p1 and p2
919
+ */
920
+ exports$1.mul = function mul (p1, p2) {
921
+ const coeff = new Uint8Array(p1.length + p2.length - 1);
922
+
923
+ for (let i = 0; i < p1.length; i++) {
924
+ for (let j = 0; j < p2.length; j++) {
925
+ coeff[i + j] ^= GF.mul(p1[i], p2[j]);
926
+ }
927
+ }
928
+
929
+ return coeff
930
+ };
931
+
932
+ /**
933
+ * Calculate the remainder of polynomials division
934
+ *
935
+ * @param {Uint8Array} divident Polynomial
936
+ * @param {Uint8Array} divisor Polynomial
937
+ * @return {Uint8Array} Remainder
938
+ */
939
+ exports$1.mod = function mod (divident, divisor) {
940
+ let result = new Uint8Array(divident);
941
+
942
+ while ((result.length - divisor.length) >= 0) {
943
+ const coeff = result[0];
944
+
945
+ for (let i = 0; i < divisor.length; i++) {
946
+ result[i] ^= GF.mul(divisor[i], coeff);
947
+ }
948
+
949
+ // remove all zeros from buffer head
950
+ let offset = 0;
951
+ while (offset < result.length && result[offset] === 0) offset++;
952
+ result = result.slice(offset);
953
+ }
954
+
955
+ return result
956
+ };
957
+
958
+ /**
959
+ * Generate an irreducible generator polynomial of specified degree
960
+ * (used by Reed-Solomon encoder)
961
+ *
962
+ * @param {Number} degree Degree of the generator polynomial
963
+ * @return {Uint8Array} Buffer containing polynomial coefficients
964
+ */
965
+ exports$1.generateECPolynomial = function generateECPolynomial (degree) {
966
+ let poly = new Uint8Array([1]);
967
+ for (let i = 0; i < degree; i++) {
968
+ poly = exports$1.mul(poly, new Uint8Array([1, GF.exp(i)]));
969
+ }
970
+
971
+ return poly
972
+ };
973
+ } (polynomial));
974
+ return polynomial;
975
+ }
976
+
977
+ var reedSolomonEncoder;
978
+ var hasRequiredReedSolomonEncoder;
979
+
980
+ function requireReedSolomonEncoder () {
981
+ if (hasRequiredReedSolomonEncoder) return reedSolomonEncoder;
982
+ hasRequiredReedSolomonEncoder = 1;
983
+ const Polynomial = requirePolynomial();
984
+
985
+ function ReedSolomonEncoder (degree) {
986
+ this.genPoly = undefined;
987
+ this.degree = degree;
988
+
989
+ if (this.degree) this.initialize(this.degree);
990
+ }
991
+
992
+ /**
993
+ * Initialize the encoder.
994
+ * The input param should correspond to the number of error correction codewords.
995
+ *
996
+ * @param {Number} degree
997
+ */
998
+ ReedSolomonEncoder.prototype.initialize = function initialize (degree) {
999
+ // create an irreducible generator polynomial
1000
+ this.degree = degree;
1001
+ this.genPoly = Polynomial.generateECPolynomial(this.degree);
1002
+ };
1003
+
1004
+ /**
1005
+ * Encodes a chunk of data
1006
+ *
1007
+ * @param {Uint8Array} data Buffer containing input data
1008
+ * @return {Uint8Array} Buffer containing encoded data
1009
+ */
1010
+ ReedSolomonEncoder.prototype.encode = function encode (data) {
1011
+ if (!this.genPoly) {
1012
+ throw new Error('Encoder not initialized')
1013
+ }
1014
+
1015
+ // Calculate EC for this data block
1016
+ // extends data size to data+genPoly size
1017
+ const paddedData = new Uint8Array(data.length + this.degree);
1018
+ paddedData.set(data);
1019
+
1020
+ // The error correction codewords are the remainder after dividing the data codewords
1021
+ // by a generator polynomial
1022
+ const remainder = Polynomial.mod(paddedData, this.genPoly);
1023
+
1024
+ // return EC data blocks (last n byte, where n is the degree of genPoly)
1025
+ // If coefficients number in remainder are less than genPoly degree,
1026
+ // pad with 0s to the left to reach the needed number of coefficients
1027
+ const start = this.degree - remainder.length;
1028
+ if (start > 0) {
1029
+ const buff = new Uint8Array(this.degree);
1030
+ buff.set(remainder, start);
1031
+
1032
+ return buff
1033
+ }
1034
+
1035
+ return remainder
1036
+ };
1037
+
1038
+ reedSolomonEncoder = ReedSolomonEncoder;
1039
+ return reedSolomonEncoder;
1040
+ }
1041
+
1042
+ var version = {};
1043
+
1044
+ var mode = {};
1045
+
1046
+ var versionCheck = {};
1047
+
1048
+ /**
1049
+ * Check if QR Code version is valid
1050
+ *
1051
+ * @param {Number} version QR Code version
1052
+ * @return {Boolean} true if valid version, false otherwise
1053
+ */
1054
+
1055
+ var hasRequiredVersionCheck;
1056
+
1057
+ function requireVersionCheck () {
1058
+ if (hasRequiredVersionCheck) return versionCheck;
1059
+ hasRequiredVersionCheck = 1;
1060
+ versionCheck.isValid = function isValid (version) {
1061
+ return !isNaN(version) && version >= 1 && version <= 40
1062
+ };
1063
+ return versionCheck;
1064
+ }
1065
+
1066
+ var regex = {};
1067
+
1068
+ var hasRequiredRegex;
1069
+
1070
+ function requireRegex () {
1071
+ if (hasRequiredRegex) return regex;
1072
+ hasRequiredRegex = 1;
1073
+ const numeric = '[0-9]+';
1074
+ const alphanumeric = '[A-Z $%*+\\-./:]+';
1075
+ let kanji = '(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|' +
1076
+ '[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|' +
1077
+ '[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|' +
1078
+ '[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+';
1079
+ kanji = kanji.replace(/u/g, '\\u');
1080
+
1081
+ const byte = '(?:(?![A-Z0-9 $%*+\\-./:]|' + kanji + ')(?:.|[\r\n]))+';
1082
+
1083
+ regex.KANJI = new RegExp(kanji, 'g');
1084
+ regex.BYTE_KANJI = new RegExp('[^A-Z0-9 $%*+\\-./:]+', 'g');
1085
+ regex.BYTE = new RegExp(byte, 'g');
1086
+ regex.NUMERIC = new RegExp(numeric, 'g');
1087
+ regex.ALPHANUMERIC = new RegExp(alphanumeric, 'g');
1088
+
1089
+ const TEST_KANJI = new RegExp('^' + kanji + '$');
1090
+ const TEST_NUMERIC = new RegExp('^' + numeric + '$');
1091
+ const TEST_ALPHANUMERIC = new RegExp('^[A-Z0-9 $%*+\\-./:]+$');
1092
+
1093
+ regex.testKanji = function testKanji (str) {
1094
+ return TEST_KANJI.test(str)
1095
+ };
1096
+
1097
+ regex.testNumeric = function testNumeric (str) {
1098
+ return TEST_NUMERIC.test(str)
1099
+ };
1100
+
1101
+ regex.testAlphanumeric = function testAlphanumeric (str) {
1102
+ return TEST_ALPHANUMERIC.test(str)
1103
+ };
1104
+ return regex;
1105
+ }
1106
+
1107
+ var hasRequiredMode;
1108
+
1109
+ function requireMode () {
1110
+ if (hasRequiredMode) return mode;
1111
+ hasRequiredMode = 1;
1112
+ (function (exports$1) {
1113
+ const VersionCheck = requireVersionCheck();
1114
+ const Regex = requireRegex();
1115
+
1116
+ /**
1117
+ * Numeric mode encodes data from the decimal digit set (0 - 9)
1118
+ * (byte values 30HEX to 39HEX).
1119
+ * Normally, 3 data characters are represented by 10 bits.
1120
+ *
1121
+ * @type {Object}
1122
+ */
1123
+ exports$1.NUMERIC = {
1124
+ id: 'Numeric',
1125
+ bit: 1 << 0,
1126
+ ccBits: [10, 12, 14]
1127
+ };
1128
+
1129
+ /**
1130
+ * Alphanumeric mode encodes data from a set of 45 characters,
1131
+ * i.e. 10 numeric digits (0 - 9),
1132
+ * 26 alphabetic characters (A - Z),
1133
+ * and 9 symbols (SP, $, %, *, +, -, ., /, :).
1134
+ * Normally, two input characters are represented by 11 bits.
1135
+ *
1136
+ * @type {Object}
1137
+ */
1138
+ exports$1.ALPHANUMERIC = {
1139
+ id: 'Alphanumeric',
1140
+ bit: 1 << 1,
1141
+ ccBits: [9, 11, 13]
1142
+ };
1143
+
1144
+ /**
1145
+ * In byte mode, data is encoded at 8 bits per character.
1146
+ *
1147
+ * @type {Object}
1148
+ */
1149
+ exports$1.BYTE = {
1150
+ id: 'Byte',
1151
+ bit: 1 << 2,
1152
+ ccBits: [8, 16, 16]
1153
+ };
1154
+
1155
+ /**
1156
+ * The Kanji mode efficiently encodes Kanji characters in accordance with
1157
+ * the Shift JIS system based on JIS X 0208.
1158
+ * The Shift JIS values are shifted from the JIS X 0208 values.
1159
+ * JIS X 0208 gives details of the shift coded representation.
1160
+ * Each two-byte character value is compacted to a 13-bit binary codeword.
1161
+ *
1162
+ * @type {Object}
1163
+ */
1164
+ exports$1.KANJI = {
1165
+ id: 'Kanji',
1166
+ bit: 1 << 3,
1167
+ ccBits: [8, 10, 12]
1168
+ };
1169
+
1170
+ /**
1171
+ * Mixed mode will contain a sequences of data in a combination of any of
1172
+ * the modes described above
1173
+ *
1174
+ * @type {Object}
1175
+ */
1176
+ exports$1.MIXED = {
1177
+ bit: -1
1178
+ };
1179
+
1180
+ /**
1181
+ * Returns the number of bits needed to store the data length
1182
+ * according to QR Code specifications.
1183
+ *
1184
+ * @param {Mode} mode Data mode
1185
+ * @param {Number} version QR Code version
1186
+ * @return {Number} Number of bits
1187
+ */
1188
+ exports$1.getCharCountIndicator = function getCharCountIndicator (mode, version) {
1189
+ if (!mode.ccBits) throw new Error('Invalid mode: ' + mode)
1190
+
1191
+ if (!VersionCheck.isValid(version)) {
1192
+ throw new Error('Invalid version: ' + version)
1193
+ }
1194
+
1195
+ if (version >= 1 && version < 10) return mode.ccBits[0]
1196
+ else if (version < 27) return mode.ccBits[1]
1197
+ return mode.ccBits[2]
1198
+ };
1199
+
1200
+ /**
1201
+ * Returns the most efficient mode to store the specified data
1202
+ *
1203
+ * @param {String} dataStr Input data string
1204
+ * @return {Mode} Best mode
1205
+ */
1206
+ exports$1.getBestModeForData = function getBestModeForData (dataStr) {
1207
+ if (Regex.testNumeric(dataStr)) return exports$1.NUMERIC
1208
+ else if (Regex.testAlphanumeric(dataStr)) return exports$1.ALPHANUMERIC
1209
+ else if (Regex.testKanji(dataStr)) return exports$1.KANJI
1210
+ else return exports$1.BYTE
1211
+ };
1212
+
1213
+ /**
1214
+ * Return mode name as string
1215
+ *
1216
+ * @param {Mode} mode Mode object
1217
+ * @returns {String} Mode name
1218
+ */
1219
+ exports$1.toString = function toString (mode) {
1220
+ if (mode && mode.id) return mode.id
1221
+ throw new Error('Invalid mode')
1222
+ };
1223
+
1224
+ /**
1225
+ * Check if input param is a valid mode object
1226
+ *
1227
+ * @param {Mode} mode Mode object
1228
+ * @returns {Boolean} True if valid mode, false otherwise
1229
+ */
1230
+ exports$1.isValid = function isValid (mode) {
1231
+ return mode && mode.bit && mode.ccBits
1232
+ };
1233
+
1234
+ /**
1235
+ * Get mode object from its name
1236
+ *
1237
+ * @param {String} string Mode name
1238
+ * @returns {Mode} Mode object
1239
+ */
1240
+ function fromString (string) {
1241
+ if (typeof string !== 'string') {
1242
+ throw new Error('Param is not a string')
1243
+ }
1244
+
1245
+ const lcStr = string.toLowerCase();
1246
+
1247
+ switch (lcStr) {
1248
+ case 'numeric':
1249
+ return exports$1.NUMERIC
1250
+ case 'alphanumeric':
1251
+ return exports$1.ALPHANUMERIC
1252
+ case 'kanji':
1253
+ return exports$1.KANJI
1254
+ case 'byte':
1255
+ return exports$1.BYTE
1256
+ default:
1257
+ throw new Error('Unknown mode: ' + string)
1258
+ }
1259
+ }
1260
+
1261
+ /**
1262
+ * Returns mode from a value.
1263
+ * If value is not a valid mode, returns defaultValue
1264
+ *
1265
+ * @param {Mode|String} value Encoding mode
1266
+ * @param {Mode} defaultValue Fallback value
1267
+ * @return {Mode} Encoding mode
1268
+ */
1269
+ exports$1.from = function from (value, defaultValue) {
1270
+ if (exports$1.isValid(value)) {
1271
+ return value
1272
+ }
1273
+
1274
+ try {
1275
+ return fromString(value)
1276
+ } catch (e) {
1277
+ return defaultValue
1278
+ }
1279
+ };
1280
+ } (mode));
1281
+ return mode;
1282
+ }
1283
+
1284
+ var hasRequiredVersion;
1285
+
1286
+ function requireVersion () {
1287
+ if (hasRequiredVersion) return version;
1288
+ hasRequiredVersion = 1;
1289
+ (function (exports$1) {
1290
+ const Utils = requireUtils$1();
1291
+ const ECCode = requireErrorCorrectionCode();
1292
+ const ECLevel = requireErrorCorrectionLevel();
1293
+ const Mode = requireMode();
1294
+ const VersionCheck = requireVersionCheck();
1295
+
1296
+ // Generator polynomial used to encode version information
1297
+ const G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0);
1298
+ const G18_BCH = Utils.getBCHDigit(G18);
1299
+
1300
+ function getBestVersionForDataLength (mode, length, errorCorrectionLevel) {
1301
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
1302
+ if (length <= exports$1.getCapacity(currentVersion, errorCorrectionLevel, mode)) {
1303
+ return currentVersion
1304
+ }
1305
+ }
1306
+
1307
+ return undefined
1308
+ }
1309
+
1310
+ function getReservedBitsCount (mode, version) {
1311
+ // Character count indicator + mode indicator bits
1312
+ return Mode.getCharCountIndicator(mode, version) + 4
1313
+ }
1314
+
1315
+ function getTotalBitsFromDataArray (segments, version) {
1316
+ let totalBits = 0;
1317
+
1318
+ segments.forEach(function (data) {
1319
+ const reservedBits = getReservedBitsCount(data.mode, version);
1320
+ totalBits += reservedBits + data.getBitsLength();
1321
+ });
1322
+
1323
+ return totalBits
1324
+ }
1325
+
1326
+ function getBestVersionForMixedData (segments, errorCorrectionLevel) {
1327
+ for (let currentVersion = 1; currentVersion <= 40; currentVersion++) {
1328
+ const length = getTotalBitsFromDataArray(segments, currentVersion);
1329
+ if (length <= exports$1.getCapacity(currentVersion, errorCorrectionLevel, Mode.MIXED)) {
1330
+ return currentVersion
1331
+ }
1332
+ }
1333
+
1334
+ return undefined
1335
+ }
1336
+
1337
+ /**
1338
+ * Returns version number from a value.
1339
+ * If value is not a valid version, returns defaultValue
1340
+ *
1341
+ * @param {Number|String} value QR Code version
1342
+ * @param {Number} defaultValue Fallback value
1343
+ * @return {Number} QR Code version number
1344
+ */
1345
+ exports$1.from = function from (value, defaultValue) {
1346
+ if (VersionCheck.isValid(value)) {
1347
+ return parseInt(value, 10)
1348
+ }
1349
+
1350
+ return defaultValue
1351
+ };
1352
+
1353
+ /**
1354
+ * Returns how much data can be stored with the specified QR code version
1355
+ * and error correction level
1356
+ *
1357
+ * @param {Number} version QR Code version (1-40)
1358
+ * @param {Number} errorCorrectionLevel Error correction level
1359
+ * @param {Mode} mode Data mode
1360
+ * @return {Number} Quantity of storable data
1361
+ */
1362
+ exports$1.getCapacity = function getCapacity (version, errorCorrectionLevel, mode) {
1363
+ if (!VersionCheck.isValid(version)) {
1364
+ throw new Error('Invalid QR Code version')
1365
+ }
1366
+
1367
+ // Use Byte mode as default
1368
+ if (typeof mode === 'undefined') mode = Mode.BYTE;
1369
+
1370
+ // Total codewords for this QR code version (Data + Error correction)
1371
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
1372
+
1373
+ // Total number of error correction codewords
1374
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
1375
+
1376
+ // Total number of data codewords
1377
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
1378
+
1379
+ if (mode === Mode.MIXED) return dataTotalCodewordsBits
1380
+
1381
+ const usableBits = dataTotalCodewordsBits - getReservedBitsCount(mode, version);
1382
+
1383
+ // Return max number of storable codewords
1384
+ switch (mode) {
1385
+ case Mode.NUMERIC:
1386
+ return Math.floor((usableBits / 10) * 3)
1387
+
1388
+ case Mode.ALPHANUMERIC:
1389
+ return Math.floor((usableBits / 11) * 2)
1390
+
1391
+ case Mode.KANJI:
1392
+ return Math.floor(usableBits / 13)
1393
+
1394
+ case Mode.BYTE:
1395
+ default:
1396
+ return Math.floor(usableBits / 8)
1397
+ }
1398
+ };
1399
+
1400
+ /**
1401
+ * Returns the minimum version needed to contain the amount of data
1402
+ *
1403
+ * @param {Segment} data Segment of data
1404
+ * @param {Number} [errorCorrectionLevel=H] Error correction level
1405
+ * @param {Mode} mode Data mode
1406
+ * @return {Number} QR Code version
1407
+ */
1408
+ exports$1.getBestVersionForData = function getBestVersionForData (data, errorCorrectionLevel) {
1409
+ let seg;
1410
+
1411
+ const ecl = ECLevel.from(errorCorrectionLevel, ECLevel.M);
1412
+
1413
+ if (Array.isArray(data)) {
1414
+ if (data.length > 1) {
1415
+ return getBestVersionForMixedData(data, ecl)
1416
+ }
1417
+
1418
+ if (data.length === 0) {
1419
+ return 1
1420
+ }
1421
+
1422
+ seg = data[0];
1423
+ } else {
1424
+ seg = data;
1425
+ }
1426
+
1427
+ return getBestVersionForDataLength(seg.mode, seg.getLength(), ecl)
1428
+ };
1429
+
1430
+ /**
1431
+ * Returns version information with relative error correction bits
1432
+ *
1433
+ * The version information is included in QR Code symbols of version 7 or larger.
1434
+ * It consists of an 18-bit sequence containing 6 data bits,
1435
+ * with 12 error correction bits calculated using the (18, 6) Golay code.
1436
+ *
1437
+ * @param {Number} version QR Code version
1438
+ * @return {Number} Encoded version info bits
1439
+ */
1440
+ exports$1.getEncodedBits = function getEncodedBits (version) {
1441
+ if (!VersionCheck.isValid(version) || version < 7) {
1442
+ throw new Error('Invalid QR Code version')
1443
+ }
1444
+
1445
+ let d = version << 12;
1446
+
1447
+ while (Utils.getBCHDigit(d) - G18_BCH >= 0) {
1448
+ d ^= (G18 << (Utils.getBCHDigit(d) - G18_BCH));
1449
+ }
1450
+
1451
+ return (version << 12) | d
1452
+ };
1453
+ } (version));
1454
+ return version;
1455
+ }
1456
+
1457
+ var formatInfo = {};
1458
+
1459
+ var hasRequiredFormatInfo;
1460
+
1461
+ function requireFormatInfo () {
1462
+ if (hasRequiredFormatInfo) return formatInfo;
1463
+ hasRequiredFormatInfo = 1;
1464
+ const Utils = requireUtils$1();
1465
+
1466
+ const G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0);
1467
+ const G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1);
1468
+ const G15_BCH = Utils.getBCHDigit(G15);
1469
+
1470
+ /**
1471
+ * Returns format information with relative error correction bits
1472
+ *
1473
+ * The format information is a 15-bit sequence containing 5 data bits,
1474
+ * with 10 error correction bits calculated using the (15, 5) BCH code.
1475
+ *
1476
+ * @param {Number} errorCorrectionLevel Error correction level
1477
+ * @param {Number} mask Mask pattern
1478
+ * @return {Number} Encoded format information bits
1479
+ */
1480
+ formatInfo.getEncodedBits = function getEncodedBits (errorCorrectionLevel, mask) {
1481
+ const data = ((errorCorrectionLevel.bit << 3) | mask);
1482
+ let d = data << 10;
1483
+
1484
+ while (Utils.getBCHDigit(d) - G15_BCH >= 0) {
1485
+ d ^= (G15 << (Utils.getBCHDigit(d) - G15_BCH));
1486
+ }
1487
+
1488
+ // xor final data with mask pattern in order to ensure that
1489
+ // no combination of Error Correction Level and data mask pattern
1490
+ // will result in an all-zero data string
1491
+ return ((data << 10) | d) ^ G15_MASK
1492
+ };
1493
+ return formatInfo;
1494
+ }
1495
+
1496
+ var segments = {};
1497
+
1498
+ var numericData;
1499
+ var hasRequiredNumericData;
1500
+
1501
+ function requireNumericData () {
1502
+ if (hasRequiredNumericData) return numericData;
1503
+ hasRequiredNumericData = 1;
1504
+ const Mode = requireMode();
1505
+
1506
+ function NumericData (data) {
1507
+ this.mode = Mode.NUMERIC;
1508
+ this.data = data.toString();
1509
+ }
1510
+
1511
+ NumericData.getBitsLength = function getBitsLength (length) {
1512
+ return 10 * Math.floor(length / 3) + ((length % 3) ? ((length % 3) * 3 + 1) : 0)
1513
+ };
1514
+
1515
+ NumericData.prototype.getLength = function getLength () {
1516
+ return this.data.length
1517
+ };
1518
+
1519
+ NumericData.prototype.getBitsLength = function getBitsLength () {
1520
+ return NumericData.getBitsLength(this.data.length)
1521
+ };
1522
+
1523
+ NumericData.prototype.write = function write (bitBuffer) {
1524
+ let i, group, value;
1525
+
1526
+ // The input data string is divided into groups of three digits,
1527
+ // and each group is converted to its 10-bit binary equivalent.
1528
+ for (i = 0; i + 3 <= this.data.length; i += 3) {
1529
+ group = this.data.substr(i, 3);
1530
+ value = parseInt(group, 10);
1531
+
1532
+ bitBuffer.put(value, 10);
1533
+ }
1534
+
1535
+ // If the number of input digits is not an exact multiple of three,
1536
+ // the final one or two digits are converted to 4 or 7 bits respectively.
1537
+ const remainingNum = this.data.length - i;
1538
+ if (remainingNum > 0) {
1539
+ group = this.data.substr(i);
1540
+ value = parseInt(group, 10);
1541
+
1542
+ bitBuffer.put(value, remainingNum * 3 + 1);
1543
+ }
1544
+ };
1545
+
1546
+ numericData = NumericData;
1547
+ return numericData;
1548
+ }
1549
+
1550
+ var alphanumericData;
1551
+ var hasRequiredAlphanumericData;
1552
+
1553
+ function requireAlphanumericData () {
1554
+ if (hasRequiredAlphanumericData) return alphanumericData;
1555
+ hasRequiredAlphanumericData = 1;
1556
+ const Mode = requireMode();
1557
+
1558
+ /**
1559
+ * Array of characters available in alphanumeric mode
1560
+ *
1561
+ * As per QR Code specification, to each character
1562
+ * is assigned a value from 0 to 44 which in this case coincides
1563
+ * with the array index
1564
+ *
1565
+ * @type {Array}
1566
+ */
1567
+ const ALPHA_NUM_CHARS = [
1568
+ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
1569
+ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
1570
+ 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
1571
+ ' ', '$', '%', '*', '+', '-', '.', '/', ':'
1572
+ ];
1573
+
1574
+ function AlphanumericData (data) {
1575
+ this.mode = Mode.ALPHANUMERIC;
1576
+ this.data = data;
1577
+ }
1578
+
1579
+ AlphanumericData.getBitsLength = function getBitsLength (length) {
1580
+ return 11 * Math.floor(length / 2) + 6 * (length % 2)
1581
+ };
1582
+
1583
+ AlphanumericData.prototype.getLength = function getLength () {
1584
+ return this.data.length
1585
+ };
1586
+
1587
+ AlphanumericData.prototype.getBitsLength = function getBitsLength () {
1588
+ return AlphanumericData.getBitsLength(this.data.length)
1589
+ };
1590
+
1591
+ AlphanumericData.prototype.write = function write (bitBuffer) {
1592
+ let i;
1593
+
1594
+ // Input data characters are divided into groups of two characters
1595
+ // and encoded as 11-bit binary codes.
1596
+ for (i = 0; i + 2 <= this.data.length; i += 2) {
1597
+ // The character value of the first character is multiplied by 45
1598
+ let value = ALPHA_NUM_CHARS.indexOf(this.data[i]) * 45;
1599
+
1600
+ // The character value of the second digit is added to the product
1601
+ value += ALPHA_NUM_CHARS.indexOf(this.data[i + 1]);
1602
+
1603
+ // The sum is then stored as 11-bit binary number
1604
+ bitBuffer.put(value, 11);
1605
+ }
1606
+
1607
+ // If the number of input data characters is not a multiple of two,
1608
+ // the character value of the final character is encoded as a 6-bit binary number.
1609
+ if (this.data.length % 2) {
1610
+ bitBuffer.put(ALPHA_NUM_CHARS.indexOf(this.data[i]), 6);
1611
+ }
1612
+ };
1613
+
1614
+ alphanumericData = AlphanumericData;
1615
+ return alphanumericData;
1616
+ }
1617
+
1618
+ var byteData;
1619
+ var hasRequiredByteData;
1620
+
1621
+ function requireByteData () {
1622
+ if (hasRequiredByteData) return byteData;
1623
+ hasRequiredByteData = 1;
1624
+ const Mode = requireMode();
1625
+
1626
+ function ByteData (data) {
1627
+ this.mode = Mode.BYTE;
1628
+ if (typeof (data) === 'string') {
1629
+ this.data = new TextEncoder().encode(data);
1630
+ } else {
1631
+ this.data = new Uint8Array(data);
1632
+ }
1633
+ }
1634
+
1635
+ ByteData.getBitsLength = function getBitsLength (length) {
1636
+ return length * 8
1637
+ };
1638
+
1639
+ ByteData.prototype.getLength = function getLength () {
1640
+ return this.data.length
1641
+ };
1642
+
1643
+ ByteData.prototype.getBitsLength = function getBitsLength () {
1644
+ return ByteData.getBitsLength(this.data.length)
1645
+ };
1646
+
1647
+ ByteData.prototype.write = function (bitBuffer) {
1648
+ for (let i = 0, l = this.data.length; i < l; i++) {
1649
+ bitBuffer.put(this.data[i], 8);
1650
+ }
1651
+ };
1652
+
1653
+ byteData = ByteData;
1654
+ return byteData;
1655
+ }
1656
+
1657
+ var kanjiData;
1658
+ var hasRequiredKanjiData;
1659
+
1660
+ function requireKanjiData () {
1661
+ if (hasRequiredKanjiData) return kanjiData;
1662
+ hasRequiredKanjiData = 1;
1663
+ const Mode = requireMode();
1664
+ const Utils = requireUtils$1();
1665
+
1666
+ function KanjiData (data) {
1667
+ this.mode = Mode.KANJI;
1668
+ this.data = data;
1669
+ }
1670
+
1671
+ KanjiData.getBitsLength = function getBitsLength (length) {
1672
+ return length * 13
1673
+ };
1674
+
1675
+ KanjiData.prototype.getLength = function getLength () {
1676
+ return this.data.length
1677
+ };
1678
+
1679
+ KanjiData.prototype.getBitsLength = function getBitsLength () {
1680
+ return KanjiData.getBitsLength(this.data.length)
1681
+ };
1682
+
1683
+ KanjiData.prototype.write = function (bitBuffer) {
1684
+ let i;
1685
+
1686
+ // In the Shift JIS system, Kanji characters are represented by a two byte combination.
1687
+ // These byte values are shifted from the JIS X 0208 values.
1688
+ // JIS X 0208 gives details of the shift coded representation.
1689
+ for (i = 0; i < this.data.length; i++) {
1690
+ let value = Utils.toSJIS(this.data[i]);
1691
+
1692
+ // For characters with Shift JIS values from 0x8140 to 0x9FFC:
1693
+ if (value >= 0x8140 && value <= 0x9FFC) {
1694
+ // Subtract 0x8140 from Shift JIS value
1695
+ value -= 0x8140;
1696
+
1697
+ // For characters with Shift JIS values from 0xE040 to 0xEBBF
1698
+ } else if (value >= 0xE040 && value <= 0xEBBF) {
1699
+ // Subtract 0xC140 from Shift JIS value
1700
+ value -= 0xC140;
1701
+ } else {
1702
+ throw new Error(
1703
+ 'Invalid SJIS character: ' + this.data[i] + '\n' +
1704
+ 'Make sure your charset is UTF-8')
1705
+ }
1706
+
1707
+ // Multiply most significant byte of result by 0xC0
1708
+ // and add least significant byte to product
1709
+ value = (((value >>> 8) & 0xff) * 0xC0) + (value & 0xff);
1710
+
1711
+ // Convert result to a 13-bit binary string
1712
+ bitBuffer.put(value, 13);
1713
+ }
1714
+ };
1715
+
1716
+ kanjiData = KanjiData;
1717
+ return kanjiData;
1718
+ }
1719
+
1720
+ var dijkstra = {exports: {}};
1721
+
1722
+ var hasRequiredDijkstra;
1723
+
1724
+ function requireDijkstra () {
1725
+ if (hasRequiredDijkstra) return dijkstra.exports;
1726
+ hasRequiredDijkstra = 1;
1727
+ (function (module) {
1728
+
1729
+ /******************************************************************************
1730
+ * Created 2008-08-19.
1731
+ *
1732
+ * Dijkstra path-finding functions. Adapted from the Dijkstar Python project.
1733
+ *
1734
+ * Copyright (C) 2008
1735
+ * Wyatt Baldwin <self@wyattbaldwin.com>
1736
+ * All rights reserved
1737
+ *
1738
+ * Licensed under the MIT license.
1739
+ *
1740
+ * http://www.opensource.org/licenses/mit-license.php
1741
+ *
1742
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1743
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1744
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
1745
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
1746
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
1747
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
1748
+ * THE SOFTWARE.
1749
+ *****************************************************************************/
1750
+ var dijkstra = {
1751
+ single_source_shortest_paths: function(graph, s, d) {
1752
+ // Predecessor map for each node that has been encountered.
1753
+ // node ID => predecessor node ID
1754
+ var predecessors = {};
1755
+
1756
+ // Costs of shortest paths from s to all nodes encountered.
1757
+ // node ID => cost
1758
+ var costs = {};
1759
+ costs[s] = 0;
1760
+
1761
+ // Costs of shortest paths from s to all nodes encountered; differs from
1762
+ // `costs` in that it provides easy access to the node that currently has
1763
+ // the known shortest path from s.
1764
+ // XXX: Do we actually need both `costs` and `open`?
1765
+ var open = dijkstra.PriorityQueue.make();
1766
+ open.push(s, 0);
1767
+
1768
+ var closest,
1769
+ u, v,
1770
+ cost_of_s_to_u,
1771
+ adjacent_nodes,
1772
+ cost_of_e,
1773
+ cost_of_s_to_u_plus_cost_of_e,
1774
+ cost_of_s_to_v,
1775
+ first_visit;
1776
+ while (!open.empty()) {
1777
+ // In the nodes remaining in graph that have a known cost from s,
1778
+ // find the node, u, that currently has the shortest path from s.
1779
+ closest = open.pop();
1780
+ u = closest.value;
1781
+ cost_of_s_to_u = closest.cost;
1782
+
1783
+ // Get nodes adjacent to u...
1784
+ adjacent_nodes = graph[u] || {};
1785
+
1786
+ // ...and explore the edges that connect u to those nodes, updating
1787
+ // the cost of the shortest paths to any or all of those nodes as
1788
+ // necessary. v is the node across the current edge from u.
1789
+ for (v in adjacent_nodes) {
1790
+ if (adjacent_nodes.hasOwnProperty(v)) {
1791
+ // Get the cost of the edge running from u to v.
1792
+ cost_of_e = adjacent_nodes[v];
1793
+
1794
+ // Cost of s to u plus the cost of u to v across e--this is *a*
1795
+ // cost from s to v that may or may not be less than the current
1796
+ // known cost to v.
1797
+ cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e;
1798
+
1799
+ // If we haven't visited v yet OR if the current known cost from s to
1800
+ // v is greater than the new cost we just found (cost of s to u plus
1801
+ // cost of u to v across e), update v's cost in the cost list and
1802
+ // update v's predecessor in the predecessor list (it's now u).
1803
+ cost_of_s_to_v = costs[v];
1804
+ first_visit = (typeof costs[v] === 'undefined');
1805
+ if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) {
1806
+ costs[v] = cost_of_s_to_u_plus_cost_of_e;
1807
+ open.push(v, cost_of_s_to_u_plus_cost_of_e);
1808
+ predecessors[v] = u;
1809
+ }
1810
+ }
1811
+ }
1812
+ }
1813
+
1814
+ if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') {
1815
+ var msg = ['Could not find a path from ', s, ' to ', d, '.'].join('');
1816
+ throw new Error(msg);
1817
+ }
1818
+
1819
+ return predecessors;
1820
+ },
1821
+
1822
+ extract_shortest_path_from_predecessor_list: function(predecessors, d) {
1823
+ var nodes = [];
1824
+ var u = d;
1825
+ while (u) {
1826
+ nodes.push(u);
1827
+ predecessors[u];
1828
+ u = predecessors[u];
1829
+ }
1830
+ nodes.reverse();
1831
+ return nodes;
1832
+ },
1833
+
1834
+ find_path: function(graph, s, d) {
1835
+ var predecessors = dijkstra.single_source_shortest_paths(graph, s, d);
1836
+ return dijkstra.extract_shortest_path_from_predecessor_list(
1837
+ predecessors, d);
1838
+ },
1839
+
1840
+ /**
1841
+ * A very naive priority queue implementation.
1842
+ */
1843
+ PriorityQueue: {
1844
+ make: function (opts) {
1845
+ var T = dijkstra.PriorityQueue,
1846
+ t = {},
1847
+ key;
1848
+ opts = opts || {};
1849
+ for (key in T) {
1850
+ if (T.hasOwnProperty(key)) {
1851
+ t[key] = T[key];
1852
+ }
1853
+ }
1854
+ t.queue = [];
1855
+ t.sorter = opts.sorter || T.default_sorter;
1856
+ return t;
1857
+ },
1858
+
1859
+ default_sorter: function (a, b) {
1860
+ return a.cost - b.cost;
1861
+ },
1862
+
1863
+ /**
1864
+ * Add a new item to the queue and ensure the highest priority element
1865
+ * is at the front of the queue.
1866
+ */
1867
+ push: function (value, cost) {
1868
+ var item = {value: value, cost: cost};
1869
+ this.queue.push(item);
1870
+ this.queue.sort(this.sorter);
1871
+ },
1872
+
1873
+ /**
1874
+ * Return the highest priority element in the queue.
1875
+ */
1876
+ pop: function () {
1877
+ return this.queue.shift();
1878
+ },
1879
+
1880
+ empty: function () {
1881
+ return this.queue.length === 0;
1882
+ }
1883
+ }
1884
+ };
1885
+
1886
+
1887
+ // node.js module exports
1888
+ {
1889
+ module.exports = dijkstra;
1890
+ }
1891
+ } (dijkstra));
1892
+ return dijkstra.exports;
1893
+ }
1894
+
1895
+ var hasRequiredSegments;
1896
+
1897
+ function requireSegments () {
1898
+ if (hasRequiredSegments) return segments;
1899
+ hasRequiredSegments = 1;
1900
+ (function (exports$1) {
1901
+ const Mode = requireMode();
1902
+ const NumericData = requireNumericData();
1903
+ const AlphanumericData = requireAlphanumericData();
1904
+ const ByteData = requireByteData();
1905
+ const KanjiData = requireKanjiData();
1906
+ const Regex = requireRegex();
1907
+ const Utils = requireUtils$1();
1908
+ const dijkstra = requireDijkstra();
1909
+
1910
+ /**
1911
+ * Returns UTF8 byte length
1912
+ *
1913
+ * @param {String} str Input string
1914
+ * @return {Number} Number of byte
1915
+ */
1916
+ function getStringByteLength (str) {
1917
+ return unescape(encodeURIComponent(str)).length
1918
+ }
1919
+
1920
+ /**
1921
+ * Get a list of segments of the specified mode
1922
+ * from a string
1923
+ *
1924
+ * @param {Mode} mode Segment mode
1925
+ * @param {String} str String to process
1926
+ * @return {Array} Array of object with segments data
1927
+ */
1928
+ function getSegments (regex, mode, str) {
1929
+ const segments = [];
1930
+ let result;
1931
+
1932
+ while ((result = regex.exec(str)) !== null) {
1933
+ segments.push({
1934
+ data: result[0],
1935
+ index: result.index,
1936
+ mode: mode,
1937
+ length: result[0].length
1938
+ });
1939
+ }
1940
+
1941
+ return segments
1942
+ }
1943
+
1944
+ /**
1945
+ * Extracts a series of segments with the appropriate
1946
+ * modes from a string
1947
+ *
1948
+ * @param {String} dataStr Input string
1949
+ * @return {Array} Array of object with segments data
1950
+ */
1951
+ function getSegmentsFromString (dataStr) {
1952
+ const numSegs = getSegments(Regex.NUMERIC, Mode.NUMERIC, dataStr);
1953
+ const alphaNumSegs = getSegments(Regex.ALPHANUMERIC, Mode.ALPHANUMERIC, dataStr);
1954
+ let byteSegs;
1955
+ let kanjiSegs;
1956
+
1957
+ if (Utils.isKanjiModeEnabled()) {
1958
+ byteSegs = getSegments(Regex.BYTE, Mode.BYTE, dataStr);
1959
+ kanjiSegs = getSegments(Regex.KANJI, Mode.KANJI, dataStr);
1960
+ } else {
1961
+ byteSegs = getSegments(Regex.BYTE_KANJI, Mode.BYTE, dataStr);
1962
+ kanjiSegs = [];
1963
+ }
1964
+
1965
+ const segs = numSegs.concat(alphaNumSegs, byteSegs, kanjiSegs);
1966
+
1967
+ return segs
1968
+ .sort(function (s1, s2) {
1969
+ return s1.index - s2.index
1970
+ })
1971
+ .map(function (obj) {
1972
+ return {
1973
+ data: obj.data,
1974
+ mode: obj.mode,
1975
+ length: obj.length
1976
+ }
1977
+ })
1978
+ }
1979
+
1980
+ /**
1981
+ * Returns how many bits are needed to encode a string of
1982
+ * specified length with the specified mode
1983
+ *
1984
+ * @param {Number} length String length
1985
+ * @param {Mode} mode Segment mode
1986
+ * @return {Number} Bit length
1987
+ */
1988
+ function getSegmentBitsLength (length, mode) {
1989
+ switch (mode) {
1990
+ case Mode.NUMERIC:
1991
+ return NumericData.getBitsLength(length)
1992
+ case Mode.ALPHANUMERIC:
1993
+ return AlphanumericData.getBitsLength(length)
1994
+ case Mode.KANJI:
1995
+ return KanjiData.getBitsLength(length)
1996
+ case Mode.BYTE:
1997
+ return ByteData.getBitsLength(length)
1998
+ }
1999
+ }
2000
+
2001
+ /**
2002
+ * Merges adjacent segments which have the same mode
2003
+ *
2004
+ * @param {Array} segs Array of object with segments data
2005
+ * @return {Array} Array of object with segments data
2006
+ */
2007
+ function mergeSegments (segs) {
2008
+ return segs.reduce(function (acc, curr) {
2009
+ const prevSeg = acc.length - 1 >= 0 ? acc[acc.length - 1] : null;
2010
+ if (prevSeg && prevSeg.mode === curr.mode) {
2011
+ acc[acc.length - 1].data += curr.data;
2012
+ return acc
2013
+ }
2014
+
2015
+ acc.push(curr);
2016
+ return acc
2017
+ }, [])
2018
+ }
2019
+
2020
+ /**
2021
+ * Generates a list of all possible nodes combination which
2022
+ * will be used to build a segments graph.
2023
+ *
2024
+ * Nodes are divided by groups. Each group will contain a list of all the modes
2025
+ * in which is possible to encode the given text.
2026
+ *
2027
+ * For example the text '12345' can be encoded as Numeric, Alphanumeric or Byte.
2028
+ * The group for '12345' will contain then 3 objects, one for each
2029
+ * possible encoding mode.
2030
+ *
2031
+ * Each node represents a possible segment.
2032
+ *
2033
+ * @param {Array} segs Array of object with segments data
2034
+ * @return {Array} Array of object with segments data
2035
+ */
2036
+ function buildNodes (segs) {
2037
+ const nodes = [];
2038
+ for (let i = 0; i < segs.length; i++) {
2039
+ const seg = segs[i];
2040
+
2041
+ switch (seg.mode) {
2042
+ case Mode.NUMERIC:
2043
+ nodes.push([seg,
2044
+ { data: seg.data, mode: Mode.ALPHANUMERIC, length: seg.length },
2045
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
2046
+ ]);
2047
+ break
2048
+ case Mode.ALPHANUMERIC:
2049
+ nodes.push([seg,
2050
+ { data: seg.data, mode: Mode.BYTE, length: seg.length }
2051
+ ]);
2052
+ break
2053
+ case Mode.KANJI:
2054
+ nodes.push([seg,
2055
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
2056
+ ]);
2057
+ break
2058
+ case Mode.BYTE:
2059
+ nodes.push([
2060
+ { data: seg.data, mode: Mode.BYTE, length: getStringByteLength(seg.data) }
2061
+ ]);
2062
+ }
2063
+ }
2064
+
2065
+ return nodes
2066
+ }
2067
+
2068
+ /**
2069
+ * Builds a graph from a list of nodes.
2070
+ * All segments in each node group will be connected with all the segments of
2071
+ * the next group and so on.
2072
+ *
2073
+ * At each connection will be assigned a weight depending on the
2074
+ * segment's byte length.
2075
+ *
2076
+ * @param {Array} nodes Array of object with segments data
2077
+ * @param {Number} version QR Code version
2078
+ * @return {Object} Graph of all possible segments
2079
+ */
2080
+ function buildGraph (nodes, version) {
2081
+ const table = {};
2082
+ const graph = { start: {} };
2083
+ let prevNodeIds = ['start'];
2084
+
2085
+ for (let i = 0; i < nodes.length; i++) {
2086
+ const nodeGroup = nodes[i];
2087
+ const currentNodeIds = [];
2088
+
2089
+ for (let j = 0; j < nodeGroup.length; j++) {
2090
+ const node = nodeGroup[j];
2091
+ const key = '' + i + j;
2092
+
2093
+ currentNodeIds.push(key);
2094
+ table[key] = { node: node, lastCount: 0 };
2095
+ graph[key] = {};
2096
+
2097
+ for (let n = 0; n < prevNodeIds.length; n++) {
2098
+ const prevNodeId = prevNodeIds[n];
2099
+
2100
+ if (table[prevNodeId] && table[prevNodeId].node.mode === node.mode) {
2101
+ graph[prevNodeId][key] =
2102
+ getSegmentBitsLength(table[prevNodeId].lastCount + node.length, node.mode) -
2103
+ getSegmentBitsLength(table[prevNodeId].lastCount, node.mode);
2104
+
2105
+ table[prevNodeId].lastCount += node.length;
2106
+ } else {
2107
+ if (table[prevNodeId]) table[prevNodeId].lastCount = node.length;
2108
+
2109
+ graph[prevNodeId][key] = getSegmentBitsLength(node.length, node.mode) +
2110
+ 4 + Mode.getCharCountIndicator(node.mode, version); // switch cost
2111
+ }
2112
+ }
2113
+ }
2114
+
2115
+ prevNodeIds = currentNodeIds;
2116
+ }
2117
+
2118
+ for (let n = 0; n < prevNodeIds.length; n++) {
2119
+ graph[prevNodeIds[n]].end = 0;
2120
+ }
2121
+
2122
+ return { map: graph, table: table }
2123
+ }
2124
+
2125
+ /**
2126
+ * Builds a segment from a specified data and mode.
2127
+ * If a mode is not specified, the more suitable will be used.
2128
+ *
2129
+ * @param {String} data Input data
2130
+ * @param {Mode | String} modesHint Data mode
2131
+ * @return {Segment} Segment
2132
+ */
2133
+ function buildSingleSegment (data, modesHint) {
2134
+ let mode;
2135
+ const bestMode = Mode.getBestModeForData(data);
2136
+
2137
+ mode = Mode.from(modesHint, bestMode);
2138
+
2139
+ // Make sure data can be encoded
2140
+ if (mode !== Mode.BYTE && mode.bit < bestMode.bit) {
2141
+ throw new Error('"' + data + '"' +
2142
+ ' cannot be encoded with mode ' + Mode.toString(mode) +
2143
+ '.\n Suggested mode is: ' + Mode.toString(bestMode))
2144
+ }
2145
+
2146
+ // Use Mode.BYTE if Kanji support is disabled
2147
+ if (mode === Mode.KANJI && !Utils.isKanjiModeEnabled()) {
2148
+ mode = Mode.BYTE;
2149
+ }
2150
+
2151
+ switch (mode) {
2152
+ case Mode.NUMERIC:
2153
+ return new NumericData(data)
2154
+
2155
+ case Mode.ALPHANUMERIC:
2156
+ return new AlphanumericData(data)
2157
+
2158
+ case Mode.KANJI:
2159
+ return new KanjiData(data)
2160
+
2161
+ case Mode.BYTE:
2162
+ return new ByteData(data)
2163
+ }
2164
+ }
2165
+
2166
+ /**
2167
+ * Builds a list of segments from an array.
2168
+ * Array can contain Strings or Objects with segment's info.
2169
+ *
2170
+ * For each item which is a string, will be generated a segment with the given
2171
+ * string and the more appropriate encoding mode.
2172
+ *
2173
+ * For each item which is an object, will be generated a segment with the given
2174
+ * data and mode.
2175
+ * Objects must contain at least the property "data".
2176
+ * If property "mode" is not present, the more suitable mode will be used.
2177
+ *
2178
+ * @param {Array} array Array of objects with segments data
2179
+ * @return {Array} Array of Segments
2180
+ */
2181
+ exports$1.fromArray = function fromArray (array) {
2182
+ return array.reduce(function (acc, seg) {
2183
+ if (typeof seg === 'string') {
2184
+ acc.push(buildSingleSegment(seg, null));
2185
+ } else if (seg.data) {
2186
+ acc.push(buildSingleSegment(seg.data, seg.mode));
2187
+ }
2188
+
2189
+ return acc
2190
+ }, [])
2191
+ };
2192
+
2193
+ /**
2194
+ * Builds an optimized sequence of segments from a string,
2195
+ * which will produce the shortest possible bitstream.
2196
+ *
2197
+ * @param {String} data Input string
2198
+ * @param {Number} version QR Code version
2199
+ * @return {Array} Array of segments
2200
+ */
2201
+ exports$1.fromString = function fromString (data, version) {
2202
+ const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled());
2203
+
2204
+ const nodes = buildNodes(segs);
2205
+ const graph = buildGraph(nodes, version);
2206
+ const path = dijkstra.find_path(graph.map, 'start', 'end');
2207
+
2208
+ const optimizedSegs = [];
2209
+ for (let i = 1; i < path.length - 1; i++) {
2210
+ optimizedSegs.push(graph.table[path[i]].node);
2211
+ }
2212
+
2213
+ return exports$1.fromArray(mergeSegments(optimizedSegs))
2214
+ };
2215
+
2216
+ /**
2217
+ * Splits a string in various segments with the modes which
2218
+ * best represent their content.
2219
+ * The produced segments are far from being optimized.
2220
+ * The output of this function is only used to estimate a QR Code version
2221
+ * which may contain the data.
2222
+ *
2223
+ * @param {string} data Input string
2224
+ * @return {Array} Array of segments
2225
+ */
2226
+ exports$1.rawSplit = function rawSplit (data) {
2227
+ return exports$1.fromArray(
2228
+ getSegmentsFromString(data, Utils.isKanjiModeEnabled())
2229
+ )
2230
+ };
2231
+ } (segments));
2232
+ return segments;
2233
+ }
2234
+
2235
+ var hasRequiredQrcode;
2236
+
2237
+ function requireQrcode () {
2238
+ if (hasRequiredQrcode) return qrcode;
2239
+ hasRequiredQrcode = 1;
2240
+ const Utils = requireUtils$1();
2241
+ const ECLevel = requireErrorCorrectionLevel();
2242
+ const BitBuffer = requireBitBuffer();
2243
+ const BitMatrix = requireBitMatrix();
2244
+ const AlignmentPattern = requireAlignmentPattern();
2245
+ const FinderPattern = requireFinderPattern();
2246
+ const MaskPattern = requireMaskPattern();
2247
+ const ECCode = requireErrorCorrectionCode();
2248
+ const ReedSolomonEncoder = requireReedSolomonEncoder();
2249
+ const Version = requireVersion();
2250
+ const FormatInfo = requireFormatInfo();
2251
+ const Mode = requireMode();
2252
+ const Segments = requireSegments();
2253
+
2254
+ /**
2255
+ * QRCode for JavaScript
2256
+ *
2257
+ * modified by Ryan Day for nodejs support
2258
+ * Copyright (c) 2011 Ryan Day
2259
+ *
2260
+ * Licensed under the MIT license:
2261
+ * http://www.opensource.org/licenses/mit-license.php
2262
+ *
2263
+ //---------------------------------------------------------------------
2264
+ // QRCode for JavaScript
2265
+ //
2266
+ // Copyright (c) 2009 Kazuhiko Arase
2267
+ //
2268
+ // URL: http://www.d-project.com/
2269
+ //
2270
+ // Licensed under the MIT license:
2271
+ // http://www.opensource.org/licenses/mit-license.php
2272
+ //
2273
+ // The word "QR Code" is registered trademark of
2274
+ // DENSO WAVE INCORPORATED
2275
+ // http://www.denso-wave.com/qrcode/faqpatent-e.html
2276
+ //
2277
+ //---------------------------------------------------------------------
2278
+ */
2279
+
2280
+ /**
2281
+ * Add finder patterns bits to matrix
2282
+ *
2283
+ * @param {BitMatrix} matrix Modules matrix
2284
+ * @param {Number} version QR Code version
2285
+ */
2286
+ function setupFinderPattern (matrix, version) {
2287
+ const size = matrix.size;
2288
+ const pos = FinderPattern.getPositions(version);
2289
+
2290
+ for (let i = 0; i < pos.length; i++) {
2291
+ const row = pos[i][0];
2292
+ const col = pos[i][1];
2293
+
2294
+ for (let r = -1; r <= 7; r++) {
2295
+ if (row + r <= -1 || size <= row + r) continue
2296
+
2297
+ for (let c = -1; c <= 7; c++) {
2298
+ if (col + c <= -1 || size <= col + c) continue
2299
+
2300
+ if ((r >= 0 && r <= 6 && (c === 0 || c === 6)) ||
2301
+ (c >= 0 && c <= 6 && (r === 0 || r === 6)) ||
2302
+ (r >= 2 && r <= 4 && c >= 2 && c <= 4)) {
2303
+ matrix.set(row + r, col + c, true, true);
2304
+ } else {
2305
+ matrix.set(row + r, col + c, false, true);
2306
+ }
2307
+ }
2308
+ }
2309
+ }
2310
+ }
2311
+
2312
+ /**
2313
+ * Add timing pattern bits to matrix
2314
+ *
2315
+ * Note: this function must be called before {@link setupAlignmentPattern}
2316
+ *
2317
+ * @param {BitMatrix} matrix Modules matrix
2318
+ */
2319
+ function setupTimingPattern (matrix) {
2320
+ const size = matrix.size;
2321
+
2322
+ for (let r = 8; r < size - 8; r++) {
2323
+ const value = r % 2 === 0;
2324
+ matrix.set(r, 6, value, true);
2325
+ matrix.set(6, r, value, true);
2326
+ }
2327
+ }
2328
+
2329
+ /**
2330
+ * Add alignment patterns bits to matrix
2331
+ *
2332
+ * Note: this function must be called after {@link setupTimingPattern}
2333
+ *
2334
+ * @param {BitMatrix} matrix Modules matrix
2335
+ * @param {Number} version QR Code version
2336
+ */
2337
+ function setupAlignmentPattern (matrix, version) {
2338
+ const pos = AlignmentPattern.getPositions(version);
2339
+
2340
+ for (let i = 0; i < pos.length; i++) {
2341
+ const row = pos[i][0];
2342
+ const col = pos[i][1];
2343
+
2344
+ for (let r = -2; r <= 2; r++) {
2345
+ for (let c = -2; c <= 2; c++) {
2346
+ if (r === -2 || r === 2 || c === -2 || c === 2 ||
2347
+ (r === 0 && c === 0)) {
2348
+ matrix.set(row + r, col + c, true, true);
2349
+ } else {
2350
+ matrix.set(row + r, col + c, false, true);
2351
+ }
2352
+ }
2353
+ }
2354
+ }
2355
+ }
2356
+
2357
+ /**
2358
+ * Add version info bits to matrix
2359
+ *
2360
+ * @param {BitMatrix} matrix Modules matrix
2361
+ * @param {Number} version QR Code version
2362
+ */
2363
+ function setupVersionInfo (matrix, version) {
2364
+ const size = matrix.size;
2365
+ const bits = Version.getEncodedBits(version);
2366
+ let row, col, mod;
2367
+
2368
+ for (let i = 0; i < 18; i++) {
2369
+ row = Math.floor(i / 3);
2370
+ col = i % 3 + size - 8 - 3;
2371
+ mod = ((bits >> i) & 1) === 1;
2372
+
2373
+ matrix.set(row, col, mod, true);
2374
+ matrix.set(col, row, mod, true);
2375
+ }
2376
+ }
2377
+
2378
+ /**
2379
+ * Add format info bits to matrix
2380
+ *
2381
+ * @param {BitMatrix} matrix Modules matrix
2382
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2383
+ * @param {Number} maskPattern Mask pattern reference value
2384
+ */
2385
+ function setupFormatInfo (matrix, errorCorrectionLevel, maskPattern) {
2386
+ const size = matrix.size;
2387
+ const bits = FormatInfo.getEncodedBits(errorCorrectionLevel, maskPattern);
2388
+ let i, mod;
2389
+
2390
+ for (i = 0; i < 15; i++) {
2391
+ mod = ((bits >> i) & 1) === 1;
2392
+
2393
+ // vertical
2394
+ if (i < 6) {
2395
+ matrix.set(i, 8, mod, true);
2396
+ } else if (i < 8) {
2397
+ matrix.set(i + 1, 8, mod, true);
2398
+ } else {
2399
+ matrix.set(size - 15 + i, 8, mod, true);
2400
+ }
2401
+
2402
+ // horizontal
2403
+ if (i < 8) {
2404
+ matrix.set(8, size - i - 1, mod, true);
2405
+ } else if (i < 9) {
2406
+ matrix.set(8, 15 - i - 1 + 1, mod, true);
2407
+ } else {
2408
+ matrix.set(8, 15 - i - 1, mod, true);
2409
+ }
2410
+ }
2411
+
2412
+ // fixed module
2413
+ matrix.set(size - 8, 8, 1, true);
2414
+ }
2415
+
2416
+ /**
2417
+ * Add encoded data bits to matrix
2418
+ *
2419
+ * @param {BitMatrix} matrix Modules matrix
2420
+ * @param {Uint8Array} data Data codewords
2421
+ */
2422
+ function setupData (matrix, data) {
2423
+ const size = matrix.size;
2424
+ let inc = -1;
2425
+ let row = size - 1;
2426
+ let bitIndex = 7;
2427
+ let byteIndex = 0;
2428
+
2429
+ for (let col = size - 1; col > 0; col -= 2) {
2430
+ if (col === 6) col--;
2431
+
2432
+ while (true) {
2433
+ for (let c = 0; c < 2; c++) {
2434
+ if (!matrix.isReserved(row, col - c)) {
2435
+ let dark = false;
2436
+
2437
+ if (byteIndex < data.length) {
2438
+ dark = (((data[byteIndex] >>> bitIndex) & 1) === 1);
2439
+ }
2440
+
2441
+ matrix.set(row, col - c, dark);
2442
+ bitIndex--;
2443
+
2444
+ if (bitIndex === -1) {
2445
+ byteIndex++;
2446
+ bitIndex = 7;
2447
+ }
2448
+ }
2449
+ }
2450
+
2451
+ row += inc;
2452
+
2453
+ if (row < 0 || size <= row) {
2454
+ row -= inc;
2455
+ inc = -inc;
2456
+ break
2457
+ }
2458
+ }
2459
+ }
2460
+ }
2461
+
2462
+ /**
2463
+ * Create encoded codewords from data input
2464
+ *
2465
+ * @param {Number} version QR Code version
2466
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2467
+ * @param {ByteData} data Data input
2468
+ * @return {Uint8Array} Buffer containing encoded codewords
2469
+ */
2470
+ function createData (version, errorCorrectionLevel, segments) {
2471
+ // Prepare data buffer
2472
+ const buffer = new BitBuffer();
2473
+
2474
+ segments.forEach(function (data) {
2475
+ // prefix data with mode indicator (4 bits)
2476
+ buffer.put(data.mode.bit, 4);
2477
+
2478
+ // Prefix data with character count indicator.
2479
+ // The character count indicator is a string of bits that represents the
2480
+ // number of characters that are being encoded.
2481
+ // The character count indicator must be placed after the mode indicator
2482
+ // and must be a certain number of bits long, depending on the QR version
2483
+ // and data mode
2484
+ // @see {@link Mode.getCharCountIndicator}.
2485
+ buffer.put(data.getLength(), Mode.getCharCountIndicator(data.mode, version));
2486
+
2487
+ // add binary data sequence to buffer
2488
+ data.write(buffer);
2489
+ });
2490
+
2491
+ // Calculate required number of bits
2492
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
2493
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
2494
+ const dataTotalCodewordsBits = (totalCodewords - ecTotalCodewords) * 8;
2495
+
2496
+ // Add a terminator.
2497
+ // If the bit string is shorter than the total number of required bits,
2498
+ // a terminator of up to four 0s must be added to the right side of the string.
2499
+ // If the bit string is more than four bits shorter than the required number of bits,
2500
+ // add four 0s to the end.
2501
+ if (buffer.getLengthInBits() + 4 <= dataTotalCodewordsBits) {
2502
+ buffer.put(0, 4);
2503
+ }
2504
+
2505
+ // If the bit string is fewer than four bits shorter, add only the number of 0s that
2506
+ // are needed to reach the required number of bits.
2507
+
2508
+ // After adding the terminator, if the number of bits in the string is not a multiple of 8,
2509
+ // pad the string on the right with 0s to make the string's length a multiple of 8.
2510
+ while (buffer.getLengthInBits() % 8 !== 0) {
2511
+ buffer.putBit(0);
2512
+ }
2513
+
2514
+ // Add pad bytes if the string is still shorter than the total number of required bits.
2515
+ // Extend the buffer to fill the data capacity of the symbol corresponding to
2516
+ // the Version and Error Correction Level by adding the Pad Codewords 11101100 (0xEC)
2517
+ // and 00010001 (0x11) alternately.
2518
+ const remainingByte = (dataTotalCodewordsBits - buffer.getLengthInBits()) / 8;
2519
+ for (let i = 0; i < remainingByte; i++) {
2520
+ buffer.put(i % 2 ? 0x11 : 0xEC, 8);
2521
+ }
2522
+
2523
+ return createCodewords(buffer, version, errorCorrectionLevel)
2524
+ }
2525
+
2526
+ /**
2527
+ * Encode input data with Reed-Solomon and return codewords with
2528
+ * relative error correction bits
2529
+ *
2530
+ * @param {BitBuffer} bitBuffer Data to encode
2531
+ * @param {Number} version QR Code version
2532
+ * @param {ErrorCorrectionLevel} errorCorrectionLevel Error correction level
2533
+ * @return {Uint8Array} Buffer containing encoded codewords
2534
+ */
2535
+ function createCodewords (bitBuffer, version, errorCorrectionLevel) {
2536
+ // Total codewords for this QR code version (Data + Error correction)
2537
+ const totalCodewords = Utils.getSymbolTotalCodewords(version);
2538
+
2539
+ // Total number of error correction codewords
2540
+ const ecTotalCodewords = ECCode.getTotalCodewordsCount(version, errorCorrectionLevel);
2541
+
2542
+ // Total number of data codewords
2543
+ const dataTotalCodewords = totalCodewords - ecTotalCodewords;
2544
+
2545
+ // Total number of blocks
2546
+ const ecTotalBlocks = ECCode.getBlocksCount(version, errorCorrectionLevel);
2547
+
2548
+ // Calculate how many blocks each group should contain
2549
+ const blocksInGroup2 = totalCodewords % ecTotalBlocks;
2550
+ const blocksInGroup1 = ecTotalBlocks - blocksInGroup2;
2551
+
2552
+ const totalCodewordsInGroup1 = Math.floor(totalCodewords / ecTotalBlocks);
2553
+
2554
+ const dataCodewordsInGroup1 = Math.floor(dataTotalCodewords / ecTotalBlocks);
2555
+ const dataCodewordsInGroup2 = dataCodewordsInGroup1 + 1;
2556
+
2557
+ // Number of EC codewords is the same for both groups
2558
+ const ecCount = totalCodewordsInGroup1 - dataCodewordsInGroup1;
2559
+
2560
+ // Initialize a Reed-Solomon encoder with a generator polynomial of degree ecCount
2561
+ const rs = new ReedSolomonEncoder(ecCount);
2562
+
2563
+ let offset = 0;
2564
+ const dcData = new Array(ecTotalBlocks);
2565
+ const ecData = new Array(ecTotalBlocks);
2566
+ let maxDataSize = 0;
2567
+ const buffer = new Uint8Array(bitBuffer.buffer);
2568
+
2569
+ // Divide the buffer into the required number of blocks
2570
+ for (let b = 0; b < ecTotalBlocks; b++) {
2571
+ const dataSize = b < blocksInGroup1 ? dataCodewordsInGroup1 : dataCodewordsInGroup2;
2572
+
2573
+ // extract a block of data from buffer
2574
+ dcData[b] = buffer.slice(offset, offset + dataSize);
2575
+
2576
+ // Calculate EC codewords for this data block
2577
+ ecData[b] = rs.encode(dcData[b]);
2578
+
2579
+ offset += dataSize;
2580
+ maxDataSize = Math.max(maxDataSize, dataSize);
2581
+ }
2582
+
2583
+ // Create final data
2584
+ // Interleave the data and error correction codewords from each block
2585
+ const data = new Uint8Array(totalCodewords);
2586
+ let index = 0;
2587
+ let i, r;
2588
+
2589
+ // Add data codewords
2590
+ for (i = 0; i < maxDataSize; i++) {
2591
+ for (r = 0; r < ecTotalBlocks; r++) {
2592
+ if (i < dcData[r].length) {
2593
+ data[index++] = dcData[r][i];
2594
+ }
2595
+ }
2596
+ }
2597
+
2598
+ // Apped EC codewords
2599
+ for (i = 0; i < ecCount; i++) {
2600
+ for (r = 0; r < ecTotalBlocks; r++) {
2601
+ data[index++] = ecData[r][i];
2602
+ }
2603
+ }
2604
+
2605
+ return data
2606
+ }
2607
+
2608
+ /**
2609
+ * Build QR Code symbol
2610
+ *
2611
+ * @param {String} data Input string
2612
+ * @param {Number} version QR Code version
2613
+ * @param {ErrorCorretionLevel} errorCorrectionLevel Error level
2614
+ * @param {MaskPattern} maskPattern Mask pattern
2615
+ * @return {Object} Object containing symbol data
2616
+ */
2617
+ function createSymbol (data, version, errorCorrectionLevel, maskPattern) {
2618
+ let segments;
2619
+
2620
+ if (Array.isArray(data)) {
2621
+ segments = Segments.fromArray(data);
2622
+ } else if (typeof data === 'string') {
2623
+ let estimatedVersion = version;
2624
+
2625
+ if (!estimatedVersion) {
2626
+ const rawSegments = Segments.rawSplit(data);
2627
+
2628
+ // Estimate best version that can contain raw splitted segments
2629
+ estimatedVersion = Version.getBestVersionForData(rawSegments, errorCorrectionLevel);
2630
+ }
2631
+
2632
+ // Build optimized segments
2633
+ // If estimated version is undefined, try with the highest version
2634
+ segments = Segments.fromString(data, estimatedVersion || 40);
2635
+ } else {
2636
+ throw new Error('Invalid data')
2637
+ }
2638
+
2639
+ // Get the min version that can contain data
2640
+ const bestVersion = Version.getBestVersionForData(segments, errorCorrectionLevel);
2641
+
2642
+ // If no version is found, data cannot be stored
2643
+ if (!bestVersion) {
2644
+ throw new Error('The amount of data is too big to be stored in a QR Code')
2645
+ }
2646
+
2647
+ // If not specified, use min version as default
2648
+ if (!version) {
2649
+ version = bestVersion;
2650
+
2651
+ // Check if the specified version can contain the data
2652
+ } else if (version < bestVersion) {
2653
+ throw new Error('\n' +
2654
+ 'The chosen QR Code version cannot contain this amount of data.\n' +
2655
+ 'Minimum version required to store current data is: ' + bestVersion + '.\n'
2656
+ )
2657
+ }
2658
+
2659
+ const dataBits = createData(version, errorCorrectionLevel, segments);
2660
+
2661
+ // Allocate matrix buffer
2662
+ const moduleCount = Utils.getSymbolSize(version);
2663
+ const modules = new BitMatrix(moduleCount);
2664
+
2665
+ // Add function modules
2666
+ setupFinderPattern(modules, version);
2667
+ setupTimingPattern(modules);
2668
+ setupAlignmentPattern(modules, version);
2669
+
2670
+ // Add temporary dummy bits for format info just to set them as reserved.
2671
+ // This is needed to prevent these bits from being masked by {@link MaskPattern.applyMask}
2672
+ // since the masking operation must be performed only on the encoding region.
2673
+ // These blocks will be replaced with correct values later in code.
2674
+ setupFormatInfo(modules, errorCorrectionLevel, 0);
2675
+
2676
+ if (version >= 7) {
2677
+ setupVersionInfo(modules, version);
2678
+ }
2679
+
2680
+ // Add data codewords
2681
+ setupData(modules, dataBits);
2682
+
2683
+ if (isNaN(maskPattern)) {
2684
+ // Find best mask pattern
2685
+ maskPattern = MaskPattern.getBestMask(modules,
2686
+ setupFormatInfo.bind(null, modules, errorCorrectionLevel));
2687
+ }
2688
+
2689
+ // Apply mask pattern
2690
+ MaskPattern.applyMask(maskPattern, modules);
2691
+
2692
+ // Replace format info bits with correct values
2693
+ setupFormatInfo(modules, errorCorrectionLevel, maskPattern);
2694
+
2695
+ return {
2696
+ modules: modules,
2697
+ version: version,
2698
+ errorCorrectionLevel: errorCorrectionLevel,
2699
+ maskPattern: maskPattern,
2700
+ segments: segments
2701
+ }
2702
+ }
2703
+
2704
+ /**
2705
+ * QR Code
2706
+ *
2707
+ * @param {String | Array} data Input data
2708
+ * @param {Object} options Optional configurations
2709
+ * @param {Number} options.version QR Code version
2710
+ * @param {String} options.errorCorrectionLevel Error correction level
2711
+ * @param {Function} options.toSJISFunc Helper func to convert utf8 to sjis
2712
+ */
2713
+ qrcode.create = function create (data, options) {
2714
+ if (typeof data === 'undefined' || data === '') {
2715
+ throw new Error('No input text')
2716
+ }
2717
+
2718
+ let errorCorrectionLevel = ECLevel.M;
2719
+ let version;
2720
+ let mask;
2721
+
2722
+ if (typeof options !== 'undefined') {
2723
+ // Use higher error correction level as default
2724
+ errorCorrectionLevel = ECLevel.from(options.errorCorrectionLevel, ECLevel.M);
2725
+ version = Version.from(options.version);
2726
+ mask = MaskPattern.from(options.maskPattern);
2727
+
2728
+ if (options.toSJISFunc) {
2729
+ Utils.setToSJISFunction(options.toSJISFunc);
2730
+ }
2731
+ }
2732
+
2733
+ return createSymbol(data, version, errorCorrectionLevel, mask)
2734
+ };
2735
+ return qrcode;
2736
+ }
2737
+
2738
+ var canvas = {};
2739
+
2740
+ var utils = {};
2741
+
2742
+ var hasRequiredUtils;
2743
+
2744
+ function requireUtils () {
2745
+ if (hasRequiredUtils) return utils;
2746
+ hasRequiredUtils = 1;
2747
+ (function (exports$1) {
2748
+ function hex2rgba (hex) {
2749
+ if (typeof hex === 'number') {
2750
+ hex = hex.toString();
2751
+ }
2752
+
2753
+ if (typeof hex !== 'string') {
2754
+ throw new Error('Color should be defined as hex string')
2755
+ }
2756
+
2757
+ let hexCode = hex.slice().replace('#', '').split('');
2758
+ if (hexCode.length < 3 || hexCode.length === 5 || hexCode.length > 8) {
2759
+ throw new Error('Invalid hex color: ' + hex)
2760
+ }
2761
+
2762
+ // Convert from short to long form (fff -> ffffff)
2763
+ if (hexCode.length === 3 || hexCode.length === 4) {
2764
+ hexCode = Array.prototype.concat.apply([], hexCode.map(function (c) {
2765
+ return [c, c]
2766
+ }));
2767
+ }
2768
+
2769
+ // Add default alpha value
2770
+ if (hexCode.length === 6) hexCode.push('F', 'F');
2771
+
2772
+ const hexValue = parseInt(hexCode.join(''), 16);
2773
+
2774
+ return {
2775
+ r: (hexValue >> 24) & 255,
2776
+ g: (hexValue >> 16) & 255,
2777
+ b: (hexValue >> 8) & 255,
2778
+ a: hexValue & 255,
2779
+ hex: '#' + hexCode.slice(0, 6).join('')
2780
+ }
2781
+ }
2782
+
2783
+ exports$1.getOptions = function getOptions (options) {
2784
+ if (!options) options = {};
2785
+ if (!options.color) options.color = {};
2786
+
2787
+ const margin = typeof options.margin === 'undefined' ||
2788
+ options.margin === null ||
2789
+ options.margin < 0
2790
+ ? 4
2791
+ : options.margin;
2792
+
2793
+ const width = options.width && options.width >= 21 ? options.width : undefined;
2794
+ const scale = options.scale || 4;
2795
+
2796
+ return {
2797
+ width: width,
2798
+ scale: width ? 4 : scale,
2799
+ margin: margin,
2800
+ color: {
2801
+ dark: hex2rgba(options.color.dark || '#000000ff'),
2802
+ light: hex2rgba(options.color.light || '#ffffffff')
2803
+ },
2804
+ type: options.type,
2805
+ rendererOpts: options.rendererOpts || {}
2806
+ }
2807
+ };
2808
+
2809
+ exports$1.getScale = function getScale (qrSize, opts) {
2810
+ return opts.width && opts.width >= qrSize + opts.margin * 2
2811
+ ? opts.width / (qrSize + opts.margin * 2)
2812
+ : opts.scale
2813
+ };
2814
+
2815
+ exports$1.getImageWidth = function getImageWidth (qrSize, opts) {
2816
+ const scale = exports$1.getScale(qrSize, opts);
2817
+ return Math.floor((qrSize + opts.margin * 2) * scale)
2818
+ };
2819
+
2820
+ exports$1.qrToImageData = function qrToImageData (imgData, qr, opts) {
2821
+ const size = qr.modules.size;
2822
+ const data = qr.modules.data;
2823
+ const scale = exports$1.getScale(size, opts);
2824
+ const symbolSize = Math.floor((size + opts.margin * 2) * scale);
2825
+ const scaledMargin = opts.margin * scale;
2826
+ const palette = [opts.color.light, opts.color.dark];
2827
+
2828
+ for (let i = 0; i < symbolSize; i++) {
2829
+ for (let j = 0; j < symbolSize; j++) {
2830
+ let posDst = (i * symbolSize + j) * 4;
2831
+ let pxColor = opts.color.light;
2832
+
2833
+ if (i >= scaledMargin && j >= scaledMargin &&
2834
+ i < symbolSize - scaledMargin && j < symbolSize - scaledMargin) {
2835
+ const iSrc = Math.floor((i - scaledMargin) / scale);
2836
+ const jSrc = Math.floor((j - scaledMargin) / scale);
2837
+ pxColor = palette[data[iSrc * size + jSrc] ? 1 : 0];
2838
+ }
2839
+
2840
+ imgData[posDst++] = pxColor.r;
2841
+ imgData[posDst++] = pxColor.g;
2842
+ imgData[posDst++] = pxColor.b;
2843
+ imgData[posDst] = pxColor.a;
2844
+ }
2845
+ }
2846
+ };
2847
+ } (utils));
2848
+ return utils;
2849
+ }
2850
+
2851
+ var hasRequiredCanvas;
2852
+
2853
+ function requireCanvas () {
2854
+ if (hasRequiredCanvas) return canvas;
2855
+ hasRequiredCanvas = 1;
2856
+ (function (exports$1) {
2857
+ const Utils = requireUtils();
2858
+
2859
+ function clearCanvas (ctx, canvas, size) {
2860
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
2861
+
2862
+ if (!canvas.style) canvas.style = {};
2863
+ canvas.height = size;
2864
+ canvas.width = size;
2865
+ canvas.style.height = size + 'px';
2866
+ canvas.style.width = size + 'px';
2867
+ }
2868
+
2869
+ function getCanvasElement () {
2870
+ try {
2871
+ return document.createElement('canvas')
2872
+ } catch (e) {
2873
+ throw new Error('You need to specify a canvas element')
2874
+ }
2875
+ }
2876
+
2877
+ exports$1.render = function render (qrData, canvas, options) {
2878
+ let opts = options;
2879
+ let canvasEl = canvas;
2880
+
2881
+ if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
2882
+ opts = canvas;
2883
+ canvas = undefined;
2884
+ }
2885
+
2886
+ if (!canvas) {
2887
+ canvasEl = getCanvasElement();
2888
+ }
2889
+
2890
+ opts = Utils.getOptions(opts);
2891
+ const size = Utils.getImageWidth(qrData.modules.size, opts);
2892
+
2893
+ const ctx = canvasEl.getContext('2d');
2894
+ const image = ctx.createImageData(size, size);
2895
+ Utils.qrToImageData(image.data, qrData, opts);
2896
+
2897
+ clearCanvas(ctx, canvasEl, size);
2898
+ ctx.putImageData(image, 0, 0);
2899
+
2900
+ return canvasEl
2901
+ };
2902
+
2903
+ exports$1.renderToDataURL = function renderToDataURL (qrData, canvas, options) {
2904
+ let opts = options;
2905
+
2906
+ if (typeof opts === 'undefined' && (!canvas || !canvas.getContext)) {
2907
+ opts = canvas;
2908
+ canvas = undefined;
2909
+ }
2910
+
2911
+ if (!opts) opts = {};
2912
+
2913
+ const canvasEl = exports$1.render(qrData, canvas, opts);
2914
+
2915
+ const type = opts.type || 'image/png';
2916
+ const rendererOpts = opts.rendererOpts || {};
2917
+
2918
+ return canvasEl.toDataURL(type, rendererOpts.quality)
2919
+ };
2920
+ } (canvas));
2921
+ return canvas;
2922
+ }
2923
+
2924
+ var svgTag = {};
2925
+
2926
+ var hasRequiredSvgTag;
2927
+
2928
+ function requireSvgTag () {
2929
+ if (hasRequiredSvgTag) return svgTag;
2930
+ hasRequiredSvgTag = 1;
2931
+ const Utils = requireUtils();
2932
+
2933
+ function getColorAttrib (color, attrib) {
2934
+ const alpha = color.a / 255;
2935
+ const str = attrib + '="' + color.hex + '"';
2936
+
2937
+ return alpha < 1
2938
+ ? str + ' ' + attrib + '-opacity="' + alpha.toFixed(2).slice(1) + '"'
2939
+ : str
2940
+ }
2941
+
2942
+ function svgCmd (cmd, x, y) {
2943
+ let str = cmd + x;
2944
+ if (typeof y !== 'undefined') str += ' ' + y;
2945
+
2946
+ return str
2947
+ }
2948
+
2949
+ function qrToPath (data, size, margin) {
2950
+ let path = '';
2951
+ let moveBy = 0;
2952
+ let newRow = false;
2953
+ let lineLength = 0;
2954
+
2955
+ for (let i = 0; i < data.length; i++) {
2956
+ const col = Math.floor(i % size);
2957
+ const row = Math.floor(i / size);
2958
+
2959
+ if (!col && !newRow) newRow = true;
2960
+
2961
+ if (data[i]) {
2962
+ lineLength++;
2963
+
2964
+ if (!(i > 0 && col > 0 && data[i - 1])) {
2965
+ path += newRow
2966
+ ? svgCmd('M', col + margin, 0.5 + row + margin)
2967
+ : svgCmd('m', moveBy, 0);
2968
+
2969
+ moveBy = 0;
2970
+ newRow = false;
2971
+ }
2972
+
2973
+ if (!(col + 1 < size && data[i + 1])) {
2974
+ path += svgCmd('h', lineLength);
2975
+ lineLength = 0;
2976
+ }
2977
+ } else {
2978
+ moveBy++;
2979
+ }
2980
+ }
2981
+
2982
+ return path
2983
+ }
2984
+
2985
+ svgTag.render = function render (qrData, options, cb) {
2986
+ const opts = Utils.getOptions(options);
2987
+ const size = qrData.modules.size;
2988
+ const data = qrData.modules.data;
2989
+ const qrcodesize = size + opts.margin * 2;
2990
+
2991
+ const bg = !opts.color.light.a
2992
+ ? ''
2993
+ : '<path ' + getColorAttrib(opts.color.light, 'fill') +
2994
+ ' d="M0 0h' + qrcodesize + 'v' + qrcodesize + 'H0z"/>';
2995
+
2996
+ const path =
2997
+ '<path ' + getColorAttrib(opts.color.dark, 'stroke') +
2998
+ ' d="' + qrToPath(data, size, opts.margin) + '"/>';
2999
+
3000
+ const viewBox = 'viewBox="' + '0 0 ' + qrcodesize + ' ' + qrcodesize + '"';
3001
+
3002
+ const width = !opts.width ? '' : 'width="' + opts.width + '" height="' + opts.width + '" ';
3003
+
3004
+ const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path + '</svg>\n';
3005
+
3006
+ if (typeof cb === 'function') {
3007
+ cb(null, svgTag);
3008
+ }
3009
+
3010
+ return svgTag
3011
+ };
3012
+ return svgTag;
3013
+ }
3014
+
3015
+ var hasRequiredBrowser;
3016
+
3017
+ function requireBrowser () {
3018
+ if (hasRequiredBrowser) return browser;
3019
+ hasRequiredBrowser = 1;
3020
+ const canPromise = requireCanPromise();
3021
+
3022
+ const QRCode = requireQrcode();
3023
+ const CanvasRenderer = requireCanvas();
3024
+ const SvgRenderer = requireSvgTag();
3025
+
3026
+ function renderCanvas (renderFunc, canvas, text, opts, cb) {
3027
+ const args = [].slice.call(arguments, 1);
3028
+ const argsNum = args.length;
3029
+ const isLastArgCb = typeof args[argsNum - 1] === 'function';
3030
+
3031
+ if (!isLastArgCb && !canPromise()) {
3032
+ throw new Error('Callback required as last argument')
3033
+ }
3034
+
3035
+ if (isLastArgCb) {
3036
+ if (argsNum < 2) {
3037
+ throw new Error('Too few arguments provided')
3038
+ }
3039
+
3040
+ if (argsNum === 2) {
3041
+ cb = text;
3042
+ text = canvas;
3043
+ canvas = opts = undefined;
3044
+ } else if (argsNum === 3) {
3045
+ if (canvas.getContext && typeof cb === 'undefined') {
3046
+ cb = opts;
3047
+ opts = undefined;
3048
+ } else {
3049
+ cb = opts;
3050
+ opts = text;
3051
+ text = canvas;
3052
+ canvas = undefined;
3053
+ }
3054
+ }
3055
+ } else {
3056
+ if (argsNum < 1) {
3057
+ throw new Error('Too few arguments provided')
3058
+ }
3059
+
3060
+ if (argsNum === 1) {
3061
+ text = canvas;
3062
+ canvas = opts = undefined;
3063
+ } else if (argsNum === 2 && !canvas.getContext) {
3064
+ opts = text;
3065
+ text = canvas;
3066
+ canvas = undefined;
3067
+ }
3068
+
3069
+ return new Promise(function (resolve, reject) {
3070
+ try {
3071
+ const data = QRCode.create(text, opts);
3072
+ resolve(renderFunc(data, canvas, opts));
3073
+ } catch (e) {
3074
+ reject(e);
3075
+ }
3076
+ })
3077
+ }
3078
+
3079
+ try {
3080
+ const data = QRCode.create(text, opts);
3081
+ cb(null, renderFunc(data, canvas, opts));
3082
+ } catch (e) {
3083
+ cb(e);
3084
+ }
3085
+ }
3086
+
3087
+ browser.create = QRCode.create;
3088
+ browser.toCanvas = renderCanvas.bind(null, CanvasRenderer.render);
3089
+ browser.toDataURL = renderCanvas.bind(null, CanvasRenderer.renderToDataURL);
3090
+
3091
+ // only svg for now.
3092
+ browser.toString = renderCanvas.bind(null, function (data, _, opts) {
3093
+ return SvgRenderer.render(data, opts)
3094
+ });
3095
+ return browser;
3096
+ }
3097
+
3098
+ requireBrowser();
3099
+
3100
+ /** Solana Mainnet (beta) cluster, e.g. https://api.mainnet-beta.solana.com */
3101
+ const SOLANA_MAINNET_CHAIN = 'solana:mainnet';
3102
+
3103
+ //#region src/base64Utils.ts
3104
+ function fromUint8Array(byteArray) {
3105
+ return window.btoa(String.fromCharCode.call(null, ...byteArray));
3106
+ }
3107
+ function toUint8Array(base64EncodedByteArray) {
3108
+ return new Uint8Array(window.atob(base64EncodedByteArray).split("").map((c) => c.charCodeAt(0)));
3109
+ }
3110
+ //#endregion
3111
+ //#region src/embedded-modal/loadingSpinner.ts
3112
+ const modalHtml$1 = `
3113
+ <div class="mobile-wallet-adapter-embedded-loading-indicator" role="dialog" aria-modal="true" aria-labelledby="modal-title">
3114
+ <div data-modal-close style="position: absolute; width: 100%; height: 100%;"></div>
3115
+ <div class="mobile-wallet-adapter-embedded-loading-container">
3116
+ <div class="mobile-wallet-adapter-embedded-loading-animation"></div>
3117
+ </div>
3118
+ </div>
3119
+ `;
3120
+ const css$6 = `
3121
+ .mobile-wallet-adapter-embedded-loading-indicator {
3122
+ display: flex; /* Use flexbox to center content */
3123
+ justify-content: center; /* Center horizontally */
3124
+ align-items: start; /* Center vertically */
3125
+ position: fixed; /* Stay in place */
3126
+ z-index: 1; /* Sit on top */
3127
+ left: 0;
3128
+ top: 0;
3129
+ width: 100%; /* Full width */
3130
+ height: 100%; /* Full height */
3131
+ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
3132
+ overflow-y: auto; /* enable scrolling */
3133
+ }
3134
+
3135
+ .mobile-wallet-adapter-embedded-loading-container {
3136
+ display: flex;
3137
+ margin: auto;
3138
+ }
3139
+
3140
+ .mobile-wallet-adapter-embedded-loading-animation {
3141
+ position: relative;
3142
+ left: -9999px;
3143
+ width: 10px;
3144
+ height: 10px;
3145
+ border-radius: 5px;
3146
+ background-color: var(--spinner-color);
3147
+ color: var(--spinner-color);
3148
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3149
+ 9999px 0 0 0 var(--spinner-color),
3150
+ 10014px 0 0 0 var(--spinner-color);
3151
+ animation: dot-typing 1.5s infinite linear;
3152
+ }
3153
+
3154
+ @keyframes dot-typing {
3155
+ 0% {
3156
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3157
+ 9999px 0 0 0 var(--spinner-color),
3158
+ 10014px 0 0 0 var(--spinner-color);
3159
+ }
3160
+ 16.667% {
3161
+ box-shadow: 9984px -10px 0 0 var(--spinner-color),
3162
+ 9999px 0 0 0 var(--spinner-color),
3163
+ 10014px 0 0 0 var(--spinner-color);
3164
+ }
3165
+ 33.333% {
3166
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3167
+ 9999px 0 0 0 var(--spinner-color),
3168
+ 10014px 0 0 0 var(--spinner-color);
3169
+ }
3170
+ 50% {
3171
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3172
+ 9999px -10px 0 0 var(--spinner-color),
3173
+ 10014px 0 0 0 var(--spinner-color);
3174
+ }
3175
+ 66.667% {
3176
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3177
+ 9999px 0 0 0 var(--spinner-color),
3178
+ 10014px 0 0 0 var(--spinner-color);
3179
+ }
3180
+ 83.333% {
3181
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3182
+ 9999px 0 0 0 var(--spinner-color),
3183
+ 10014px -10px 0 0 var(--spinner-color);
3184
+ }
3185
+ 100% {
3186
+ box-shadow: 9984px 0 0 0 var(--spinner-color),
3187
+ 9999px 0 0 0 var(--spinner-color),
3188
+ 10014px 0 0 0 var(--spinner-color);
3189
+ }
3190
+ }
3191
+ `;
3192
+ var EmbeddedLoadingSpinner = class {
3193
+ #root = null;
3194
+ #eventListeners = {};
3195
+ #listenersAttached = false;
3196
+ dom = null;
3197
+ constructor() {
3198
+ this.init = this.init.bind(this);
3199
+ this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
3200
+ }
3201
+ async init() {
3202
+ console.log("Injecting modal");
3203
+ this.#injectHTML();
3204
+ }
3205
+ open = () => {
3206
+ console.debug("Modal open");
3207
+ this.#attachEventListeners();
3208
+ if (this.#root) this.#root.style.display = "flex";
3209
+ };
3210
+ close = (event = void 0) => {
3211
+ console.debug("Modal close");
3212
+ this.#removeEventListeners();
3213
+ if (this.#root) this.#root.style.display = "none";
3214
+ this.#eventListeners["close"]?.forEach((listener) => listener(event));
3215
+ };
3216
+ addEventListener(event, listener) {
3217
+ this.#eventListeners[event]?.push(listener) || (this.#eventListeners[event] = [listener]);
3218
+ return () => this.removeEventListener(event, listener);
3219
+ }
3220
+ removeEventListener(event, listener) {
3221
+ this.#eventListeners[event] = this.#eventListeners[event]?.filter((existingListener) => listener !== existingListener);
3222
+ }
3223
+ #injectHTML() {
3224
+ if (this.dom) return;
3225
+ this.#root = document.createElement("div");
3226
+ this.#root.id = "mobile-wallet-adapter-embedded-root-ui";
3227
+ this.#root.innerHTML = modalHtml$1;
3228
+ this.#root.style.display = "none";
3229
+ const styles = document.createElement("style");
3230
+ styles.id = "mobile-wallet-adapter-embedded-modal-styles";
3231
+ styles.textContent = css$6;
3232
+ const host = document.createElement("div");
3233
+ this.dom = host.attachShadow({ mode: "closed" });
3234
+ host.style.setProperty("--spinner-color", "#FFFFFF");
3235
+ this.dom.appendChild(styles);
3236
+ this.dom.appendChild(this.#root);
3237
+ document.body.appendChild(host);
3238
+ }
3239
+ #attachEventListeners() {
3240
+ if (!this.#root || this.#listenersAttached) return;
3241
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.addEventListener("click", (event) => {
3242
+ this.close(event);
3243
+ }));
3244
+ window.addEventListener("load", this.close);
3245
+ document.addEventListener("keydown", this.#handleKeyDown);
3246
+ this.#listenersAttached = true;
3247
+ }
3248
+ #removeEventListeners() {
3249
+ if (!this.#listenersAttached) return;
3250
+ window.removeEventListener("load", this.close);
3251
+ document.removeEventListener("keydown", this.#handleKeyDown);
3252
+ if (!this.#root) return;
3253
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.removeEventListener("click", this.close));
3254
+ this.#listenersAttached = false;
3255
+ }
3256
+ #handleKeyDown = (event) => {
3257
+ if (event.key === "Escape") this.close(event);
3258
+ };
3259
+ };
3260
+ //#endregion
3261
+ //#region src/embedded-modal/modal.ts
3262
+ const modalHtml = `
3263
+ <div class="mobile-wallet-adapter-embedded-modal-container" role="dialog" aria-modal="true" aria-labelledby="modal-title">
3264
+ <div data-modal-close style="position: absolute; width: 100%; height: 100%;"></div>
3265
+ <div class="mobile-wallet-adapter-embedded-modal-card">
3266
+ <div>
3267
+ <button data-modal-close class="mobile-wallet-adapter-embedded-modal-close">
3268
+ <svg width="14" height="14">
3269
+ <path d="M 6.7125,8.3036995 1.9082,13.108199 c -0.2113,0.2112 -0.4765,0.3168 -0.7957,0.3168 -0.3192,0 -0.5844,-0.1056 -0.7958,-0.3168 C 0.1056,12.896899 0,12.631699 0,12.312499 c 0,-0.3192 0.1056,-0.5844 0.3167,-0.7958 L 5.1212,6.7124995 0.3167,1.9082 C 0.1056,1.6969 0,1.4317 0,1.1125 0,0.7933 0.1056,0.5281 0.3167,0.3167 0.5281,0.1056 0.7933,0 1.1125,0 1.4317,0 1.6969,0.1056 1.9082,0.3167 L 6.7125,5.1212 11.5167,0.3167 C 11.7281,0.1056 11.9933,0 12.3125,0 c 0.3192,0 0.5844,0.1056 0.7957,0.3167 0.2112,0.2114 0.3168,0.4766 0.3168,0.7958 0,0.3192 -0.1056,0.5844 -0.3168,0.7957 L 8.3037001,6.7124995 13.1082,11.516699 c 0.2112,0.2114 0.3168,0.4766 0.3168,0.7958 0,0.3192 -0.1056,0.5844 -0.3168,0.7957 -0.2113,0.2112 -0.4765,0.3168 -0.7957,0.3168 -0.3192,0 -0.5844,-0.1056 -0.7958,-0.3168 z" />
3270
+ </svg>
3271
+ </button>
3272
+ </div>
3273
+ <div class="mobile-wallet-adapter-embedded-modal-content"></div>
3274
+ </div>
3275
+ </div>
3276
+ `;
3277
+ const css$5 = `
3278
+ .mobile-wallet-adapter-embedded-modal-container {
3279
+ display: flex; /* Use flexbox to center content */
3280
+ justify-content: center; /* Center horizontally */
3281
+ align-items: center; /* Center vertically */
3282
+ position: fixed; /* Stay in place */
3283
+ z-index: 2147483647; /* Sit on top */
3284
+ left: 0;
3285
+ top: 0;
3286
+ width: 100%; /* Full width */
3287
+ height: 100%; /* Full height */
3288
+ background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
3289
+ overflow-y: auto; /* enable scrolling */
3290
+ }
3291
+
3292
+ .mobile-wallet-adapter-embedded-modal-card {
3293
+ display: flex;
3294
+ flex-direction: column;
3295
+ margin: auto 20px;
3296
+ max-width: 780px;
3297
+ padding: 20px;
3298
+ border-radius: 24px;
3299
+ background: #ffffff;
3300
+ font-family: "Inter Tight", "PT Sans", Calibri, sans-serif;
3301
+ transform: translateY(-200%);
3302
+ animation: slide-in 0.5s forwards;
3303
+ }
3304
+
3305
+ @keyframes slide-in {
3306
+ 100% { transform: translateY(0%); }
3307
+ }
3308
+
3309
+ .mobile-wallet-adapter-embedded-modal-close {
3310
+ display: flex;
3311
+ align-items: center;
3312
+ justify-content: center;
3313
+ width: 32px;
3314
+ height: 32px;
3315
+ cursor: pointer;
3316
+ background: #e4e9e9;
3317
+ border: none;
3318
+ border-radius: 50%;
3319
+ }
3320
+
3321
+ .mobile-wallet-adapter-embedded-modal-close:focus-visible {
3322
+ outline-color: red;
3323
+ }
3324
+
3325
+ .mobile-wallet-adapter-embedded-modal-close svg {
3326
+ fill: #546266;
3327
+ transition: fill 200ms ease 0s;
3328
+ }
3329
+
3330
+ .mobile-wallet-adapter-embedded-modal-close:hover svg {
3331
+ fill: #fff;
3332
+ }
3333
+ `;
3334
+ const fonts = `
3335
+ <link rel="preconnect" href="https://fonts.googleapis.com">
3336
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
3337
+ <link href="https://fonts.googleapis.com/css2?family=Inter+Tight:ital,wght@0,100..900;1,100..900&display=swap" rel="stylesheet">
3338
+ `;
3339
+ var EmbeddedModal = class {
3340
+ #root = null;
3341
+ #eventListeners = {};
3342
+ #listenersAttached = false;
3343
+ dom = null;
3344
+ constructor() {
3345
+ this.init = this.init.bind(this);
3346
+ this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
3347
+ }
3348
+ async init() {
3349
+ console.log("Injecting modal");
3350
+ this.#injectHTML();
3351
+ }
3352
+ open = () => {
3353
+ console.debug("Modal open");
3354
+ this.#attachEventListeners();
3355
+ if (this.#root) this.#root.style.display = "flex";
3356
+ };
3357
+ close = (event = void 0) => {
3358
+ console.debug("Modal close");
3359
+ this.#removeEventListeners();
3360
+ if (this.#root) this.#root.style.display = "none";
3361
+ this.#eventListeners["close"]?.forEach((listener) => listener(event));
3362
+ };
3363
+ addEventListener(event, listener) {
3364
+ this.#eventListeners[event]?.push(listener) || (this.#eventListeners[event] = [listener]);
3365
+ return () => this.removeEventListener(event, listener);
3366
+ }
3367
+ removeEventListener(event, listener) {
3368
+ this.#eventListeners[event] = this.#eventListeners[event]?.filter((existingListener) => listener !== existingListener);
3369
+ }
3370
+ #injectHTML() {
3371
+ if (document.getElementById("mobile-wallet-adapter-embedded-root-ui")) {
3372
+ if (!this.#root) this.#root = document.getElementById("mobile-wallet-adapter-embedded-root-ui");
3373
+ return;
3374
+ }
3375
+ this.#root = document.createElement("div");
3376
+ this.#root.id = "mobile-wallet-adapter-embedded-root-ui";
3377
+ this.#root.innerHTML = modalHtml;
3378
+ this.#root.style.display = "none";
3379
+ const content = this.#root.querySelector(".mobile-wallet-adapter-embedded-modal-content");
3380
+ if (content) content.innerHTML = this.contentHtml;
3381
+ const styles = document.createElement("style");
3382
+ styles.id = "mobile-wallet-adapter-embedded-modal-styles";
3383
+ styles.textContent = css$5 + this.contentStyles;
3384
+ const host = document.createElement("div");
3385
+ host.innerHTML = fonts;
3386
+ this.dom = host.attachShadow({ mode: "closed" });
3387
+ this.dom.appendChild(styles);
3388
+ this.dom.appendChild(this.#root);
3389
+ document.body.appendChild(host);
3390
+ }
3391
+ #attachEventListeners() {
3392
+ if (!this.#root || this.#listenersAttached) return;
3393
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.addEventListener("click", this.close));
3394
+ window.addEventListener("load", this.close);
3395
+ document.addEventListener("keydown", this.#handleKeyDown);
3396
+ this.#listenersAttached = true;
3397
+ }
3398
+ #removeEventListeners() {
3399
+ if (!this.#listenersAttached) return;
3400
+ window.removeEventListener("load", this.close);
3401
+ document.removeEventListener("keydown", this.#handleKeyDown);
3402
+ if (!this.#root) return;
3403
+ [...this.#root.querySelectorAll("[data-modal-close]")].forEach((closer) => closer?.removeEventListener("click", this.close));
3404
+ this.#listenersAttached = false;
3405
+ }
3406
+ #handleKeyDown = (event) => {
3407
+ if (event.key === "Escape") this.close(event);
3408
+ };
3409
+ };
3410
+ //#endregion
3411
+ //#region src/embedded-modal/localConnectionModal.ts
3412
+ var LocalConnectionModal = class extends EmbeddedModal {
3413
+ contentStyles = css$3;
3414
+ contentHtml = ErrorDialogHtml$3;
3415
+ initWithCallback(callback) {
3416
+ super.init();
3417
+ this.#prepareLaunchAction(callback);
3418
+ }
3419
+ #prepareLaunchAction(callback) {
3420
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
3421
+ const listener = async () => {
3422
+ launchButton?.removeEventListener("click", listener);
3423
+ this.close();
3424
+ callback();
3425
+ };
3426
+ launchButton?.addEventListener("click", listener);
3427
+ }
3428
+ };
3429
+ const ErrorDialogHtml$3 = `
3430
+ <svg class="mobile-wallet-adapter-embedded-modal-launch-icon" width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
3431
+ <path d="M21.6 48C7.2 48 0 40.8 0 26.4V21.6C0 7.2 7.2 0 21.6 0H26.4C40.8 0 48 7.2 48 21.6V26.4C48 40.8 40.8 48 26.4 48H21.6Z" fill="#15994E"/>
3432
+ <mask id="mask0_189_522" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="8" y="8" width="32" height="32">
3433
+ <rect x="8" y="8" width="32" height="32" fill="#D9D9D9"/>
3434
+ </mask>
3435
+ <g mask="url(#mask0_189_522)">
3436
+ <mask id="mask1_189_522" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="8" y="8" width="32" height="32">
3437
+ <rect x="8" y="8" width="32" height="32" fill="#D9D9D9"/>
3438
+ </mask>
3439
+ <g mask="url(#mask1_189_522)">
3440
+ <path d="M22.1092 26.1208L19.4498 23.4615C19.1736 23.1851 18.8253 23.0468 18.4048 23.0468C17.9846 23.0468 17.6363 23.1851 17.3598 23.4615C17.0836 23.7377 16.9468 24.0861 16.9495 24.5065C16.9522 24.9267 17.0916 25.275 17.3678 25.5512L21.0405 29.2238C21.3463 29.5276 21.7031 29.6795 22.1108 29.6795C22.5184 29.6795 22.8742 29.5276 23.1782 29.2238L30.5918 21.8098C30.8683 21.5336 31.0065 21.1867 31.0065 20.7692C31.0065 20.3514 30.8683 20.0044 30.5918 19.7282C30.3156 19.4517 29.9673 19.3135 29.5468 19.3135C29.1266 19.3135 28.7784 19.4517 28.5022 19.7282L22.1092 26.1208ZM23.9998 37.6042C22.113 37.6042 20.3425 37.2473 18.6885 36.5335C17.0343 35.8197 15.5954 34.8512 14.3718 33.6278C13.1485 32.4043 12.18 30.9654 11.4662 29.3112C10.7524 27.6572 10.3955 25.8867 10.3955 23.9998C10.3955 22.113 10.7524 20.3425 11.4662 18.6885C12.18 17.0343 13.1485 15.5954 14.3718 14.3718C15.5954 13.1485 17.0343 12.18 18.6885 11.4662C20.3425 10.7524 22.113 10.3955 23.9998 10.3955C25.8867 10.3955 27.6572 10.7524 29.3112 11.4662C30.9654 12.18 32.4043 13.1485 33.6278 14.3718C34.8512 15.5954 35.8197 17.0343 36.5335 18.6885C37.2473 20.3425 37.6042 22.113 37.6042 23.9998C37.6042 25.8867 37.2473 27.6572 36.5335 29.3112C35.8197 30.9654 34.8512 32.4043 33.6278 33.6278C32.4043 34.8512 30.9654 35.8197 29.3112 36.5335C27.6572 37.2473 25.8867 37.6042 23.9998 37.6042Z" fill="white"/>
3441
+ </g>
3442
+ </g>
3443
+ </svg>
3444
+ <div class="mobile-wallet-adapter-embedded-modal-title">Ready to connect!</div>
3445
+ <div>
3446
+ <button data-modal-action id="mobile-wallet-adapter-launch-action" class="mobile-wallet-adapter-embedded-modal-launch-action">
3447
+ Connect Wallet
3448
+ </button>
3449
+ </div>
3450
+ `;
3451
+ const css$3 = `
3452
+ .mobile-wallet-adapter-embedded-modal-close {
3453
+ display: none;
3454
+ }
3455
+ .mobile-wallet-adapter-embedded-modal-content {
3456
+ text-align: center;
3457
+ min-width: 300px;
3458
+ }
3459
+ .mobile-wallet-adapter-embedded-modal-launch-icon {
3460
+ margin-top: 24px;
3461
+ }
3462
+ .mobile-wallet-adapter-embedded-modal-title {
3463
+ margin: 18px 100px 30px 100px;
3464
+ color: #000000;
3465
+ font-size: 2.75em;
3466
+ font-weight: 600;
3467
+ }
3468
+ .mobile-wallet-adapter-embedded-modal-launch-action {
3469
+ display: block;
3470
+ width: 100%;
3471
+ height: 56px;
3472
+ font-size: 1.25em;
3473
+ background: #000000;
3474
+ color: #FFFFFF;
3475
+ border-radius: 18px;
3476
+ }
3477
+ /* Smaller screens */
3478
+ @media all and (max-width: 600px) {
3479
+ .mobile-wallet-adapter-embedded-modal-title {
3480
+ font-size: 1.5em;
3481
+ margin-right: 12px;
3482
+ margin-left: 12px;
3483
+ }
3484
+ }
3485
+ `;
3486
+ //#endregion
3487
+ //#region src/embedded-modal/loopbackBlockedModal.ts
3488
+ var LoopbackPermissionBlockedModal = class extends EmbeddedModal {
3489
+ contentStyles = css$2;
3490
+ get contentHtml() {
3491
+ const instructions = getIsPwaLaunchedAsApp() ? "Long press the app icon on your home screen to open site settings" : "Tap the lock or settings icon in the address bar to open site settings";
3492
+ return ErrorDialogHtml$2.replace("{{PERMISSION_INSTRUCTION_DETAIL}}", instructions);
3493
+ }
3494
+ async init() {
3495
+ super.init();
3496
+ this.#prepareLaunchAction();
3497
+ }
3498
+ #prepareLaunchAction() {
3499
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
3500
+ const listener = async (event) => {
3501
+ launchButton?.removeEventListener("click", listener);
3502
+ this.close(event);
3503
+ };
3504
+ launchButton?.addEventListener("click", listener);
3505
+ }
3506
+ };
3507
+ const ErrorDialogHtml$2 = `
3508
+ <div class="mobile-wallet-adapter-embedded-modal-header">
3509
+ Local Wallet Connection
3510
+ </div>
3511
+ <svg width="48" height="48" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
3512
+ <path d="M21.6 48C7.2 48 0 40.8 0 26.4V21.6C0 7.2 7.2 0 21.6 0H26.4C40.8 0 48 7.2 48 21.6V26.4C48 40.8 40.8 48 26.4 48H21.6Z" fill="#ED1515"/>
3513
+ <mask id="mask0_147_1364" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="8" y="8" width="32" height="32">
3514
+ <rect x="8" y="8" width="32" height="32" fill="#D9D9D9"/>
3515
+ </mask>
3516
+ <g mask="url(#mask0_147_1364)">
3517
+ <path d="M20.1398 36.2705C19.7363 36.2705 19.3508 36.1945 18.9835 36.0425C18.6162 35.8907 18.2916 35.674 18.0098 35.3922L12.6072 29.9895C12.3254 29.7077 12.1086 29.3832 11.9568 29.0158C11.8048 28.6485 11.7288 28.2631 11.7288 27.8595V20.1395C11.7288 19.736 11.8048 19.3505 11.9568 18.9832C12.1086 18.6158 12.3254 18.2913 12.6072 18.0095L18.0098 12.6068C18.2916 12.3251 18.6162 12.1083 18.9835 11.9565C19.3508 11.8045 19.7363 11.7285 20.1398 11.7285H27.8598C28.2634 11.7285 28.6488 11.8045 29.0162 11.9565C29.3835 12.1083 29.708 12.3251 29.9898 12.6068L35.3925 18.0095C35.6743 18.2913 35.891 18.6158 36.0428 18.9832C36.1948 19.3505 36.2708 19.736 36.2708 20.1395V27.8595C36.2708 28.2631 36.1948 28.6485 36.0428 29.0158C35.891 29.3832 35.6743 29.7077 35.3925 29.9895L29.9898 35.3922C29.708 35.674 29.3835 35.8907 29.0162 36.0425C28.6488 36.1945 28.2634 36.2705 27.8598 36.2705H20.1398ZM20.1732 33.2372H27.8265L33.2375 27.8262V20.1728L27.8265 14.7618H20.1732L14.7622 20.1728V27.8262L20.1732 33.2372ZM23.9998 25.9538L26.7868 28.7408C27.0473 29.0013 27.3729 29.1302 27.7638 29.1275C28.1549 29.1248 28.4807 28.9933 28.7412 28.7328C29.0016 28.4724 29.1318 28.1466 29.1318 27.7555C29.1318 27.3646 29.0016 27.039 28.7412 26.7785L25.9542 23.9995L28.7412 21.2125C29.0016 20.9521 29.1318 20.6264 29.1318 20.2355C29.1318 19.8444 29.0016 19.5186 28.7412 19.2582C28.4807 18.9977 28.1549 18.8675 27.7638 18.8675C27.3729 18.8675 27.0473 18.9977 26.7868 19.2582L23.9998 22.0452L21.2128 19.2582C20.9524 18.9977 20.628 18.8675 20.2398 18.8675C19.8514 18.8675 19.5269 18.9977 19.2665 19.2582C19.006 19.5186 18.8758 19.8444 18.8758 20.2355C18.8758 20.6264 19.006 20.9521 19.2665 21.2125L22.0455 23.9995L19.2585 26.7865C18.998 27.047 18.8692 27.3713 18.8718 27.7595C18.8745 28.148 19.006 28.4724 19.2665 28.7328C19.5269 28.9933 19.8527 29.1235 20.2438 29.1235C20.6347 29.1235 20.9604 28.9933 21.2208 28.7328L23.9998 25.9538Z" fill="black"/>
3518
+ </g>
3519
+ </svg>
3520
+ <div class="mobile-wallet-adapter-embedded-modal-title">
3521
+ Your wallet connection is blocked
3522
+ </div>
3523
+ <div id="mobile-wallet-adapter-local-launch-message" class="mobile-wallet-adapter-embedded-modal-subtitle">
3524
+ Visit site settings in the address bar and allow "Apps on Device".
3525
+ </div>
3526
+
3527
+ <div class="mobile-wallet-adapter-embedded-modal-divider"><hr></div>
3528
+ <div class="mobile-wallet-adapter-embedded-modal-footer">
3529
+ <div class="mobile-wallet-adapter-embedded-modal-details">
3530
+ <!-- Clickable header (label associated with the checkbox) -->
3531
+ <label for="collapsible-1" class="mobile-wallet-adapter-embedded-modal-details-collapsible-header">
3532
+ <!-- Hidden checkbox to track state -->
3533
+ <input type="checkbox" id="collapsible-1" class="mobile-wallet-adapter-embedded-modal-details-collapsible-input">
3534
+ <span class="mobile-wallet-adapter-embedded-modal-details-collapsible-header-label">
3535
+ See details
3536
+ </span>
3537
+ <svg class="mobile-wallet-adapter-embedded-modal-details-collapsible-header-icon" width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
3538
+ <mask id="mask0_147_1382" style="mask-type:alpha" maskUnits="userSpaceOnUse" x="0" y="0" width="24" height="24">
3539
+ <rect width="24" height="24" fill="#D9D9D9"/>
3540
+ </mask>
3541
+ <g mask="url(#mask0_147_1382)">
3542
+ <path d="M11.9999 17.0811C11.8506 17.0811 11.7087 17.0563 11.5741 17.0067C11.4395 16.957 11.3162 16.8762 11.2042 16.7643L6.57924 12.1393C6.36801 11.9281 6.26656 11.667 6.27489 11.3561C6.28322 11.0453 6.39301 10.7842 6.60424 10.573C6.81547 10.3618 7.08069 10.2561 7.39989 10.2561C7.71909 10.2561 7.9843 10.3618 8.19554 10.573L11.9999 14.3773L15.8292 10.548C16.0405 10.3368 16.3015 10.2353 16.6124 10.2436C16.9233 10.252 17.1843 10.3618 17.3955 10.573C17.6068 10.7842 17.7124 11.0494 17.7124 11.3686C17.7124 11.6878 17.6068 11.9531 17.3955 12.1643L12.7955 16.7643C12.6836 16.8762 12.5603 16.957 12.4257 17.0067C12.2911 17.0563 12.1492 17.0811 11.9999 17.0811Z" fill="black"/>
3543
+ </g>
3544
+ </svg>
3545
+ </label>
3546
+
3547
+ <!-- Content to show/hide -->
3548
+ <ul class="mobile-wallet-adapter-embedded-modal-details-collapsible-content">
3549
+ <li>{{PERMISSION_INSTRUCTION_DETAIL}}</li>
3550
+ <li>Allow "Apps on Device"</li>
3551
+ </ul>
3552
+ </div>
3553
+ </div>
3554
+ <div>
3555
+ <button data-modal-action id="mobile-wallet-adapter-launch-action" class="mobile-wallet-adapter-embedded-modal-launch-action">
3556
+ Got it
3557
+ </button>
3558
+ </div>
3559
+ `;
3560
+ const css$2 = `
3561
+ .mobile-wallet-adapter-embedded-modal-close {
3562
+ display: none;
3563
+ }
3564
+ .mobile-wallet-adapter-embedded-modal-content {
3565
+ text-align: center;
3566
+ }
3567
+ .mobile-wallet-adapter-embedded-modal-header {
3568
+ margin: 18px auto 30px auto;
3569
+ color: #7D9093;
3570
+ font-size: 1.0em;
3571
+ font-weight: 500;
3572
+ }
3573
+ .mobile-wallet-adapter-embedded-modal-title {
3574
+ margin: 18px 100px auto 100px;
3575
+ color: #000000;
3576
+ font-size: 2.75em;
3577
+ font-weight: 600;
3578
+ }
3579
+ .mobile-wallet-adapter-embedded-modal-subtitle {
3580
+ margin: 12px 60px 30px 60px;
3581
+ color: #7D9093;
3582
+ font-size: 1.25em;
3583
+ font-weight: 400;
3584
+ }
3585
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-header {
3586
+ display: flex;
3587
+ flex-direction: row;
3588
+ justify-content: space-between;
3589
+ margin: 10px auto 10px auto;
3590
+ color: #000000;
3591
+ font-size: 1.5em;
3592
+ font-weight: 600;
3593
+ cursor: pointer; /* Show pointer on hover */
3594
+ transition: background 0.2s ease; /* Smooth background change */
3595
+ }
3596
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-header-icon {
3597
+ transition: rotate 0.3s ease;
3598
+ }
3599
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-input {
3600
+ display: none; /* Hide the checkbox */
3601
+ }
3602
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-content {
3603
+ margin: 0px auto 40px auto;
3604
+ max-height: 0px; /* Collapse content */
3605
+ overflow: hidden; /* Hide overflow when collapsed */
3606
+ transition: max-height 0.3s ease; /* Smooth transition */
3607
+ }
3608
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-content li {
3609
+ margin: 20px auto;
3610
+ color: #000000;
3611
+ font-size: 1.25em;
3612
+ font-weight: 400;
3613
+ text-align: left;
3614
+ }
3615
+ /* When checkbox is checked, show content */
3616
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-header:has(> input:checked) ~ .mobile-wallet-adapter-embedded-modal-details-collapsible-content {
3617
+ max-height: 300px;
3618
+ }
3619
+ .mobile-wallet-adapter-embedded-modal-details-collapsible-header:has(> input:checked) > .mobile-wallet-adapter-embedded-modal-details-collapsible-header-icon {
3620
+ rotate: 180deg;
3621
+ }
3622
+ .mobile-wallet-adapter-embedded-modal-launch-action {
3623
+ display: block;
3624
+ width: 100%;
3625
+ height: 56px;
3626
+ /*margin-top: 40px;*/
3627
+ font-size: 1.25em;
3628
+ /*line-height: 24px;*/
3629
+ /*letter-spacing: -1%;*/
3630
+ background: #000000;
3631
+ color: #FFFFFF;
3632
+ border-radius: 18px;
3633
+ }
3634
+ /* Smaller screens */
3635
+ @media all and (max-width: 600px) {
3636
+ .mobile-wallet-adapter-embedded-modal-title {
3637
+ font-size: 1.75em;
3638
+ margin-right: 12px;
3639
+ margin-left: 12px;
3640
+ }
3641
+ .mobile-wallet-adapter-embedded-modal-subtitle {
3642
+ margin-right: 12px;
3643
+ margin-left: 12px;
3644
+ }
3645
+ }
3646
+ `;
3647
+ //#endregion
3648
+ //#region src/embedded-modal/loopbackPermissionModal.ts
3649
+ var LoopbackPermissionModal = class extends EmbeddedModal {
3650
+ contentStyles = css$1;
3651
+ contentHtml = ErrorDialogHtml$1;
3652
+ async init() {
3653
+ super.init();
3654
+ this.#prepareLaunchAction();
3655
+ }
3656
+ #prepareLaunchAction() {
3657
+ const launchButton = this.dom?.getElementById("mobile-wallet-adapter-launch-action");
3658
+ const listener = async () => {
3659
+ launchButton?.removeEventListener("click", listener);
3660
+ try {
3661
+ await fetch("http://localhost");
3662
+ } catch {}
3663
+ this.close();
3664
+ };
3665
+ launchButton?.addEventListener("click", listener);
3666
+ }
3667
+ };
3668
+ const ErrorDialogHtml$1 = `
3669
+ <div class="mobile-wallet-adapter-embedded-modal-title">Allow connections to your wallet</div>
3670
+ <div id="mobile-wallet-adapter-local-launch-message" class="mobile-wallet-adapter-embedded-modal-subtitle">
3671
+ Tap "Allow" on the next screen
3672
+ </div>
3673
+ <svg class="mobile-wallet-adapter-embedded-modal-permission-prompt-mock" xmlns="http://www.w3.org/2000/svg" width="281" height="83" viewBox="0 0 281 83" fill="none">
3674
+ <rect width="281" height="83" rx="22" fill="#F0F3F5"/>
3675
+ <path d="M254.194 64L252.626 56.657H254.047L254.866 61.452L254.985 62.278H255.02L255.146 61.452L255.993 57.497H257.4L258.254 61.431L258.373 62.278H258.415L258.534 61.431L259.346 56.657H260.718L259.143 64H257.673L256.826 59.961L256.693 59.093H256.651L256.511 59.961L255.664 64H254.194Z" fill="black"/>
3676
+ <path d="M248.837 64.231C248.147 64.231 247.54 64.07 247.017 63.748C246.495 63.426 246.086 62.978 245.792 62.404C245.498 61.83 245.351 61.1673 245.351 60.416V60.241C245.351 59.4897 245.498 58.827 245.792 58.253C246.086 57.679 246.495 57.2333 247.017 56.916C247.54 56.594 248.147 56.433 248.837 56.433C249.528 56.433 250.135 56.594 250.657 56.916C251.18 57.2333 251.588 57.679 251.882 58.253C252.176 58.827 252.323 59.4897 252.323 60.241V60.416C252.323 61.1673 252.176 61.83 251.882 62.404C251.588 62.978 251.18 63.426 250.657 63.748C250.135 64.07 249.528 64.231 248.837 64.231ZM248.837 62.824C249.43 62.824 249.897 62.607 250.237 62.173C250.583 61.7343 250.755 61.1417 250.755 60.395V60.262C250.755 59.5107 250.583 58.918 250.237 58.484C249.897 58.05 249.43 57.833 248.837 57.833C248.249 57.833 247.783 58.05 247.437 58.484C247.092 58.918 246.919 59.5107 246.919 60.262V60.395C246.919 61.1417 247.092 61.7343 247.437 62.173C247.783 62.607 248.249 62.824 248.837 62.824Z" fill="black"/>
3677
+ <path d="M242.298 64.231C241.467 64.231 240.814 63.993 240.338 63.517C239.866 63.0364 239.631 62.3737 239.631 61.529V53.78H241.178V61.389C241.178 62.3317 241.591 62.803 242.417 62.803C242.65 62.803 242.865 62.7587 243.061 62.67C243.257 62.5814 243.464 62.4367 243.684 62.236L244.538 63.377C244.225 63.6664 243.884 63.881 243.516 64.021C243.152 64.161 242.746 64.231 242.298 64.231ZM237.51 55.061V53.78H240.611V55.061H237.51Z" fill="black"/>
3678
+ <path d="M234.463 64.231C233.633 64.231 232.979 63.993 232.503 63.517C232.032 63.0364 231.796 62.3737 231.796 61.529V53.78H233.343V61.389C233.343 62.3317 233.756 62.803 234.582 62.803C234.816 62.803 235.03 62.7587 235.226 62.67C235.422 62.5814 235.63 62.4367 235.849 62.236L236.703 63.377C236.391 63.6664 236.05 63.881 235.681 64.021C235.317 64.161 234.911 64.231 234.463 64.231ZM229.675 55.061V53.78H232.776V55.061H229.675Z" fill="black"/>
3679
+ <path d="M221.442 64L224.557 53.976H226.132L229.233 64H227.581L225.642 56.972L225.341 55.761H225.299L225.005 56.972L223.073 64H221.442ZM222.835 61.634L223.255 60.29H227.371L227.805 61.634H222.835Z" fill="black"/>
3680
+ <path d="M178.261 64L175.034 60.066V60.024L178.121 56.657H180.011L176.504 60.423V59.632L180.165 64H178.261ZM173.543 64V53.78H175.097V64H173.543Z" fill="#7D9093" fill-opacity="0.5"/>
3681
+ <path d="M169.306 64.224C168.588 64.224 167.958 64.0653 167.416 63.748C166.88 63.426 166.462 62.9803 166.163 62.411C165.865 61.837 165.715 61.1673 165.715 60.402V60.248C165.715 59.4873 165.862 58.8223 166.156 58.253C166.45 57.679 166.863 57.2333 167.395 56.916C167.927 56.594 168.546 56.433 169.25 56.433C169.978 56.433 170.59 56.6056 171.084 56.951C171.579 57.2917 171.955 57.777 172.211 58.407L170.874 58.995C170.72 58.6123 170.508 58.323 170.237 58.127C169.967 57.9263 169.633 57.826 169.236 57.826C168.63 57.826 168.149 58.0383 167.794 58.463C167.444 58.883 167.269 59.4616 167.269 60.199V60.465C167.269 61.1837 167.454 61.7577 167.822 62.187C168.196 62.6163 168.69 62.831 169.306 62.831C169.712 62.831 170.06 62.733 170.349 62.537C170.639 62.341 170.877 62.0423 171.063 61.641L172.379 62.285C172.188 62.6957 171.941 63.0457 171.637 63.335C171.334 63.6243 170.986 63.846 170.594 64C170.202 64.1493 169.773 64.224 169.306 64.224Z" fill="#7D9093" fill-opacity="0.5"/>
3682
+ <path d="M161.003 64.231C160.312 64.231 159.706 64.07 159.183 63.748C158.66 63.426 158.252 62.978 157.958 62.404C157.664 61.83 157.517 61.1673 157.517 60.416V60.241C157.517 59.4897 157.664 58.827 157.958 58.253C158.252 57.679 158.66 57.2333 159.183 56.916C159.706 56.594 160.312 56.433 161.003 56.433C161.694 56.433 162.3 56.594 162.823 56.916C163.346 57.2333 163.754 57.679 164.048 58.253C164.342 58.827 164.489 59.4897 164.489 60.241V60.416C164.489 61.1673 164.342 61.83 164.048 62.404C163.754 62.978 163.346 63.426 162.823 63.748C162.3 64.07 161.694 64.231 161.003 64.231ZM161.003 62.824C161.596 62.824 162.062 62.607 162.403 62.173C162.748 61.7343 162.921 61.1417 162.921 60.395V60.262C162.921 59.5107 162.748 58.918 162.403 58.484C162.062 58.05 161.596 57.833 161.003 57.833C160.415 57.833 159.948 58.05 159.603 58.484C159.258 58.918 159.085 59.5107 159.085 60.262V60.395C159.085 61.1417 159.258 61.7343 159.603 62.173C159.948 62.607 160.415 62.824 161.003 62.824Z" fill="#7D9093" fill-opacity="0.5"/>
3683
+ <path d="M154.463 64.231C153.633 64.231 152.979 63.993 152.503 63.517C152.032 63.0364 151.796 62.3737 151.796 61.529V53.78H153.343V61.389C153.343 62.3317 153.756 62.803 154.582 62.803C154.816 62.803 155.03 62.7587 155.226 62.67C155.422 62.5814 155.63 62.4367 155.849 62.236L156.703 63.377C156.391 63.6664 156.05 63.881 155.681 64.021C155.317 64.161 154.911 64.231 154.463 64.231ZM149.675 55.061V53.78H152.776V55.061H149.675Z" fill="#7D9093" fill-opacity="0.5"/>
3684
+ <path d="M142.24 64V53.976H145.544C146.421 53.976 147.112 54.1953 147.616 54.634C148.12 55.0726 148.372 55.6583 148.372 56.391V56.566C148.372 57.0886 148.246 57.5366 147.994 57.91C147.742 58.2833 147.38 58.5586 146.909 58.736V58.792C147.492 58.9226 147.947 59.2003 148.274 59.625C148.605 60.045 148.771 60.5606 148.771 61.172V61.361C148.771 61.893 148.645 62.3573 148.393 62.754C148.145 63.1506 147.795 63.4586 147.343 63.678C146.895 63.8926 146.365 64 145.754 64H142.24ZM143.794 62.656H145.572C146.085 62.656 146.482 62.5253 146.762 62.264C147.042 62.0026 147.182 61.6293 147.182 61.144V60.99C147.182 60.5046 147.037 60.1313 146.748 59.87C146.463 59.604 146.05 59.471 145.509 59.471H143.36V58.183H145.32C145.791 58.183 146.153 58.064 146.405 57.826C146.657 57.588 146.783 57.2496 146.783 56.811V56.685C146.783 56.2416 146.657 55.9033 146.405 55.67C146.157 55.4366 145.796 55.32 145.32 55.32H143.794V62.656Z" fill="#7D9093" fill-opacity="0.5"/>
3685
+ <rect x="18" y="17" width="246" height="7" rx="3.5" fill="#7D9093" fill-opacity="0.26"/>
3686
+ <rect x="18" y="33" width="82" height="7" rx="3.5" fill="#7D9093" fill-opacity="0.26"/>
3687
+ </svg>
3688
+ <div>
3689
+ <button data-modal-action id="mobile-wallet-adapter-launch-action" class="mobile-wallet-adapter-embedded-modal-launch-action">
3690
+ Continue to Allow
3691
+ </button>
3692
+ </div>
3693
+ `;
3694
+ const css$1 = `
3695
+ .mobile-wallet-adapter-embedded-modal-close {
3696
+ display: none;
3697
+ }
3698
+ .mobile-wallet-adapter-embedded-modal-content {
3699
+ text-align: center;
3700
+ }
3701
+ .mobile-wallet-adapter-embedded-modal-title {
3702
+ margin: 18px 100px auto 100px;
3703
+ color: #000000;
3704
+ font-size: 2.75em;
3705
+ font-weight: 600;
3706
+ }
3707
+ .mobile-wallet-adapter-embedded-modal-subtitle {
3708
+ margin: 20px 60px 40px 60px;
3709
+ color: #7D9093;
3710
+ font-size: 1.25em;
3711
+ font-weight: 400;
3712
+ }
3713
+ .mobile-wallet-adapter-embedded-modal-permission-prompt-mock {
3714
+ width: 90%;
3715
+ height: auto;
3716
+ margin: 0 auto 30px auto;
3717
+ display: block;
3718
+ }
3719
+ .mobile-wallet-adapter-embedded-modal-launch-action {
3720
+ display: block;
3721
+ width: 100%;
3722
+ height: 56px;
3723
+ font-size: 1.25em;
3724
+ background: #000000;
3725
+ color: #FFFFFF;
3726
+ border-radius: 18px;
3727
+ }
3728
+ /* Smaller screens */
3729
+ @media all and (max-width: 600px) {
3730
+ .mobile-wallet-adapter-embedded-modal-title {
3731
+ font-size: 1.5em;
3732
+ margin-right: 12px;
3733
+ margin-left: 12px;
3734
+ }
3735
+ .mobile-wallet-adapter-embedded-modal-subtitle {
3736
+ margin-right: 12px;
3737
+ margin-left: 12px;
3738
+ }
3739
+ }
3740
+ `;
3741
+ function isSolanaMobileWebShell(userAgentString) {
3742
+ return userAgentString.includes("Solana Mobile Web Shell");
3743
+ }
3744
+ function getIsPwaLaunchedAsApp() {
3745
+ const isAndroidTwa = typeof document !== "undefined" && document.referrer.startsWith("android-app://");
3746
+ if (typeof window == "undefined") return isAndroidTwa;
3747
+ const isStandalone = window.matchMedia("(display-mode: standalone)").matches;
3748
+ const isFullscreen = window.matchMedia("(display-mode: fullscreen)").matches;
3749
+ const isMinimalUI = window.matchMedia("(display-mode: minimal-ui)").matches;
3750
+ return isAndroidTwa || isStandalone || isFullscreen || isMinimalUI;
3751
+ }
3752
+ async function checkLocalNetworkAccessPermission() {
3753
+ if (typeof navigator !== "undefined" && isSolanaMobileWebShell(navigator.userAgent)) return;
3754
+ try {
3755
+ const lnaPermission = await navigator.permissions.query({ name: "loopback-network" });
3756
+ if (lnaPermission.state === "granted") return;
3757
+ else if (lnaPermission.state === "denied") {
3758
+ const modal = new LoopbackPermissionBlockedModal();
3759
+ modal.init();
3760
+ modal.open();
3761
+ throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, "Local Network Access permission denied");
3762
+ } else if (lnaPermission.state === "prompt") {
3763
+ const modal = new LoopbackPermissionModal();
3764
+ if (await new Promise((resolve, reject) => {
3765
+ modal.addEventListener("close", (event) => {
3766
+ if (event) reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection cancelled by user", { event }));
3767
+ });
3768
+ lnaPermission.onchange = () => {
3769
+ lnaPermission.onchange = null;
3770
+ resolve(lnaPermission.state);
3771
+ };
3772
+ modal.init();
3773
+ modal.open();
3774
+ }) === "granted") {
3775
+ const modal = new LocalConnectionModal();
3776
+ await new Promise((resolve, reject) => {
3777
+ modal.addEventListener("close", (event) => {
3778
+ if (event) reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection cancelled by user", { event }));
3779
+ });
3780
+ modal.initWithCallback(async () => {
3781
+ resolve(true);
3782
+ });
3783
+ modal.open();
3784
+ });
3785
+ return;
3786
+ } else return await checkLocalNetworkAccessPermission();
3787
+ }
3788
+ throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, "Local Network Access permission unknown");
3789
+ } catch (e) {
3790
+ if (e instanceof TypeError && (e.message.includes("loopback-network") || e.message.includes("local-network-access"))) return;
3791
+ if (e instanceof SolanaMobileWalletAdapterError) throw e;
3792
+ throw new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_LOOPBACK_ACCESS_BLOCKED, e instanceof Error ? e.message : "Local Network Access permission unknown");
3793
+ }
3794
+ }
3795
+ //#endregion
3796
+ //#region src/icon.ts
3797
+ const icon = "data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZmlsbC1ydWxlPSJldmVub2RkIiBjbGlwLXJ1bGU9ImV2ZW5vZGQiIGQ9Ik03IDIuNUgxN0MxNy44Mjg0IDIuNSAxOC41IDMuMTcxNTcgMTguNSA0VjIwQzE4LjUgMjAuODI4NCAxNy44Mjg0IDIxLjUgMTcgMjEuNUg3QzYuMTcxNTcgMjEuNSA1LjUgMjAuODI4NCA1LjUgMjBWNEM1LjUgMy4xNzE1NyA2LjE3MTU3IDIuNSA3IDIuNVpNMyA0QzMgMS43OTA4NiA0Ljc5MDg2IDAgNyAwSDE3QzE5LjIwOTEgMCAyMSAxLjc5MDg2IDIxIDRWMjBDMjEgMjIuMjA5MSAxOS4yMDkxIDI0IDE3IDI0SDdDNC43OTA4NiAyNCAzIDIyLjIwOTEgMyAyMFY0Wk0xMSA0LjYxNTM4QzEwLjQ0NzcgNC42MTUzOCAxMCA1LjA2MzEgMTAgNS42MTUzOFY2LjM4NDYyQzEwIDYuOTM2OSAxMC40NDc3IDcuMzg0NjIgMTEgNy4zODQ2MkgxM0MxMy41NTIzIDcuMzg0NjIgMTQgNi45MzY5IDE0IDYuMzg0NjJWNS42MTUzOEMxNCA1LjA2MzEgMTMuNTUyMyA0LjYxNTM4IDEzIDQuNjE1MzhIMTFaIiBmaWxsPSIjRENCOEZGIi8+Cjwvc3ZnPgo=";
3798
+ //#endregion
3799
+ //#region src/wallet.ts
3800
+ const SolanaMobileWalletAdapterWalletName = "Mobile Wallet Adapter";
3801
+ const SIGNATURE_LENGTH_IN_BYTES = 64;
3802
+ const DEFAULT_FEATURES = [
3803
+ SolanaSignAndSendTransaction,
3804
+ SolanaSignTransaction,
3805
+ SolanaSignMessage,
3806
+ SolanaSignIn
3807
+ ];
3808
+ const WALLET_ASSOCIATION_TIMEOUT = 3e4;
3809
+ function getErrorMessage(error) {
3810
+ return error instanceof Error ? error.message : "Unknown error";
3811
+ }
3812
+ var LocalSolanaMobileWalletAdapterWallet = class {
3813
+ #listeners = {};
3814
+ #version = "1.0.0";
3815
+ #name = SolanaMobileWalletAdapterWalletName;
3816
+ #url = "https://solanamobile.com/wallets";
3817
+ #icon = icon;
3818
+ #appIdentity;
3819
+ #authorization;
3820
+ #authorizationCache;
3821
+ #connecting = false;
3822
+ /**
3823
+ * Every time the connection is recycled in some way (eg. `disconnect()` is called)
3824
+ * increment this and use it to make sure that `transact` calls from the previous
3825
+ * 'generation' don't continue to do work and throw exceptions.
3826
+ */
3827
+ #connectionGeneration = 0;
3828
+ #chains = [];
3829
+ #chainSelector;
3830
+ #optionalFeatures;
3831
+ #onWalletNotFound;
3832
+ get version() {
3833
+ return this.#version;
3834
+ }
3835
+ get name() {
3836
+ return this.#name;
3837
+ }
3838
+ get url() {
3839
+ return this.#url;
3840
+ }
3841
+ get icon() {
3842
+ return this.#icon;
3843
+ }
3844
+ get chains() {
3845
+ return this.#chains;
3846
+ }
3847
+ get features() {
3848
+ return {
3849
+ [StandardConnect]: {
3850
+ version: "1.0.0",
3851
+ connect: this.#connect
3852
+ },
3853
+ [StandardDisconnect]: {
3854
+ version: "1.0.0",
3855
+ disconnect: this.#disconnect
3856
+ },
3857
+ [StandardEvents]: {
3858
+ version: "1.0.0",
3859
+ on: this.#on
3860
+ },
3861
+ [SolanaSignMessage]: {
3862
+ version: "1.0.0",
3863
+ signMessage: this.#signMessage
3864
+ },
3865
+ [SolanaSignIn]: {
3866
+ version: "1.0.0",
3867
+ signIn: this.#signIn
3868
+ },
3869
+ ...this.#optionalFeatures
3870
+ };
3871
+ }
3872
+ get accounts() {
3873
+ return this.#authorization?.accounts ?? [];
3874
+ }
3875
+ constructor(config) {
3876
+ this.#authorizationCache = config.authorizationCache;
3877
+ this.#appIdentity = config.appIdentity;
3878
+ this.#chains = config.chains;
3879
+ this.#chainSelector = config.chainSelector;
3880
+ this.#onWalletNotFound = config.onWalletNotFound;
3881
+ this.#optionalFeatures = {
3882
+ [SolanaSignAndSendTransaction]: {
3883
+ version: "1.0.0",
3884
+ supportedTransactionVersions: ["legacy", 0],
3885
+ signAndSendTransaction: this.#signAndSendTransaction
3886
+ },
3887
+ [SolanaSignTransaction]: {
3888
+ version: "1.0.0",
3889
+ supportedTransactionVersions: ["legacy", 0],
3890
+ signTransaction: this.#signTransaction
3891
+ }
3892
+ };
3893
+ }
3894
+ get connected() {
3895
+ return !!this.#authorization;
3896
+ }
3897
+ get isAuthorized() {
3898
+ return !!this.#authorization;
3899
+ }
3900
+ get currentAuthorization() {
3901
+ return this.#authorization;
3902
+ }
3903
+ get cachedAuthorizationResult() {
3904
+ return this.#authorizationCache.get();
3905
+ }
3906
+ #on = (event, listener) => {
3907
+ this.#listeners[event]?.push(listener) || (this.#listeners[event] = [listener]);
3908
+ return () => this.#off(event, listener);
3909
+ };
3910
+ #emit(event, ...args) {
3911
+ this.#listeners[event]?.forEach((listener) => listener.apply(null, args));
3912
+ }
3913
+ #off(event, listener) {
3914
+ this.#listeners[event] = this.#listeners[event]?.filter((existingListener) => listener !== existingListener);
3915
+ }
3916
+ #connect = async ({ silent } = {}) => {
3917
+ if (this.#connecting || this.connected) return { accounts: this.accounts };
3918
+ this.#connecting = true;
3919
+ try {
3920
+ if (silent) {
3921
+ const cachedAuthorization = await this.#authorizationCache.get();
3922
+ if (cachedAuthorization) {
3923
+ await this.#handleWalletCapabilitiesResult(cachedAuthorization.capabilities);
3924
+ await this.#handleAuthorizationResult(cachedAuthorization);
3925
+ } else return { accounts: this.accounts };
3926
+ } else await this.#performAuthorization();
3927
+ } catch (e) {
3928
+ throw new Error(getErrorMessage(e), { cause: e });
3929
+ } finally {
3930
+ this.#connecting = false;
3931
+ }
3932
+ return { accounts: this.accounts };
3933
+ };
3934
+ #performAuthorization = async (signInPayload) => {
3935
+ try {
3936
+ const cachedAuthorizationResult = await this.#authorizationCache.get();
3937
+ if (cachedAuthorizationResult) {
3938
+ this.#handleAuthorizationResult(cachedAuthorizationResult);
3939
+ return cachedAuthorizationResult;
3940
+ }
3941
+ const selectedChain = await this.#chainSelector.select(this.#chains);
3942
+ return await this.#transact(async (wallet) => {
3943
+ const [capabilities, mwaAuthorizationResult] = await Promise.all([wallet.getCapabilities(), wallet.authorize({
3944
+ chain: selectedChain,
3945
+ identity: this.#appIdentity,
3946
+ sign_in_payload: signInPayload
3947
+ })]);
3948
+ const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
3949
+ const authorization = {
3950
+ ...mwaAuthorizationResult,
3951
+ accounts,
3952
+ chain: selectedChain,
3953
+ capabilities
3954
+ };
3955
+ Promise.all([
3956
+ this.#handleWalletCapabilitiesResult(capabilities),
3957
+ this.#authorizationCache.set(authorization),
3958
+ this.#handleAuthorizationResult(authorization)
3959
+ ]);
3960
+ return authorization;
3961
+ });
3962
+ } catch (e) {
3963
+ throw new Error(getErrorMessage(e), { cause: e });
3964
+ }
3965
+ };
3966
+ #handleAuthorizationResult = async (authorization) => {
3967
+ const didPublicKeysChange = this.#authorization == null || this.#authorization?.accounts.length !== authorization.accounts.length || this.#authorization.accounts.some((account, ii) => account.address !== authorization.accounts[ii].address);
3968
+ this.#authorization = authorization;
3969
+ if (didPublicKeysChange) this.#emit("change", { accounts: this.accounts });
3970
+ };
3971
+ #handleWalletCapabilitiesResult = async (capabilities) => {
3972
+ const supportsSignTransaction = capabilities.features.includes("solana:signTransactions");
3973
+ const supportsSignAndSendTransaction = capabilities.supports_sign_and_send_transactions;
3974
+ const didCapabilitiesChange = SolanaSignAndSendTransaction in this.features !== supportsSignAndSendTransaction || SolanaSignTransaction in this.features !== supportsSignTransaction;
3975
+ this.#optionalFeatures = {
3976
+ ...(supportsSignAndSendTransaction || !supportsSignAndSendTransaction && !supportsSignTransaction) && { [SolanaSignAndSendTransaction]: {
3977
+ version: "1.0.0",
3978
+ supportedTransactionVersions: ["legacy", 0],
3979
+ signAndSendTransaction: this.#signAndSendTransaction
3980
+ } },
3981
+ ...supportsSignTransaction && { [SolanaSignTransaction]: {
3982
+ version: "1.0.0",
3983
+ supportedTransactionVersions: ["legacy", 0],
3984
+ signTransaction: this.#signTransaction
3985
+ } }
3986
+ };
3987
+ if (didCapabilitiesChange) this.#emit("change", { features: this.features });
3988
+ };
3989
+ #performReauthorization = async (wallet, authToken, chain) => {
3990
+ try {
3991
+ const [capabilities, mwaAuthorizationResult] = await Promise.all([this.#authorization?.capabilities ?? await wallet.getCapabilities(), wallet.authorize({
3992
+ auth_token: authToken,
3993
+ identity: this.#appIdentity,
3994
+ chain
3995
+ })]);
3996
+ const accounts = this.#accountsToWalletStandardAccounts(mwaAuthorizationResult.accounts);
3997
+ const authorization = {
3998
+ ...mwaAuthorizationResult,
3999
+ accounts,
4000
+ chain,
4001
+ capabilities
4002
+ };
4003
+ Promise.all([this.#authorizationCache.set(authorization), this.#handleAuthorizationResult(authorization)]);
4004
+ } catch (e) {
4005
+ this.#disconnect();
4006
+ throw new Error(getErrorMessage(e), { cause: e });
4007
+ }
4008
+ };
4009
+ #disconnect = async () => {
4010
+ this.#authorizationCache.clear();
4011
+ this.#connecting = false;
4012
+ this.#connectionGeneration++;
4013
+ this.#authorization = void 0;
4014
+ this.#emit("change", { accounts: this.accounts });
4015
+ };
4016
+ #transact = async (callback) => {
4017
+ const walletUriBase = this.#authorization?.wallet_uri_base;
4018
+ const config = walletUriBase ? { baseUri: walletUriBase } : void 0;
4019
+ const currentConnectionGeneration = this.#connectionGeneration;
4020
+ const loadingSpinner = new EmbeddedLoadingSpinner();
4021
+ try {
4022
+ let associating = true;
4023
+ let timeout = void 0;
4024
+ const result = await Promise.race([checkLocalNetworkAccessPermission().then(async () => {
4025
+ loadingSpinner.init();
4026
+ const { wallet, close } = await startScenario(config);
4027
+ associating = false;
4028
+ loadingSpinner.addEventListener("close", (event) => {
4029
+ if (event) close();
4030
+ });
4031
+ loadingSpinner.open();
4032
+ const result = await callback(await wallet);
4033
+ loadingSpinner.close();
4034
+ close();
4035
+ return result;
4036
+ }), new Promise((_, reject) => {
4037
+ timeout = setTimeout(() => {
4038
+ if (associating) reject(new SolanaMobileWalletAdapterError(SolanaMobileWalletAdapterErrorCode.ERROR_ASSOCIATION_CANCELLED, "Wallet connection timed out", { event: void 0 }));
4039
+ }, WALLET_ASSOCIATION_TIMEOUT);
4040
+ })]);
4041
+ clearTimeout(timeout);
4042
+ return result;
4043
+ } catch (e) {
4044
+ loadingSpinner.close();
4045
+ if (this.#connectionGeneration !== currentConnectionGeneration) await new Promise(() => {});
4046
+ if (e instanceof Error && e.name === "SolanaMobileWalletAdapterError" && e.code === "ERROR_WALLET_NOT_FOUND") await this.#onWalletNotFound(this);
4047
+ throw e;
4048
+ }
4049
+ };
4050
+ #assertIsAuthorized = () => {
4051
+ if (!this.#authorization) throw new Error("Wallet not connected");
4052
+ return {
4053
+ authToken: this.#authorization.auth_token,
4054
+ chain: this.#authorization.chain
4055
+ };
4056
+ };
4057
+ #accountsToWalletStandardAccounts = (accounts) => {
4058
+ return accounts.map((account) => {
4059
+ const publicKey = toUint8Array(account.address);
4060
+ return {
4061
+ address: base58.encode(publicKey),
4062
+ publicKey,
4063
+ label: account.label,
4064
+ icon: account.icon,
4065
+ chains: account.chains ?? this.#chains,
4066
+ features: account.features ?? DEFAULT_FEATURES
4067
+ };
4068
+ });
4069
+ };
4070
+ #performSignTransactions = async (transactions) => {
4071
+ const { authToken, chain } = this.#assertIsAuthorized();
4072
+ try {
4073
+ const base64Transactions = transactions.map((tx) => {
4074
+ return fromUint8Array(tx);
4075
+ });
4076
+ return await this.#transact(async (wallet) => {
4077
+ await this.#performReauthorization(wallet, authToken, chain);
4078
+ return (await wallet.signTransactions({ payloads: base64Transactions })).signed_payloads.map(toUint8Array);
4079
+ });
4080
+ } catch (e) {
4081
+ throw new Error(getErrorMessage(e), { cause: e });
4082
+ }
4083
+ };
4084
+ #performSignAndSendTransaction = async (transaction, options) => {
4085
+ const { authToken, chain } = this.#assertIsAuthorized();
4086
+ try {
4087
+ return await this.#transact(async (wallet) => {
4088
+ const [capabilities] = await Promise.all([wallet.getCapabilities(), this.#performReauthorization(wallet, authToken, chain)]);
4089
+ if (capabilities.supports_sign_and_send_transactions) {
4090
+ const base64Transaction = fromUint8Array(transaction);
4091
+ return (await wallet.signAndSendTransactions({
4092
+ ...options,
4093
+ payloads: [base64Transaction]
4094
+ })).signatures.map(toUint8Array)[0];
4095
+ } else throw new Error("connected wallet does not support signAndSendTransaction");
4096
+ });
4097
+ } catch (e) {
4098
+ throw new Error(getErrorMessage(e), { cause: e });
4099
+ }
4100
+ };
4101
+ #signAndSendTransaction = async (...inputs) => {
4102
+ const outputs = [];
4103
+ for (const input of inputs) {
4104
+ const signature = await this.#performSignAndSendTransaction(input.transaction, input.options);
4105
+ outputs.push({ signature });
4106
+ }
4107
+ return outputs;
4108
+ };
4109
+ #signTransaction = async (...inputs) => {
4110
+ return (await this.#performSignTransactions(inputs.map(({ transaction }) => transaction))).map((signedTransaction) => {
4111
+ return { signedTransaction };
4112
+ });
4113
+ };
4114
+ #signMessage = async (...inputs) => {
4115
+ const { authToken, chain } = this.#assertIsAuthorized();
4116
+ const addresses = inputs.map(({ account }) => fromUint8Array(new Uint8Array(account.publicKey)));
4117
+ const messages = inputs.map(({ message }) => fromUint8Array(message));
4118
+ try {
4119
+ return await this.#transact(async (wallet) => {
4120
+ await this.#performReauthorization(wallet, authToken, chain);
4121
+ return (await wallet.signMessages({
4122
+ addresses,
4123
+ payloads: messages
4124
+ })).signed_payloads.map(toUint8Array).map((signedMessage) => {
4125
+ return {
4126
+ signedMessage,
4127
+ signature: signedMessage.slice(-SIGNATURE_LENGTH_IN_BYTES)
4128
+ };
4129
+ });
4130
+ });
4131
+ } catch (e) {
4132
+ throw new Error(getErrorMessage(e), { cause: e });
4133
+ }
4134
+ };
4135
+ #signIn = async (...inputs) => {
4136
+ const outputs = [];
4137
+ if (inputs.length > 1) for (const input of inputs) outputs.push(await this.#performSignIn(input));
4138
+ else return [await this.#performSignIn(inputs[0])];
4139
+ return outputs;
4140
+ };
4141
+ #performSignIn = async (input) => {
4142
+ this.#connecting = true;
4143
+ try {
4144
+ const authorizationResult = await this.#performAuthorization({
4145
+ ...input,
4146
+ domain: input?.domain ?? window.location.host
4147
+ });
4148
+ if (!authorizationResult.sign_in_result) throw new Error("Sign in failed, no sign in result returned by wallet");
4149
+ const signedInAddress = authorizationResult.sign_in_result.address;
4150
+ const signedInAccount = authorizationResult.accounts.find((acc) => acc.address == signedInAddress);
4151
+ return {
4152
+ account: {
4153
+ ...signedInAccount ?? { address: base58.encode(toUint8Array(signedInAddress)) },
4154
+ publicKey: toUint8Array(signedInAddress),
4155
+ chains: signedInAccount?.chains ?? this.#chains,
4156
+ features: signedInAccount?.features ?? authorizationResult.capabilities.features
4157
+ },
4158
+ signedMessage: toUint8Array(authorizationResult.sign_in_result.signed_message),
4159
+ signature: toUint8Array(authorizationResult.sign_in_result.signature)
4160
+ };
4161
+ } catch (e) {
4162
+ throw new Error(getErrorMessage(e), { cause: e });
4163
+ } finally {
4164
+ this.#connecting = false;
4165
+ }
4166
+ };
4167
+ };
4168
+ //#endregion
4169
+ //#region src/createDefaultAuthorizationCache.ts
4170
+ const CACHE_KEY = "SolanaMobileWalletAdapterDefaultAuthorizationCache";
4171
+ function createDefaultAuthorizationCache() {
4172
+ let storage;
4173
+ try {
4174
+ storage = window.localStorage;
4175
+ } catch {}
4176
+ return {
4177
+ async clear() {
4178
+ if (!storage) return;
4179
+ try {
4180
+ storage.removeItem(CACHE_KEY);
4181
+ } catch {}
4182
+ },
4183
+ async get() {
4184
+ if (!storage) return;
4185
+ try {
4186
+ const parsed = JSON.parse(storage.getItem(CACHE_KEY));
4187
+ if (parsed && parsed.accounts) {
4188
+ const parsedAccounts = parsed.accounts.map((account) => {
4189
+ return {
4190
+ ...account,
4191
+ publicKey: "publicKey" in account ? new Uint8Array(Object.values(account.publicKey)) : base58.decode(account.address)
4192
+ };
4193
+ });
4194
+ return {
4195
+ ...parsed,
4196
+ accounts: parsedAccounts
4197
+ };
4198
+ } else return parsed || void 0;
4199
+ } catch {}
4200
+ },
4201
+ async set(authorization) {
4202
+ if (!storage) return;
4203
+ try {
4204
+ storage.setItem(CACHE_KEY, JSON.stringify(authorization));
4205
+ } catch {}
4206
+ }
4207
+ };
4208
+ }
4209
+ //#endregion
4210
+ //#region src/createDefaultChainSelector.ts
4211
+ function createDefaultChainSelector() {
4212
+ return { async select(chains) {
4213
+ if (chains.length === 1) return chains[0];
4214
+ else if (chains.includes(SOLANA_MAINNET_CHAIN)) return SOLANA_MAINNET_CHAIN;
4215
+ else return chains[0];
4216
+ } };
4217
+ }
4218
+
4219
+ export { LocalSolanaMobileWalletAdapterWallet, SolanaMobileWalletAdapterWalletName, createDefaultAuthorizationCache, createDefaultChainSelector };
4220
+ //# sourceMappingURL=index.browser-DaNhOhkQ.esm.js.map