@reclaimprotocol/client 0.1.29 → 0.1.32

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 (110) hide show
  1. package/README.md +255 -234
  2. package/lib/api.d.ts +2 -0
  3. package/lib/api.js +2 -0
  4. package/lib/client.js +2 -0
  5. package/lib/enckeys.d.ts +1 -1
  6. package/lib/enckeys.js +2 -2
  7. package/lib/encoding.d.ts +4 -0
  8. package/lib/encoding.js +10 -0
  9. package/lib/feature-flags.d.ts +9 -0
  10. package/lib/feature-flags.js +19 -0
  11. package/lib/index.d.ts +4 -4
  12. package/lib/index.js +4 -4
  13. package/lib/jwks.d.ts +8 -8
  14. package/lib/jwks.js +38 -17
  15. package/lib/launch/destination.d.ts +14 -0
  16. package/lib/launch/destination.js +89 -0
  17. package/lib/launch/device.d.ts +30 -0
  18. package/lib/launch/device.js +168 -0
  19. package/lib/launch/environment.d.ts +224 -0
  20. package/lib/launch/environment.js +98 -0
  21. package/lib/launch/errors.d.ts +20 -0
  22. package/lib/launch/errors.js +25 -0
  23. package/lib/launch/extension.d.ts +42 -0
  24. package/lib/launch/extension.js +72 -0
  25. package/lib/launch/flow.d.ts +82 -0
  26. package/lib/launch/flow.js +222 -0
  27. package/lib/launch/index.d.ts +16 -0
  28. package/lib/launch/index.js +12 -0
  29. package/lib/launch/mobile.d.ts +77 -0
  30. package/lib/launch/mobile.js +124 -0
  31. package/lib/launch/modal.d.ts +50 -0
  32. package/lib/launch/modal.js +258 -0
  33. package/lib/launch/options.d.ts +74 -0
  34. package/lib/launch/options.js +20 -0
  35. package/lib/launch/portal.d.ts +28 -0
  36. package/lib/launch/portal.js +68 -0
  37. package/lib/launch/qr.d.ts +5 -0
  38. package/lib/launch/qr.js +28 -0
  39. package/lib/launch/target.d.ts +46 -0
  40. package/lib/launch/target.js +128 -0
  41. package/lib/launch/vendor/qrcodegen.d.ts +134 -0
  42. package/lib/launch/vendor/qrcodegen.js +822 -0
  43. package/lib/legacy-proof.d.ts +2 -0
  44. package/lib/legacy-proof.js +37 -7
  45. package/lib/proof-hash.d.ts +5 -5
  46. package/lib/proof-hash.js +1 -1
  47. package/lib/proof-recipe.d.ts +3 -3
  48. package/lib/proof-recipe.js +1 -1
  49. package/lib/proof-types.d.ts +35 -8
  50. package/lib/reclaim.d.ts +81 -70
  51. package/lib/reclaim.js +79 -130
  52. package/lib/request-proof.d.ts +60 -0
  53. package/lib/request-proof.js +241 -0
  54. package/lib/result.d.ts +46 -38
  55. package/lib/result.js +160 -100
  56. package/lib/routes.gen.d.ts +76 -28
  57. package/lib/routes.gen.js +24 -11
  58. package/lib/tee-binding.d.ts +1 -1
  59. package/lib/types/openapi.d.ts +1 -0
  60. package/lib/types/openapi.gen.d.ts +1598 -485
  61. package/lib/types/openapi.gen.js +5 -0
  62. package/lib/verification-clients.d.ts +28 -14
  63. package/lib/verification-clients.js +31 -11
  64. package/lib/verify-attestor-tee.d.ts +19 -2
  65. package/lib/verify-attestor-tee.js +40 -4
  66. package/lib/verify-tee.d.ts +10 -1
  67. package/lib/verify-tee.js +34 -10
  68. package/package.json +5 -1
  69. package/src/api.ts +9 -0
  70. package/src/client.ts +2 -0
  71. package/src/enckeys.ts +2 -2
  72. package/src/encoding.ts +12 -0
  73. package/src/feature-flags.ts +39 -0
  74. package/src/index.ts +13 -14
  75. package/src/jwks.ts +52 -30
  76. package/src/launch/destination.ts +111 -0
  77. package/src/launch/device.ts +242 -0
  78. package/src/launch/environment.ts +337 -0
  79. package/src/launch/errors.ts +49 -0
  80. package/src/launch/extension.ts +124 -0
  81. package/src/launch/flow.ts +369 -0
  82. package/src/launch/index.ts +42 -0
  83. package/src/launch/mobile.ts +184 -0
  84. package/src/launch/modal.ts +378 -0
  85. package/src/launch/options.ts +99 -0
  86. package/src/launch/portal.ts +104 -0
  87. package/src/launch/qr.ts +37 -0
  88. package/src/launch/target.ts +150 -0
  89. package/src/launch/vendor/qrcodegen.ts +1034 -0
  90. package/src/proof-hash.ts +6 -6
  91. package/src/proof-recipe.ts +3 -3
  92. package/src/proof-types.ts +36 -8
  93. package/src/reclaim.ts +185 -218
  94. package/src/{legacy-proof.ts → request-proof.ts} +81 -36
  95. package/src/result.ts +238 -172
  96. package/src/routes.gen.ts +24 -11
  97. package/src/tee-binding.ts +1 -1
  98. package/src/types/openapi.gen.ts +1603 -485
  99. package/src/types/openapi.ts +3 -1
  100. package/src/verification-clients.ts +33 -19
  101. package/src/verify-attestor-tee.ts +66 -8
  102. package/src/verify-tee.ts +44 -13
  103. package/lib/api-client.d.ts +0 -31
  104. package/lib/api-client.js +0 -112
  105. package/lib/api-consts.d.ts +0 -4
  106. package/lib/api-consts.js +0 -4
  107. package/lib/api-errors.d.ts +0 -13
  108. package/lib/api-errors.js +0 -30
  109. package/lib/eip712.d.ts +0 -20
  110. package/lib/eip712.js +0 -108
