qr-decoder-js 1.0.5 → 1.0.8

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 (54) hide show
  1. package/LICENSE.jsQR +201 -0
  2. package/LICENSE.qcore +21 -0
  3. package/README.md +19 -121
  4. package/README_ZH.md +19 -117
  5. package/dist/cjs/core/decoder.js +246 -0
  6. package/dist/cjs/core/encoding.js +217 -0
  7. package/dist/cjs/core/preprocess.js +687 -0
  8. package/dist/cjs/index.js +12 -0
  9. package/dist/cjs/native/binarize.js +76 -0
  10. package/dist/cjs/native/bitstream.js +138 -0
  11. package/dist/cjs/native/format.js +33 -0
  12. package/dist/cjs/native/gf256.js +50 -0
  13. package/dist/cjs/native/locator.js +159 -0
  14. package/dist/cjs/native/matrix-decoder.js +166 -0
  15. package/dist/cjs/native/matrix.js +31 -0
  16. package/dist/cjs/native/reed-solomon.js +106 -0
  17. package/dist/cjs/native/sampling.js +71 -0
  18. package/dist/cjs/native/scanner.js +60 -0
  19. package/dist/cjs/native/versions.js +45 -0
  20. package/dist/cjs/package.json +1 -0
  21. package/dist/esm/core/decoder.d.ts +59 -0
  22. package/dist/esm/core/decoder.js +242 -0
  23. package/dist/esm/core/encoding.d.ts +33 -0
  24. package/dist/esm/core/encoding.js +211 -0
  25. package/dist/esm/core/preprocess.d.ts +191 -0
  26. package/dist/esm/core/preprocess.js +670 -0
  27. package/dist/esm/index.d.ts +7 -0
  28. package/dist/esm/index.js +7 -0
  29. package/dist/esm/native/binarize.d.ts +6 -0
  30. package/dist/esm/native/binarize.js +73 -0
  31. package/dist/esm/native/bitstream.d.ts +14 -0
  32. package/dist/esm/native/bitstream.js +135 -0
  33. package/dist/esm/native/format.d.ts +9 -0
  34. package/dist/esm/native/format.js +30 -0
  35. package/dist/esm/native/gf256.d.ts +5 -0
  36. package/dist/esm/native/gf256.js +44 -0
  37. package/dist/esm/native/locator.d.ts +14 -0
  38. package/dist/esm/native/locator.js +156 -0
  39. package/dist/esm/native/matrix-decoder.d.ts +5 -0
  40. package/dist/esm/native/matrix-decoder.js +162 -0
  41. package/dist/esm/native/matrix.d.ts +12 -0
  42. package/dist/esm/native/matrix.js +27 -0
  43. package/dist/esm/native/reed-solomon.d.ts +2 -0
  44. package/dist/esm/native/reed-solomon.js +103 -0
  45. package/dist/esm/native/sampling.d.ts +7 -0
  46. package/dist/esm/native/sampling.js +68 -0
  47. package/dist/esm/native/scanner.d.ts +2 -0
  48. package/dist/esm/native/scanner.js +57 -0
  49. package/dist/esm/native/versions.d.ts +9 -0
  50. package/dist/esm/native/versions.js +42 -0
  51. package/dist/{index.d.ts → esm/types.d.ts} +18 -3
  52. package/package.json +17 -19
  53. package/dist/qr-decoder.js +0 -2611
  54. package/dist/qr-decoder.umd.cjs +0 -1