@@ -0,0 +1,822 @@
1
+ /**
2
+ * QR Code generator library (TypeScript)
3
+ *
4
+ * Copyright (c) Project Nayuki. (MIT License)
5
+ * https://www.nayuki.io/page/qr-code-generator-library
6
+ * https://github.com/nayuki/QR-Code-generator (typescript-javascript/qrcodegen.ts)
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of
9
+ * this software and associated documentation files (the "Software"), to deal in
10
+ * the Software without restriction, including without limitation the rights to
11
+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
12
+ * the Software, and to permit persons to whom the Software is furnished to do so,
13
+ * subject to the following conditions:
14
+ * - The above copyright notice and this permission notice shall be included in
15
+ * all copies or substantial portions of the Software.
16
+ * - The Software is provided "as is", without warranty of any kind, express or
17
+ * implied, including but not limited to the warranties of merchantability,
18
+ * fitness for a particular purpose and noninfringement. In no event shall the
19
+ * authors or copyright holders be liable for any claim, damages or other
20
+ * liability, whether in an action of contract, tort or otherwise, arising from,
21
+ * out of or in connection with the Software or the use or other dealings in the
22
+ * Software.
23
+ *
24
+ * ---
25
+ *
26
+ * Vendored here, NOT an npm dependency. The launch-API plan requires the QR
27
+ * modal to work with zero configuration, and `qrcode` (the usual npm encoder)
28
+ * is deliberately not a dependency of this package.
29
+ *
30
+ * Adaptations from the upstream source (kept otherwise verbatim, including
31
+ * comments):
32
+ * - Flattened the `namespace qrcodegen { ... }` / `namespace
33
+ * qrcodegen.QrCode { ... }` / `namespace qrcodegen.QrSegment { ... }`
34
+ * wrappers into plain top-level declarations, and renamed the
35
+ * namespace-merged `QrCode.Ecc` / `QrSegment.Mode` helper classes to
36
+ * standalone `QrCodeEcc` / `QrSegmentMode` — this package's
37
+ * `tsconfig.json` sets `erasableSyntaxOnly`, which Node's native TS
38
+ * type-stripping (`node --test tests/*.test.ts`) requires, and a
39
+ * `namespace` with runtime content isn't erasable.
40
+ * - Rewrote every constructor-parameter-property (`constructor(public
41
+ * readonly x: T)`) into an explicit field declaration plus a body
42
+ * assignment, for the same `erasableSyntaxOnly` reason: those also
43
+ * generate code beyond type erasure.
44
+ * - Dropped the `"use strict"` prologue (redundant in an ES module).
45
+ * No changes to the encoding algorithm itself (mode selection, version
46
+ * sizing, Reed–Solomon ECC, masking, penalty scoring).
47
+ *
48
+ * This directory is named `vendor` on purpose: `eslint.config.js` already
49
+ * ignores that directory name, so this file keeps upstream's style rather
50
+ * than being reformatted to this repo's conventions.
51
+ */
52
+ /*---- QR Code symbol class ----*/
53
+ /*
54
+ * A QR Code symbol, which is a type of two-dimension barcode.
55
+ * Invented by Denso Wave and described in the ISO/IEC 18004 standard.
56
+ * Instances of this class represent an immutable square grid of dark and light cells.
57
+ * The class provides static factory functions to create a QR Code from text or binary data.
58
+ * The class covers the QR Code Model 2 specification, supporting all versions (sizes)
59
+ * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.
60
+ *
61
+ * Ways to create a QR Code object:
62
+ * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().
63
+ * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().
64
+ * - Low level: Custom-make the array of data codeword bytes (including
65
+ * segment headers and final padding, excluding error correction codewords),
66
+ * supply the appropriate version number, and call the QrCode() constructor.
67
+ * (Note that all ways require supplying the desired error correction level.)
68
+ */
69
+ export class QrCode {
70
+ /*-- Static factory functions (high level) --*/
71
+ // Returns a QR Code representing the given Unicode text string at the given error correction level.
72
+ // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer
73
+ // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible
74
+ // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the
75
+ // ecl argument if it can be done without increasing the version.
76
+ static encodeText(text, ecl) {
77
+ const segs = QrSegment.makeSegments(text);
78
+ return QrCode.encodeSegments(segs, ecl);
79
+ }
80
+ // Returns a QR Code representing the given binary data at the given error correction level.
81
+ // This function always encodes using the binary segment mode, not any text mode. The maximum number of
82
+ // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.
83
+ // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.
84
+ static encodeBinary(data, ecl) {
85
+ const seg = QrSegment.makeBytes(data);
86
+ return QrCode.encodeSegments([seg], ecl);
87
+ }
88
+ /*-- Static factory functions (mid level) --*/
89
+ // Returns a QR Code representing the given segments with the given encoding parameters.
90
+ // The smallest possible QR Code version within the given range is automatically
91
+ // chosen for the output. Iff boostEcl is true, then the ECC level of the result
92
+ // may be higher than the ecl argument if it can be done without increasing the
93
+ // version. The mask number is either between 0 to 7 (inclusive) to force that
94
+ // mask, or -1 to automatically choose an appropriate mask (which may be slow).
95
+ // This function allows the user to create a custom sequence of segments that switches
96
+ // between modes (such as alphanumeric and byte) to encode text in less space.
97
+ // This is a mid-level API; the high-level API is encodeText() and encodeBinary().
98
+ static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) {
99
+ if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)
100
+ || mask < -1 || mask > 7)
101
+ throw new RangeError("Invalid value");
102
+ // Find the minimal version number to use
103
+ let version;
104
+ let dataUsedBits;
105
+ for (version = minVersion;; version++) {
106
+ const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available
107
+ const usedBits = QrSegment.getTotalBits(segs, version);
108
+ if (usedBits <= dataCapacityBits) {
109
+ dataUsedBits = usedBits;
110
+ break; // This version number is found to be suitable
111
+ }
112
+ if (version >= maxVersion) // All versions in the range could not fit the given data
113
+ throw new RangeError("Data too long");
114
+ }
115
+ // Increase the error correction level while the data still fits in the current version number
116
+ for (const newEcl of [QrCodeEcc.MEDIUM, QrCodeEcc.QUARTILE, QrCodeEcc.HIGH]) { // From low to high
117
+ if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)
118
+ ecl = newEcl;
119
+ }
120
+ // Concatenate all segments to create the data bit string
121
+ let bb = [];
122
+ for (const seg of segs) {
123
+ appendBits(seg.mode.modeBits, 4, bb);
124
+ appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);
125
+ for (const b of seg.getData())
126
+ bb.push(b);
127
+ }
128
+ assert(bb.length == dataUsedBits);
129
+ // Add terminator and pad up to a byte if applicable
130
+ const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;
131
+ assert(bb.length <= dataCapacityBits);
132
+ appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);
133
+ appendBits(0, (8 - bb.length % 8) % 8, bb);
134
+ assert(bb.length % 8 == 0);
135
+ // Pad with alternating bytes until data capacity is reached
136
+ for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)
137
+ appendBits(padByte, 8, bb);
138
+ // Pack bits into bytes in big endian
139
+ let dataCodewords = [];
140
+ while (dataCodewords.length * 8 < bb.length)
141
+ dataCodewords.push(0);
142
+ bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << (7 - (i & 7)));
143
+ // Create the QR Code object
144
+ return new QrCode(version, ecl, dataCodewords, mask);
145
+ }
146
+ /*-- Constructor (low level) and fields --*/
147
+ // Creates a new QR Code with the given version number,
148
+ // error correction level, data codeword bytes, and mask number.
149
+ // This is a low-level API that most users should not use directly.
150
+ // A mid-level API is the encodeSegments() function.
151
+ constructor(version, errorCorrectionLevel, dataCodewords, msk) {
152
+ // The modules of this QR Code (false = light, true = dark).
153
+ // Immutable after constructor finishes. Accessed through getModule().
154
+ this.modules = [];
155
+ // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.
156
+ this.isFunction = [];
157
+ // Check scalar arguments
158
+ if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)
159
+ throw new RangeError("Version value out of range");
160
+ if (msk < -1 || msk > 7)
161
+ throw new RangeError("Mask value out of range");
162
+ this.version = version;
163
+ this.errorCorrectionLevel = errorCorrectionLevel;
164
+ this.size = version * 4 + 17;
165
+ // Initialize both grids to be size*size arrays of Boolean false
166
+ let row = [];
167
+ for (let i = 0; i < this.size; i++)
168
+ row.push(false);
169
+ for (let i = 0; i < this.size; i++) {
170
+ this.modules.push(row.slice()); // Initially all light
171
+ this.isFunction.push(row.slice());
172
+ }
173
+ // Compute ECC, draw modules
174
+ this.drawFunctionPatterns();
175
+ const allCodewords = this.addEccAndInterleave(dataCodewords);
176
+ this.drawCodewords(allCodewords);
177
+ // Do masking
178
+ if (msk == -1) { // Automatically choose best mask
179
+ let minPenalty = 1000000000;
180
+ for (let i = 0; i < 8; i++) {
181
+ this.applyMask(i);
182
+ this.drawFormatBits(i);
183
+ const penalty = this.getPenaltyScore();
184
+ if (penalty < minPenalty) {
185
+ msk = i;
186
+ minPenalty = penalty;
187
+ }
188
+ this.applyMask(i); // Undoes the mask due to XOR
189
+ }
190
+ }
191
+ assert(0 <= msk && msk <= 7);
192
+ this.mask = msk;
193
+ this.applyMask(msk); // Apply the final choice of mask
194
+ this.drawFormatBits(msk); // Overwrite old format bits
195
+ this.isFunction = [];
196
+ }
197
+ /*-- Accessor methods --*/
198
+ // Returns the color of the module (pixel) at the given coordinates, which is false
199
+ // for light or true for dark. The top left corner has the coordinates (x=0, y=0).
200
+ // If the given coordinates are out of bounds, then false (light) is returned.
201
+ getModule(x, y) {
202
+ return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];
203
+ }
204
+ /*-- Private helper methods for constructor: Drawing function modules --*/
205
+ // Reads this object's version field, and draws and marks all function modules.
206
+ drawFunctionPatterns() {
207
+ // Draw horizontal and vertical timing patterns
208
+ for (let i = 0; i < this.size; i++) {
209
+ this.setFunctionModule(6, i, i % 2 == 0);
210
+ this.setFunctionModule(i, 6, i % 2 == 0);
211
+ }
212
+ // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)
213
+ this.drawFinderPattern(3, 3);
214
+ this.drawFinderPattern(this.size - 4, 3);
215
+ this.drawFinderPattern(3, this.size - 4);
216
+ // Draw numerous alignment patterns
217
+ const alignPatPos = this.getAlignmentPatternPositions();
218
+ const numAlign = alignPatPos.length;
219
+ for (let i = 0; i < numAlign; i++) {
220
+ for (let j = 0; j < numAlign; j++) {
221
+ // Don't draw on the three finder corners
222
+ if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))
223
+ this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);
224
+ }
225
+ }
226
+ // Draw configuration data
227
+ this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor
228
+ this.drawVersion();
229
+ }
230
+ // Draws two copies of the format bits (with its own error correction code)
231
+ // based on the given mask and this object's error correction level field.
232
+ drawFormatBits(mask) {
233
+ // Calculate error correction code and pack bits
234
+ const data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3
235
+ let rem = data;
236
+ for (let i = 0; i < 10; i++)
237
+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
238
+ const bits = (data << 10 | rem) ^ 0x5412; // uint15
239
+ assert(bits >>> 15 == 0);
240
+ // Draw first copy
241
+ for (let i = 0; i <= 5; i++)
242
+ this.setFunctionModule(8, i, getBit(bits, i));
243
+ this.setFunctionModule(8, 7, getBit(bits, 6));
244
+ this.setFunctionModule(8, 8, getBit(bits, 7));
245
+ this.setFunctionModule(7, 8, getBit(bits, 8));
246
+ for (let i = 9; i < 15; i++)
247
+ this.setFunctionModule(14 - i, 8, getBit(bits, i));
248
+ // Draw second copy
249
+ for (let i = 0; i < 8; i++)
250
+ this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));
251
+ for (let i = 8; i < 15; i++)
252
+ this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));
253
+ this.setFunctionModule(8, this.size - 8, true); // Always dark
254
+ }
255
+ // Draws two copies of the version bits (with its own error correction code),
256
+ // based on this object's version field, iff 7 <= version <= 40.
257
+ drawVersion() {
258
+ if (this.version < 7)
259
+ return;
260
+ // Calculate error correction code and pack bits
261
+ let rem = this.version; // version is uint6, in the range [7, 40]
262
+ for (let i = 0; i < 12; i++)
263
+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);
264
+ const bits = this.version << 12 | rem; // uint18
265
+ assert(bits >>> 18 == 0);
266
+ // Draw two copies
267
+ for (let i = 0; i < 18; i++) {
268
+ const color = getBit(bits, i);
269
+ const a = this.size - 11 + i % 3;
270
+ const b = Math.floor(i / 3);
271
+ this.setFunctionModule(a, b, color);
272
+ this.setFunctionModule(b, a, color);
273
+ }
274
+ }
275
+ // Draws a 9*9 finder pattern including the border separator,
276
+ // with the center module at (x, y). Modules can be out of bounds.
277
+ drawFinderPattern(x, y) {
278
+ for (let dy = -4; dy <= 4; dy++) {
279
+ for (let dx = -4; dx <= 4; dx++) {
280
+ const dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm
281
+ const xx = x + dx;
282
+ const yy = y + dy;
283
+ if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)
284
+ this.setFunctionModule(xx, yy, dist != 2 && dist != 4);
285
+ }
286
+ }
287
+ }
288
+ // Draws a 5*5 alignment pattern, with the center module
289
+ // at (x, y). All modules must be in bounds.
290
+ drawAlignmentPattern(x, y) {
291
+ for (let dy = -2; dy <= 2; dy++) {
292
+ for (let dx = -2; dx <= 2; dx++)
293
+ this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);
294
+ }
295
+ }
296
+ // Sets the color of a module and marks it as a function module.
297
+ // Only used by the constructor. Coordinates must be in bounds.
298
+ setFunctionModule(x, y, isDark) {
299
+ this.modules[y][x] = isDark;
300
+ this.isFunction[y][x] = true;
301
+ }
302
+ /*-- Private helper methods for constructor: Codewords and masking --*/
303
+ // Returns a new byte string representing the given data with the appropriate error correction
304
+ // codewords appended to it, based on this object's version and error correction level.
305
+ addEccAndInterleave(data) {
306
+ const ver = this.version;
307
+ const ecl = this.errorCorrectionLevel;
308
+ if (data.length != QrCode.getNumDataCodewords(ver, ecl))
309
+ throw new RangeError("Invalid argument");
310
+ // Calculate parameter numbers
311
+ const numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
312
+ const blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];
313
+ const rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);
314
+ const numShortBlocks = numBlocks - rawCodewords % numBlocks;
315
+ const shortBlockLen = Math.floor(rawCodewords / numBlocks);
316
+ // Split data into blocks and append ECC to each block
317
+ let blocks = [];
318
+ const rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);
319
+ for (let i = 0, k = 0; i < numBlocks; i++) {
320
+ let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));
321
+ k += dat.length;
322
+ const ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);
323
+ if (i < numShortBlocks)
324
+ dat.push(0);
325
+ blocks.push(dat.concat(ecc));
326
+ }
327
+ // Interleave (not concatenate) the bytes from every block into a single sequence
328
+ let result = [];
329
+ for (let i = 0; i < blocks[0].length; i++) {
330
+ blocks.forEach((block, j) => {
331
+ // Skip the padding byte in short blocks
332
+ if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)
333
+ result.push(block[i]);
334
+ });
335
+ }
336
+ assert(result.length == rawCodewords);
337
+ return result;
338
+ }
339
+ // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire
340
+ // data area of this QR Code. Function modules need to be marked off before this is called.
341
+ drawCodewords(data) {
342
+ if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))
343
+ throw new RangeError("Invalid argument");
344
+ let i = 0; // Bit index into the data
345
+ // Do the funny zigzag scan
346
+ for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair
347
+ if (right == 6)
348
+ right = 5;
349
+ for (let vert = 0; vert < this.size; vert++) { // Vertical counter
350
+ for (let j = 0; j < 2; j++) {
351
+ const x = right - j; // Actual x coordinate
352
+ const upward = ((right + 1) & 2) == 0;
353
+ const y = upward ? this.size - 1 - vert : vert; // Actual y coordinate
354
+ if (!this.isFunction[y][x] && i < data.length * 8) {
355
+ this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));
356
+ i++;
357
+ }
358
+ // If this QR Code has any remainder bits (0 to 7), they were assigned as
359
+ // 0/false/light by the constructor and are left unchanged by this method
360
+ }
361
+ }
362
+ }
363
+ assert(i == data.length * 8);
364
+ }
365
+ // XORs the codeword modules in this QR Code with the given mask pattern.
366
+ // The function modules must be marked and the codeword bits must be drawn
367
+ // before masking. Due to the arithmetic of XOR, calling applyMask() with
368
+ // the same mask value a second time will undo the mask. A final well-formed
369
+ // QR Code needs exactly one (not zero, two, etc.) mask applied.
370
+ applyMask(mask) {
371
+ if (mask < 0 || mask > 7)
372
+ throw new RangeError("Mask value out of range");
373
+ for (let y = 0; y < this.size; y++) {
374
+ for (let x = 0; x < this.size; x++) {
375
+ let invert;
376
+ switch (mask) {
377
+ case 0:
378
+ invert = (x + y) % 2 == 0;
379
+ break;
380
+ case 1:
381
+ invert = y % 2 == 0;
382
+ break;
383
+ case 2:
384
+ invert = x % 3 == 0;
385
+ break;
386
+ case 3:
387
+ invert = (x + y) % 3 == 0;
388
+ break;
389
+ case 4:
390
+ invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;
391
+ break;
392
+ case 5:
393
+ invert = x * y % 2 + x * y % 3 == 0;
394
+ break;
395
+ case 6:
396
+ invert = (x * y % 2 + x * y % 3) % 2 == 0;
397
+ break;
398
+ case 7:
399
+ invert = ((x + y) % 2 + x * y % 3) % 2 == 0;
400
+ break;
401
+ default: throw new Error("Unreachable");
402
+ }
403
+ if (!this.isFunction[y][x] && invert)
404
+ this.modules[y][x] = !this.modules[y][x];
405
+ }
406
+ }
407
+ }
408
+ // Calculates and returns the penalty score based on state of this QR Code's current modules.
409
+ // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.
410
+ getPenaltyScore() {
411
+ let result = 0;
412
+ // Adjacent modules in row having same color, and finder-like patterns
413
+ for (let y = 0; y < this.size; y++) {
414
+ let runColor = false;
415
+ let runX = 0;
416
+ let runHistory = [0, 0, 0, 0, 0, 0, 0];
417
+ for (let x = 0; x < this.size; x++) {
418
+ if (this.modules[y][x] == runColor) {
419
+ runX++;
420
+ if (runX == 5)
421
+ result += QrCode.PENALTY_N1;
422
+ else if (runX > 5)
423
+ result++;
424
+ }
425
+ else {
426
+ this.finderPenaltyAddHistory(runX, runHistory);
427
+ if (!runColor)
428
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
429
+ runColor = this.modules[y][x];
430
+ runX = 1;
431
+ }
432
+ }
433
+ result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;
434
+ }
435
+ // Adjacent modules in column having same color, and finder-like patterns
436
+ for (let x = 0; x < this.size; x++) {
437
+ let runColor = false;
438
+ let runY = 0;
439
+ let runHistory = [0, 0, 0, 0, 0, 0, 0];
440
+ for (let y = 0; y < this.size; y++) {
441
+ if (this.modules[y][x] == runColor) {
442
+ runY++;
443
+ if (runY == 5)
444
+ result += QrCode.PENALTY_N1;
445
+ else if (runY > 5)
446
+ result++;
447
+ }
448
+ else {
449
+ this.finderPenaltyAddHistory(runY, runHistory);
450
+ if (!runColor)
451
+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;
452
+ runColor = this.modules[y][x];
453
+ runY = 1;
454
+ }
455
+ }
456
+ result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;
457
+ }
458
+ // 2*2 blocks of modules having same color
459
+ for (let y = 0; y < this.size - 1; y++) {
460
+ for (let x = 0; x < this.size - 1; x++) {
461
+ const color = this.modules[y][x];
462
+ if (color == this.modules[y][x + 1] &&
463
+ color == this.modules[y + 1][x] &&
464
+ color == this.modules[y + 1][x + 1])
465
+ result += QrCode.PENALTY_N2;
466
+ }
467
+ }
468
+ // Balance of dark and light modules
469
+ let dark = 0;
470
+ for (const row of this.modules)
471
+ dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);
472
+ const total = this.size * this.size; // Note that size is odd, so dark/total != 1/2
473
+ // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%
474
+ const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;
475
+ assert(0 <= k && k <= 9);
476
+ result += k * QrCode.PENALTY_N4;
477
+ assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4
478
+ return result;
479
+ }
480
+ /*-- Private helper functions --*/
481
+ // Returns an ascending list of positions of alignment patterns for this version number.
482
+ // Each position is in the range [0,177), and are used on both the x and y axes.
483
+ // This could be implemented as lookup table of 40 variable-length lists of integers.
484
+ getAlignmentPatternPositions() {
485
+ if (this.version == 1)
486
+ return [];
487
+ else {
488
+ const numAlign = Math.floor(this.version / 7) + 2;
489
+ const step = Math.floor((this.version * 8 + numAlign * 3 + 5) / (numAlign * 4 - 4)) * 2;
490
+ let result = [6];
491
+ for (let pos = this.size - 7; result.length < numAlign; pos -= step)
492
+ result.splice(1, 0, pos);
493
+ return result;
494
+ }
495
+ }
496
+ // Returns the number of data bits that can be stored in a QR Code of the given version number, after
497
+ // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.
498
+ // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.
499
+ static getNumRawDataModules(ver) {
500
+ if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)
501
+ throw new RangeError("Version number out of range");
502
+ let result = (16 * ver + 128) * ver + 64;
503
+ if (ver >= 2) {
504
+ const numAlign = Math.floor(ver / 7) + 2;
505
+ result -= (25 * numAlign - 10) * numAlign - 55;
506
+ if (ver >= 7)
507
+ result -= 36;
508
+ }
509
+ assert(208 <= result && result <= 29648);
510
+ return result;
511
+ }
512
+ // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any
513
+ // QR Code of the given version number and error correction level, with remainder bits discarded.
514
+ // This stateless pure function could be implemented as a (40*4)-cell lookup table.
515
+ static getNumDataCodewords(ver, ecl) {
516
+ return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -
517
+ QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *
518
+ QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];
519
+ }
520
+ // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be
521
+ // implemented as a lookup table over all possible parameter values, instead of as an algorithm.
522
+ static reedSolomonComputeDivisor(degree) {
523
+ if (degree < 1 || degree > 255)
524
+ throw new RangeError("Degree out of range");
525
+ // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.
526
+ // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].
527
+ let result = [];
528
+ for (let i = 0; i < degree - 1; i++)
529
+ result.push(0);
530
+ result.push(1); // Start off with the monomial x^0
531
+ // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),
532
+ // and drop the highest monomial term which is always 1x^degree.
533
+ // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).
534
+ let root = 1;
535
+ for (let i = 0; i < degree; i++) {
536
+ // Multiply the current product by (x - r^i)
537
+ for (let j = 0; j < result.length; j++) {
538
+ result[j] = QrCode.reedSolomonMultiply(result[j], root);
539
+ if (j + 1 < result.length)
540
+ result[j] ^= result[j + 1];
541
+ }
542
+ root = QrCode.reedSolomonMultiply(root, 0x02);
543
+ }
544
+ return result;
545
+ }
546
+ // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.
547
+ static reedSolomonComputeRemainder(data, divisor) {
548
+ let result = divisor.map(_ => 0);
549
+ for (const b of data) { // Polynomial division
550
+ const factor = b ^ result.shift();
551
+ result.push(0);
552
+ divisor.forEach((coef, i) => result[i] ^= QrCode.reedSolomonMultiply(coef, factor));
553
+ }
554
+ return result;
555
+ }
556
+ // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result
557
+ // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.
558
+ static reedSolomonMultiply(x, y) {
559
+ if (x >>> 8 != 0 || y >>> 8 != 0)
560
+ throw new RangeError("Byte out of range");
561
+ // Russian peasant multiplication
562
+ let z = 0;
563
+ for (let i = 7; i >= 0; i--) {
564
+ z = (z << 1) ^ ((z >>> 7) * 0x11D);
565
+ z ^= ((y >>> i) & 1) * x;
566
+ }
567
+ assert(z >>> 8 == 0);
568
+ return z;
569
+ }
570
+ // Can only be called immediately after a light run is added, and
571
+ // returns either 0, 1, or 2. A helper function for getPenaltyScore().
572
+ finderPenaltyCountPatterns(runHistory) {
573
+ const n = runHistory[1];
574
+ assert(n <= this.size * 3);
575
+ const core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;
576
+ return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)
577
+ + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);
578
+ }
579
+ // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().
580
+ finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) {
581
+ if (currentRunColor) { // Terminate dark run
582
+ this.finderPenaltyAddHistory(currentRunLength, runHistory);
583
+ currentRunLength = 0;
584
+ }
585
+ currentRunLength += this.size; // Add light border to final run
586
+ this.finderPenaltyAddHistory(currentRunLength, runHistory);
587
+ return this.finderPenaltyCountPatterns(runHistory);
588
+ }
589
+ // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().
590
+ finderPenaltyAddHistory(currentRunLength, runHistory) {
591
+ if (runHistory[0] == 0)
592
+ currentRunLength += this.size; // Add light border to initial run
593
+ runHistory.pop();
594
+ runHistory.unshift(currentRunLength);
595
+ }
596
+ }
597
+ /*-- Constants and tables --*/
598
+ // The minimum version number supported in the QR Code Model 2 standard.
599
+ QrCode.MIN_VERSION = 1;
600
+ // The maximum version number supported in the QR Code Model 2 standard.
601
+ QrCode.MAX_VERSION = 40;
602
+ // For use in getPenaltyScore(), when evaluating which mask is best.
603
+ QrCode.PENALTY_N1 = 3;
604
+ QrCode.PENALTY_N2 = 3;
605
+ QrCode.PENALTY_N3 = 40;
606
+ QrCode.PENALTY_N4 = 10;
607
+ QrCode.ECC_CODEWORDS_PER_BLOCK = [
608
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
609
+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
610
+ [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Low
611
+ [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], // Medium
612
+ [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // Quartile
613
+ [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High
614
+ ];
615
+ QrCode.NUM_ERROR_CORRECTION_BLOCKS = [
616
+ // Version: (note that index 0 is for padding, and is set to an illegal value)
617
+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level
618
+ [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], // Low
619
+ [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], // Medium
620
+ [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], // Quartile
621
+ [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High
622
+ ];
623
+ // Appends the given number of low-order bits of the given value
624
+ // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.
625
+ function appendBits(val, len, bb) {
626
+ if (len < 0 || len > 31 || val >>> len != 0)
627
+ throw new RangeError("Value out of range");
628
+ for (let i = len - 1; i >= 0; i--) // Append bit by bit
629
+ bb.push((val >>> i) & 1);
630
+ }
631
+ // Returns true iff the i'th bit of x is set to 1.
632
+ function getBit(x, i) {
633
+ return ((x >>> i) & 1) != 0;
634
+ }
635
+ // Throws an exception if the given condition is false.
636
+ function assert(cond) {
637
+ if (!cond)
638
+ throw new Error("Assertion error");
639
+ }
640
+ /*---- Data segment class ----*/
641
+ /*
642
+ * A segment of character/binary/control data in a QR Code symbol.
643
+ * Instances of this class are immutable.
644
+ * The mid-level way to create a segment is to take the payload data
645
+ * and call a static factory function such as QrSegment.makeNumeric().
646
+ * The low-level way to create a segment is to custom-make the bit buffer
647
+ * and call the QrSegment() constructor with appropriate values.
648
+ * This segment class imposes no length restrictions, but QR Codes have restrictions.
649
+ * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.
650
+ * Any segment longer than this is meaningless for the purpose of generating QR Codes.
651
+ */
652
+ export class QrSegment {
653
+ /*-- Static factory functions (mid level) --*/
654
+ // Returns a segment representing the given binary data encoded in
655
+ // byte mode. All input byte arrays are acceptable. Any text string
656
+ // can be converted to UTF-8 bytes and encoded as a byte mode segment.
657
+ static makeBytes(data) {
658
+ let bb = [];
659
+ for (const b of data)
660
+ appendBits(b, 8, bb);
661
+ return new QrSegment(QrSegmentMode.BYTE, data.length, bb);
662
+ }
663
+ // Returns a segment representing the given string of decimal digits encoded in numeric mode.
664
+ static makeNumeric(digits) {
665
+ if (!QrSegment.isNumeric(digits))
666
+ throw new RangeError("String contains non-numeric characters");
667
+ let bb = [];
668
+ for (let i = 0; i < digits.length;) { // Consume up to 3 digits per iteration
669
+ const n = Math.min(digits.length - i, 3);
670
+ appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);
671
+ i += n;
672
+ }
673
+ return new QrSegment(QrSegmentMode.NUMERIC, digits.length, bb);
674
+ }
675
+ // Returns a segment representing the given text string encoded in alphanumeric mode.
676
+ // The characters allowed are: 0 to 9, A to Z (uppercase only), space,
677
+ // dollar, percent, asterisk, plus, hyphen, period, slash, colon.
678
+ static makeAlphanumeric(text) {
679
+ if (!QrSegment.isAlphanumeric(text))
680
+ throw new RangeError("String contains unencodable characters in alphanumeric mode");
681
+ let bb = [];
682
+ let i;
683
+ for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2
684
+ let temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;
685
+ temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));
686
+ appendBits(temp, 11, bb);
687
+ }
688
+ if (i < text.length) // 1 character remaining
689
+ appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);
690
+ return new QrSegment(QrSegmentMode.ALPHANUMERIC, text.length, bb);
691
+ }
692
+ // Returns a new mutable list of zero or more segments to represent the given Unicode text string.
693
+ // The result may use various segment modes and switch modes to optimize the length of the bit stream.
694
+ static makeSegments(text) {
695
+ // Select the most efficient segment encoding automatically
696
+ if (text == "")
697
+ return [];
698
+ else if (QrSegment.isNumeric(text))
699
+ return [QrSegment.makeNumeric(text)];
700
+ else if (QrSegment.isAlphanumeric(text))
701
+ return [QrSegment.makeAlphanumeric(text)];
702
+ else
703
+ return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];
704
+ }
705
+ // Returns a segment representing an Extended Channel Interpretation
706
+ // (ECI) designator with the given assignment value.
707
+ static makeEci(assignVal) {
708
+ let bb = [];
709
+ if (assignVal < 0)
710
+ throw new RangeError("ECI assignment value out of range");
711
+ else if (assignVal < (1 << 7))
712
+ appendBits(assignVal, 8, bb);
713
+ else if (assignVal < (1 << 14)) {
714
+ appendBits(0b10, 2, bb);
715
+ appendBits(assignVal, 14, bb);
716
+ }
717
+ else if (assignVal < 1000000) {
718
+ appendBits(0b110, 3, bb);
719
+ appendBits(assignVal, 21, bb);
720
+ }
721
+ else
722
+ throw new RangeError("ECI assignment value out of range");
723
+ return new QrSegment(QrSegmentMode.ECI, 0, bb);
724
+ }
725
+ // Tests whether the given string can be encoded as a segment in numeric mode.
726
+ // A string is encodable iff each character is in the range 0 to 9.
727
+ static isNumeric(text) {
728
+ return QrSegment.NUMERIC_REGEX.test(text);
729
+ }
730
+ // Tests whether the given string can be encoded as a segment in alphanumeric mode.
731
+ // A string is encodable iff each character is in the following set: 0 to 9, A to Z
732
+ // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.
733
+ static isAlphanumeric(text) {
734
+ return QrSegment.ALPHANUMERIC_REGEX.test(text);
735
+ }
736
+ // Creates a new QR Code segment with the given attributes and data.
737
+ // The character count (numChars) must agree with the mode and the bit buffer length,
738
+ // but the constraint isn't checked. The given bit buffer is cloned and stored.
739
+ constructor(mode, numChars, bitData) {
740
+ if (numChars < 0)
741
+ throw new RangeError("Invalid argument");
742
+ this.mode = mode;
743
+ this.numChars = numChars;
744
+ this.bitData = bitData.slice(); // Make defensive copy
745
+ }
746
+ /*-- Methods --*/
747
+ // Returns a new copy of the data bits of this segment.
748
+ getData() {
749
+ return this.bitData.slice(); // Make defensive copy
750
+ }
751
+ // (Package-private) Calculates and returns the number of bits needed to encode the given segments at
752
+ // the given version. The result is infinity if a segment has too many characters to fit its length field.
753
+ static getTotalBits(segs, version) {
754
+ let result = 0;
755
+ for (const seg of segs) {
756
+ const ccbits = seg.mode.numCharCountBits(version);
757
+ if (seg.numChars >= (1 << ccbits))
758
+ return Infinity; // The segment's length doesn't fit the field's bit width
759
+ result += 4 + ccbits + seg.bitData.length;
760
+ }
761
+ return result;
762
+ }
763
+ // Returns a new array of bytes representing the given string encoded in UTF-8.
764
+ static toUtf8ByteArray(str) {
765
+ str = encodeURI(str);
766
+ let result = [];
767
+ for (let i = 0; i < str.length; i++) {
768
+ if (str.charAt(i) != "%")
769
+ result.push(str.charCodeAt(i));
770
+ else {
771
+ result.push(parseInt(str.substring(i + 1, i + 3), 16));
772
+ i += 2;
773
+ }
774
+ }
775
+ return result;
776
+ }
777
+ }
778
+ /*-- Constants --*/
779
+ // Describes precisely all strings that are encodable in numeric mode.
780
+ QrSegment.NUMERIC_REGEX = /^[0-9]*$/;
781
+ // Describes precisely all strings that are encodable in alphanumeric mode.
782
+ QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;
783
+ // The set of all legal characters in alphanumeric mode,
784
+ // where each character value maps to the index in the string.
785
+ QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
786
+ /*---- Public helper enumeration ----*/
787
+ /*
788
+ * The error correction level in a QR Code symbol. Immutable.
789
+ */
790
+ export class QrCodeEcc {
791
+ constructor(ordinal, formatBits) {
792
+ this.ordinal = ordinal;
793
+ this.formatBits = formatBits;
794
+ }
795
+ }
796
+ /*-- Constants --*/
797
+ QrCodeEcc.LOW = new QrCodeEcc(0, 1); // The QR Code can tolerate about 7% erroneous codewords
798
+ QrCodeEcc.MEDIUM = new QrCodeEcc(1, 0); // The QR Code can tolerate about 15% erroneous codewords
799
+ QrCodeEcc.QUARTILE = new QrCodeEcc(2, 3); // The QR Code can tolerate about 25% erroneous codewords
800
+ QrCodeEcc.HIGH = new QrCodeEcc(3, 2); // The QR Code can tolerate about 30% erroneous codewords
801
+ /*---- Public helper enumeration ----*/
802
+ /*
803
+ * Describes how a segment's data bits are interpreted. Immutable.
804
+ */
805
+ export class QrSegmentMode {
806
+ constructor(modeBits, numBitsCharCount) {
807
+ this.modeBits = modeBits;
808
+ this.numBitsCharCount = numBitsCharCount;
809
+ }
810
+ /*-- Method --*/
811
+ // (Package-private) Returns the bit width of the character count field for a segment in
812
+ // this mode in a QR Code at the given version number. The result is in the range [0, 16].
813
+ numCharCountBits(ver) {
814
+ return this.numBitsCharCount[Math.floor((ver + 7) / 17)];
815
+ }
816
+ }
817
+ /*-- Constants --*/
818
+ QrSegmentMode.NUMERIC = new QrSegmentMode(0x1, [10, 12, 14]);
819
+ QrSegmentMode.ALPHANUMERIC = new QrSegmentMode(0x2, [9, 11, 13]);
820
+ QrSegmentMode.BYTE = new QrSegmentMode(0x4, [8, 16, 16]);
821
+ QrSegmentMode.KANJI = new QrSegmentMode(0x8, [8, 10, 12]);
822
+ QrSegmentMode.ECI = new QrSegmentMode(0x7, [0, 0, 0]);