@@ -0,0 +1,211 @@
1
+ // Character encoding name normalization and multi-encoding fallback decoding.
2
+ const encodingAliasMap = {
3
+ // Simplified Chinese
4
+ GB: 'gbk',
5
+ GBK: 'gbk',
6
+ GB2312: 'gb2312',
7
+ GB_2312: 'gb2312',
8
+ GB18030: 'gb18030',
9
+ GB_18030: 'gb18030',
10
+ // Traditional Chinese
11
+ BIG5: 'big5',
12
+ BIG_5: 'big5',
13
+ BIG5_HKSCS: 'big5',
14
+ // UTF / ASCII
15
+ 'UTF-8': 'utf-8',
16
+ UTF8: 'utf-8',
17
+ UTF_8: 'utf-8',
18
+ UNICODEUTF8: 'utf-8',
19
+ 'UTF-16': 'utf-16',
20
+ UTF16: 'utf-16',
21
+ 'UTF-16LE': 'utf-16le',
22
+ 'UTF-16BE': 'utf-16be',
23
+ UCS2: 'utf-16le',
24
+ 'UCS-2': 'utf-16le',
25
+ ASCII: 'ascii',
26
+ 'US-ASCII': 'ascii',
27
+ // Western
28
+ 'WINDOWS-1252': 'windows-1252',
29
+ CP1252: 'windows-1252',
30
+ 'ISO-8859-1': 'windows-1252',
31
+ 'ISO8859-1': 'windows-1252',
32
+ LATIN1: 'windows-1252',
33
+ // Japanese
34
+ SHIFT_JIS: 'shift_jis',
35
+ SHIFTJIS: 'shift_jis',
36
+ SJIS: 'shift_jis',
37
+ MS_KANJI: 'shift_jis',
38
+ 'EUC-JP': 'euc-jp',
39
+ EUC_JP: 'euc-jp',
40
+ EUCJP: 'euc-jp',
41
+ // Korean
42
+ 'EUC-KR': 'euc-kr',
43
+ EUC_KR: 'euc-kr',
44
+ EUCKR: 'euc-kr',
45
+ 'KS_C_5601-1987': 'euc-kr',
46
+ // Other
47
+ 'ISO-2022-JP': 'iso-2022-jp',
48
+ 'ISO-2022-KR': 'iso-2022-kr',
49
+ };
50
+ /**
51
+ * Normalize an encoding name into a label understood by TextDecoder.
52
+ * Example: "GBK" -> "gbk", "Shift_JIS" -> "shift_jis".
53
+ */
54
+ export function normalizeEncoding(enc) {
55
+ if (!enc)
56
+ return 'utf-8';
57
+ let upper = String(enc).trim().toUpperCase();
58
+ upper = upper.replace(/\(.*?\)/g, '').trim();
59
+ if (encodingAliasMap[upper])
60
+ return encodingAliasMap[upper];
61
+ return upper.replace(/_/g, '-').toLowerCase();
62
+ }
63
+ // Fallback candidate list: standard universal CJK and western encodings
64
+ const FALLBACK_ENCODINGS = [
65
+ 'utf-8',
66
+ 'gb18030',
67
+ 'gbk',
68
+ 'big5',
69
+ 'gb2312',
70
+ 'shift_jis',
71
+ 'euc-jp',
72
+ 'euc-kr',
73
+ 'windows-1252',
74
+ ];
75
+ const TIEBREAK_PREFERENCE = [
76
+ 'utf-8',
77
+ 'gb18030',
78
+ 'gbk',
79
+ 'gb2312',
80
+ 'big5',
81
+ 'shift_jis',
82
+ 'euc-jp',
83
+ 'euc-kr',
84
+ 'windows-1252',
85
+ ];
86
+ function tiebreakRank(enc) {
87
+ const idx = TIEBREAK_PREFERENCE.indexOf(enc);
88
+ return idx === -1 ? TIEBREAK_PREFERENCE.length : idx;
89
+ }
90
+ /**
91
+ * Universal text readability scorer.
92
+ * Gives positive points for valid readable CJK and printable ASCII,
93
+ * while heavily penalizing mojibake (replacement character \uFFFD) and unexpected control codes.
94
+ * Contains ZERO project-specific heuristics.
95
+ *
96
+ * @param {string} text
97
+ * @returns {number}
98
+ */
99
+ export function scoreText(text) {
100
+ if (!text)
101
+ return -Infinity;
102
+ // CJK unified ideographs + kana + hangul
103
+ const cjkCount = (text.match(/[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af\uf900-\ufaff]/g) || []).length;
104
+ const replacementCount = (text.match(/\uFFFD/g) || []).length;
105
+ let printable = 0;
106
+ let garbage = 0;
107
+ for (let i = 0; i < text.length; i++) {
108
+ const c = text.charCodeAt(i);
109
+ // Printable characters + whitespace (\t, \n, \r)
110
+ if ((c >= 0x20 && c !== 0x7f) || c === 0x09 || c === 0x0a || c === 0x0d) {
111
+ printable++;
112
+ }
113
+ else {
114
+ garbage++;
115
+ }
116
+ }
117
+ // Heavy penalties for common mojibake sequences when multi-byte bytes are misinterpreted as Latin-1
118
+ let mojibakePenalty = 0;
119
+ if (/[¹ÐÖ¿ÅÆÑÌ]/.test(text))
120
+ mojibakePenalty += 40;
121
+ if (/Ã.|Â./.test(text))
122
+ mojibakePenalty += 30;
123
+ const ratioPenalty = text.length > 0 ? (replacementCount + garbage) / text.length : 1;
124
+ return (cjkCount * 10 +
125
+ printable * 2 -
126
+ mojibakePenalty -
127
+ (replacementCount + garbage) * 100 -
128
+ (ratioPenalty > 0.4 ? 10000 : 0));
129
+ }
130
+ /**
131
+ * Decode raw QR bytes with multi-encoding fallback.
132
+ * Uses native TextDecoder with automatic validation and heuristic scoring.
133
+ *
134
+ * @param {Uint8Array} bytes
135
+ * @param {string} [detectedEncoding] Optional encoding hint from the caller.
136
+ * @returns {{ text: string, score: number, encoding: string }}
137
+ */
138
+ export function decodeWithFallback(bytes, detectedEncoding) {
139
+ // 1. Strict UTF-8 verification: if bytes form completely valid UTF-8 without error,
140
+ // UTF-8 has the highest confidence.
141
+ let validUtf8 = false;
142
+ try {
143
+ new TextDecoder('utf-8', { fatal: true }).decode(bytes);
144
+ validUtf8 = true;
145
+ }
146
+ catch {
147
+ // Not valid UTF-8
148
+ }
149
+ const candidates = [normalizeEncoding(detectedEncoding), ...FALLBACK_ENCODINGS];
150
+ const unique = [];
151
+ for (const enc of candidates) {
152
+ if (enc && !unique.includes(enc))
153
+ unique.push(enc);
154
+ }
155
+ let best = { text: '', score: -Infinity, encoding: 'utf-8' };
156
+ for (const enc of unique) {
157
+ try {
158
+ const decoder = new TextDecoder(enc, { fatal: false });
159
+ const text = decoder.decode(bytes);
160
+ let score = scoreText(text);
161
+ if (validUtf8 && enc === 'utf-8') {
162
+ score += 5000;
163
+ }
164
+ if (score > best.score ||
165
+ (score === best.score && tiebreakRank(enc) < tiebreakRank(best.encoding))) {
166
+ best = { text, score, encoding: enc };
167
+ }
168
+ }
169
+ catch {
170
+ // Skip unsupported encodings in current JS environment
171
+ }
172
+ }
173
+ return best;
174
+ }
175
+ // Decode each byte segment separately: an ECI assignment applies to subsequent segments.
176
+ const ECI_ENCODINGS = { 3: 'iso-8859-1', 20: 'shift_jis', 26: 'utf-8', 28: 'big5', 29: 'gb18030', 30: 'euc-kr' };
177
+ export function decodeChunks(chunks, characterSet) {
178
+ let eci = null;
179
+ const encodings = [];
180
+ let text = '';
181
+ let guessed = null;
182
+ for (const chunk of chunks) {
183
+ if (chunk.type === 'eci') {
184
+ eci = ECI_ENCODINGS[chunk.assignmentNumber];
185
+ if (!eci)
186
+ throw new Error(`Unsupported ECI assignment ${chunk.assignmentNumber}`);
187
+ }
188
+ else if (chunk.type === 'byte') {
189
+ const bytes = new Uint8Array(chunk.bytes);
190
+ const declared = eci || characterSet;
191
+ if (declared) {
192
+ const encoding = eci === 'iso-8859-1' ? eci : normalizeEncoding(declared);
193
+ text += eci === 'iso-8859-1'
194
+ ? Array.from(bytes, byte => String.fromCharCode(byte)).join('')
195
+ : new TextDecoder(encoding, { fatal: true }).decode(bytes);
196
+ encodings.push(encoding);
197
+ }
198
+ else {
199
+ const result = decodeWithFallback(bytes);
200
+ text += result.text;
201
+ guessed = result.encoding;
202
+ encodings.push(result.encoding);
203
+ }
204
+ }
205
+ else {
206
+ text += chunk.text || '';
207
+ }
208
+ }
209
+ const unique = [...new Set(encodings)];
210
+ return { text, encoding: unique.length === 1 ? unique[0] : unique.length ? 'mixed' : 'utf-8', detectedEncoding: guessed };
211
+ }
@@ -0,0 +1,191 @@
1
+ /**
2
+ * Safe factory for ImageData or ImageData-compatible pixel container.
3
+ * Compatible with Browser DOM, Web Workers, OffscreenCanvas, and headless environments.
4
+ *
5
+ * @param {number} width
6
+ * @param {number} height
7
+ * @returns {ImageData}
8
+ */
9
+ export declare function createImageData(width: any, height: any): ImageData | {
10
+ width: any;
11
+ height: any;
12
+ data: Uint8ClampedArray<ArrayBuffer>;
13
+ };
14
+ /** Enlarge small colored codes before and after adaptive thresholding. */
15
+ export declare function enlargeSmallColorCode(imageData: any): ImageData | {
16
+ width: any;
17
+ height: any;
18
+ data: Uint8ClampedArray<ArrayBuffer>;
19
+ };
20
+ /**
21
+ * Generate targeted multi-path rescue variants for colored and blue-ink QR codes.
22
+ * Keeps the raw channel formulas first because they preserve module boundaries;
23
+ * stretched variants follow for images whose color range is especially narrow.
24
+ *
25
+ * 1. blue-enhanced: raw (2*R - B), the primary blue-ink rescue path.
26
+ * 2. red-channel: raw red channel, useful when blue ink absorbs red strongly.
27
+ * 3. blue-enhanced-stretched and red-stretched: dynamic-range rescue variants.
28
+ *
29
+ * @param {ImageData} imageData
30
+ * @returns {{ data: ImageData, label: string }[]}
31
+ */
32
+ export declare function generatePreprocessVariants(imageData: any): {
33
+ data: ImageData | {
34
+ width: any;
35
+ height: any;
36
+ data: Uint8ClampedArray<ArrayBuffer>;
37
+ };
38
+ label: string;
39
+ }[];
40
+ /**
41
+ * 3x3 Laplacian edge-sharpening (Unsharp Mask) filter.
42
+ * Directly restores blurry, out-of-focus, and low-contrast module transitions.
43
+ *
44
+ * @param {ImageData} imageData
45
+ * @param {number} [amount=1.2]
46
+ * @returns {ImageData}
47
+ */
48
+ export declare function sharpenImageData(imageData: any, amount?: number): ImageData | {
49
+ width: any;
50
+ height: any;
51
+ data: Uint8ClampedArray<ArrayBuffer>;
52
+ };
53
+ /**
54
+ * Generate CLAHE (Contrast Limited Adaptive Histogram Equalization) variants.
55
+ * Handles blur, weak focus, shadows, and locally uneven lighting.
56
+ *
57
+ * @param {ImageData} imageData
58
+ * @returns {{ data: ImageData, label: string }[]}
59
+ */
60
+ export declare function generateCLAHEVariants(imageData: any): {
61
+ data: ImageData | {
62
+ width: any;
63
+ height: any;
64
+ data: Uint8ClampedArray<ArrayBuffer>;
65
+ };
66
+ label: string;
67
+ }[];
68
+ /**
69
+ * Extract center crop (e.g. 60% of frame).
70
+ * Fixes distant / small QR codes in large high-resolution frames (e.g. 960px or 1080p).
71
+ * Prevents full-image downscaling from destroying small modules.
72
+ *
73
+ * @param {ImageData} imageData
74
+ * @param {number} [ratio=0.6]
75
+ * @returns {ImageData}
76
+ */
77
+ export declare function centerCrop(imageData: any, ratio?: number): ImageData | {
78
+ width: any;
79
+ height: any;
80
+ data: Uint8ClampedArray<ArrayBuffer>;
81
+ };
82
+ /**
83
+ * Perspective shear compensation for tilted/skewed QR codes.
84
+ * Uses fast Canvas 2D GPU transform where available, with fast affine CPU fallback.
85
+ *
86
+ * @param {ImageData} srcImageData
87
+ * @param {Array<{sx: number, sy: number, label: string}>} [shearAngles]
88
+ * @returns {{ data: ImageData, label: string }[]}
89
+ */
90
+ export declare function generateShearVariants(srcImageData: any, shearAngles?: {
91
+ sx: number;
92
+ sy: number;
93
+ label: string;
94
+ }[]): any[];
95
+ /**
96
+ * Pad an image with a clean white quiet zone border.
97
+ * Fixes edge-cropped QR codes that lack surrounding quiet zone.
98
+ *
99
+ * @param {ImageData} imageData
100
+ * @param {number} [borderRatio=0.15]
101
+ * @returns {ImageData|null}
102
+ */
103
+ export declare function addQuietZone(imageData: any, borderRatio?: number): ImageData | {
104
+ width: any;
105
+ height: any;
106
+ data: Uint8ClampedArray<ArrayBuffer>;
107
+ };
108
+ /**
109
+ * Generate inverted luma variant for light-on-dark (inverted) QR codes.
110
+ *
111
+ * @param {ImageData} imageData
112
+ * @returns {{ data: ImageData, label: string }}
113
+ */
114
+ export declare function generateInvertedVariant(imageData: any): {
115
+ data: ImageData | {
116
+ width: any;
117
+ height: any;
118
+ data: Uint8ClampedArray<ArrayBuffer>;
119
+ };
120
+ label: string;
121
+ };
122
+ /**
123
+ * Lightweight 3x3 morphological closing to heal broken dot-matrix / pin-printer dots.
124
+ *
125
+ * @param {ImageData} imageData
126
+ * @param {number} [threshold=135]
127
+ * @returns {{ data: ImageData, label: string }[]}
128
+ */
129
+ export declare function generateDotMatrixFixVariants(imageData: any, threshold?: number): {
130
+ data: ImageData | {
131
+ width: any;
132
+ height: any;
133
+ data: Uint8ClampedArray<ArrayBuffer>;
134
+ };
135
+ label: string;
136
+ }[];
137
+ /**
138
+ * Standard grayscale conversion.
139
+ *
140
+ * @param {ImageData} imgData
141
+ * @returns {Uint8ClampedArray}
142
+ */
143
+ export declare function toGray(imgData: any): Uint8ClampedArray<ArrayBuffer>;
144
+ /**
145
+ * Convert a 1-channel grayscale byte plane back to an RGBA ImageData.
146
+ *
147
+ * @param {Uint8ClampedArray} gray
148
+ * @param {number} width
149
+ * @param {number} height
150
+ * @returns {ImageData}
151
+ */
152
+ export declare function grayToImageData(gray: any, width: any, height: any): ImageData | {
153
+ width: any;
154
+ height: any;
155
+ data: Uint8ClampedArray<ArrayBuffer>;
156
+ };
157
+ /**
158
+ * Otsu global thresholding binarization.
159
+ *
160
+ * @param {Uint8ClampedArray} gray
161
+ * @param {number} width
162
+ * @param {number} height
163
+ * @returns {Uint8ClampedArray}
164
+ */
165
+ export declare function toOtsuBinary(gray: any, width: any, height: any): Uint8ClampedArray<any>;
166
+ /**
167
+ * Local adaptive thresholding for unevenly lit or low-contrast QR images.
168
+ * Uses an integral image so the per-pixel neighborhood mean stays linear-time.
169
+ *
170
+ * @param {Uint8ClampedArray} gray
171
+ * @param {number} width
172
+ * @param {number} height
173
+ * @param {number} [radius=8]
174
+ * @param {number} [bias=0.15]
175
+ * @returns {Uint8ClampedArray}
176
+ */
177
+ export declare function toAdaptiveBinary(gray: any, width: any, height: any, radius?: number, bias?: number): Uint8ClampedArray<any>;
178
+ /**
179
+ * CLAHE (Contrast Limited Adaptive Histogram Equalization) on a grayscale plane.
180
+ * Directly fixes blurred, poorly focused, or unevenly lit QR codes.
181
+ *
182
+ * @param {Uint8ClampedArray} gray
183
+ * @param {number} width
184
+ * @param {number} height
185
+ * @param {object} [opts]
186
+ * @returns {Uint8ClampedArray}
187
+ */
188
+ export declare function toCLAHE(gray: any, width: any, height: any, opts?: {
189
+ clipLimit?: number;
190
+ tileSize?: number;
191
+ }): Uint8ClampedArray<any>;