@sythos/js_barcode_universal 1.1.0 → 1.2.5

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 (44) hide show
  1. package/LICENSE +16 -17
  2. package/NOTICE.md +24 -22
  3. package/README.md +100 -49
  4. package/bundle/sythos-barcode.esm.js +2058 -54
  5. package/bundle/sythos-barcode.js +2050 -54
  6. package/examples/create.html +2 -1
  7. package/licenses/README.md +58 -30
  8. package/licenses/aztec-code.license +12 -12
  9. package/licenses/codabar.license +9 -9
  10. package/licenses/code-11.license +9 -9
  11. package/licenses/code-128.license +6 -6
  12. package/licenses/code-39.license +6 -6
  13. package/licenses/code-93.license +7 -7
  14. package/licenses/data-matrix.license +11 -11
  15. package/licenses/ean-13.license +6 -6
  16. package/licenses/ean-8.license +6 -6
  17. package/licenses/gs1-128.license +6 -6
  18. package/licenses/isbn.license +7 -7
  19. package/licenses/itf-14.license +6 -6
  20. package/licenses/itf.license +6 -6
  21. package/licenses/micropdf417.license +96 -0
  22. package/licenses/msi-plessey.license +7 -7
  23. package/licenses/pdf417.license +37 -0
  24. package/licenses/pharmacode.license +7 -7
  25. package/licenses/qr-code.license +6 -6
  26. package/licenses/upc-a.license +7 -7
  27. package/licenses/upc-e.license +6 -6
  28. package/package.json +9 -2
  29. package/src/core/reed-solomon.js +326 -312
  30. package/src/index.js +77 -3
  31. package/src/micropdf417/compaction.js +116 -0
  32. package/src/micropdf417/decoder.js +183 -0
  33. package/src/micropdf417/detector.js +149 -0
  34. package/src/micropdf417/encoder.js +209 -0
  35. package/src/micropdf417/error-correction.js +55 -0
  36. package/src/micropdf417/index.js +49 -0
  37. package/src/micropdf417/tables.js +184 -0
  38. package/src/pdf417/compaction.js +298 -0
  39. package/src/pdf417/decoder.js +75 -0
  40. package/src/pdf417/detector.js +468 -0
  41. package/src/pdf417/encoder.js +91 -0
  42. package/src/pdf417/error-correction.js +47 -0
  43. package/src/pdf417/index.js +6 -0
  44. package/src/pdf417/tables.js +317 -0
@@ -1,313 +1,327 @@
1
- /*!
2
- * Sythos Barcode Suite
3
- *
4
- * MIT License
5
- *
6
- * Copyright (c) 2026 Sythos
7
- *
8
- * Permission is hereby granted, free of charge, to any person obtaining a copy
9
- * of this software and associated documentation files (the "Software"), to deal
10
- * in the Software without restriction, including without limitation the rights
11
- * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
- * copies of the Software, and to permit persons to whom the Software is
13
- * furnished to do so, subject to the following conditions:
14
- *
15
- * The above copyright notice and this permission notice shall be included in all
16
- * copies or substantial portions of the Software.
17
- *
18
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
- * SOFTWARE.
25
- *
26
- * SPDX-License-Identifier: MIT
27
- *
28
- * Original work. No code from any other barcode implementation.
29
- */
30
-
31
- /**
32
- * Reed-Solomon encoding and decoding over an arbitrary finite field.
33
- *
34
- * Systematic encoding: the output is the message followed by parity symbols,
35
- * so the data is readable without decoding when the symbol is undamaged.
36
- *
37
- * Decoding is syndromes -> Berlekamp-Massey -> Chien search -> Forney.
38
- * It corrects up to floor(eccLen / 2) symbol errors at unknown positions.
39
- *
40
- * Every arithmetic operation routes through the field object. There is
41
- * deliberately not a single bare `^` in this file: XOR is correct for binary
42
- * fields and wrong for GF(929), and the resulting bug is invisible to any test
43
- * that only exercises QR or Data Matrix. See core/galois-field.js.
44
- *
45
- * Polynomial convention in this module: **coefficient index 0 is the highest
46
- * degree**, matching the wire order of a codeword. The decoder converts to
47
- * degree-ascending internally where the algorithms are stated that way.
48
- *
49
- * @module core/reed-solomon
50
- */
51
-
52
- import { ChecksumError } from './errors.js';
53
-
54
- /**
55
- * Build the generator polynomial for `eccLen` parity symbols.
56
- *
57
- * g(x) = product over i of (x - a^(base + i)), i = 0 .. eccLen-1
58
- *
1
+ /*!
2
+ * Sythos Barcode Suite
3
+ *
4
+ * MIT License
5
+ *
6
+ * Copyright (c) 2026 Sythos
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ * of this software and associated documentation files (the "Software"), to deal
10
+ * in the Software without restriction, including without limitation the rights
11
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ * copies of the Software, and to permit persons to whom the Software is
13
+ * furnished to do so, subject to the following conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all
16
+ * copies or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ * SOFTWARE.
25
+ *
26
+ * SPDX-License-Identifier: MIT
27
+ *
28
+ * Original work. No code from any other barcode implementation.
29
+ */
30
+
31
+ /**
32
+ * Reed-Solomon encoding and decoding over an arbitrary finite field.
33
+ *
34
+ * Systematic encoding: the output is the message followed by parity symbols,
35
+ * so the data is readable without decoding when the symbol is undamaged.
36
+ *
37
+ * Decoding is syndromes -> Berlekamp-Massey -> Chien search -> Forney.
38
+ * It corrects up to floor(eccLen / 2) symbol errors at unknown positions.
39
+ *
40
+ * Every arithmetic operation routes through the field object. There is
41
+ * deliberately not a single bare `^` in this file: XOR is correct for binary
42
+ * fields and wrong for GF(929), and the resulting bug is invisible to any test
43
+ * that only exercises QR or Data Matrix. See core/galois-field.js.
44
+ *
45
+ * Polynomial convention in this module: **coefficient index 0 is the highest
46
+ * degree**, matching the wire order of a codeword. The decoder converts to
47
+ * degree-ascending internally where the algorithms are stated that way.
48
+ *
49
+ * @module core/reed-solomon
50
+ */
51
+
52
+ import { ChecksumError } from './errors.js';
53
+
54
+ /**
55
+ * Build the generator polynomial for `eccLen` parity symbols.
56
+ *
57
+ * g(x) = product over i of (x - a^(base + i)), i = 0 .. eccLen-1
58
+ *
59
59
  * `base` is 0 for QR; 1 for Aztec, Data Matrix and PDF417.
60
- *
61
- * @param {number} eccLen
62
- * @param {import('./galois-field.js').GaloisField} field
63
- * @param {number} [base]
64
- * @returns {number[]} Monic, degree-descending, length eccLen + 1.
65
- */
66
- export function generatorPoly(eccLen, field, base = 0) {
67
- let g = [1];
68
- for (let i = 0; i < eccLen; i++) {
69
- const root = field.exp(base + i);
70
- const next = new Array(g.length + 1).fill(0);
71
- for (let j = 0; j < g.length; j++) {
72
- // g[j]*x lands at next[j]; g[j]*(-root) lands at next[j+1].
73
- next[j] = field.add(next[j], g[j]);
74
- next[j + 1] = field.sub(next[j + 1], field.mul(g[j], root));
75
- }
76
- g = next;
77
- }
78
- return g;
79
- }
80
-
81
- const generatorCache = new Map();
82
-
83
- /**
84
- * Cached {@link generatorPoly}. Encoding the same format repeatedly is the
85
- * common case and rebuilding the polynomial each time is pure waste.
86
- *
87
- * @param {number} eccLen
88
- * @param {import('./galois-field.js').GaloisField} field
89
- * @param {number} [base]
90
- * @returns {number[]}
91
- */
92
- function cachedGenerator(eccLen, field, base) {
93
- const key = `${field.name}|${eccLen}|${base}`;
94
- let g = generatorCache.get(key);
95
- if (!g) {
96
- g = generatorPoly(eccLen, field, base);
97
- generatorCache.set(key, g);
98
- }
99
- return g;
100
- }
101
-
102
- /**
103
- * Compute `eccLen` parity symbols for `data`.
104
- *
105
- * @param {ArrayLike<number>} data
106
- * @param {number} eccLen
107
- * @param {import('./galois-field.js').GaloisField} field
108
- * @param {number} [base]
109
- * @returns {number[]} The parity symbols alone, length eccLen.
110
- */
111
- export function rsEncode(data, eccLen, field, base = 0) {
112
- if (eccLen <= 0) return [];
113
- const gen = cachedGenerator(eccLen, field, base);
114
- const res = new Array(data.length + eccLen).fill(0);
115
- for (let i = 0; i < data.length; i++) res[i] = data[i];
116
-
117
- // Synthetic division by a monic divisor: the leading coefficient is
118
- // annihilated each step and its multiple subtracted from the tail.
119
- for (let i = 0; i < data.length; i++) {
120
- const coef = res[i];
121
- if (coef === 0) continue;
122
- for (let j = 1; j <= eccLen; j++) {
123
- res[i + j] = field.sub(res[i + j], field.mul(gen[j], coef));
124
- }
125
- }
126
-
127
- const remainder = res.slice(data.length);
128
-
129
- // The codeword is data(x)*x^eccLen MINUS the remainder, so the parity
130
- // symbols are the negated remainder. In a binary field negation is the
131
- // identity and this is invisible; in GF(929) omitting it produces a
132
- // codeword that is not divisible by the generator, and every symbol fails
133
- // to decode. Exactly the class of bug the field abstraction exists to stop.
134
- if (field.prime) {
135
- for (let i = 0; i < remainder.length; i++) remainder[i] = field.neg(remainder[i]);
136
- }
137
- return remainder;
138
- }
139
-
140
- /**
141
- * Evaluate a degree-descending polynomial at x (Horner).
142
- *
143
- * @param {ArrayLike<number>} poly
144
- * @param {number} x
145
- * @param {import('./galois-field.js').GaloisField} field
146
- * @returns {number}
147
- */
148
- function evalPoly(poly, x, field) {
149
- let acc = 0;
150
- for (let i = 0; i < poly.length; i++) {
151
- acc = field.add(field.mul(acc, x), poly[i]);
152
- }
153
- return acc;
154
- }
155
-
156
- /**
157
- * Correct errors in a received codeword, in place.
158
- *
159
- * @param {number[]} received Data followed by parity, degree-descending.
160
- * @param {number} eccLen
161
- * @param {import('./galois-field.js').GaloisField} field
162
- * @param {number} [base]
163
- * @returns {number} Number of symbols corrected.
164
- * @throws {ChecksumError} If the damage exceeds the correction capacity.
165
- */
166
- export function rsDecode(received, eccLen, field, base = 0) {
167
- const n = received.length;
168
-
169
- // --- Syndromes. S[i] = R(a^(base+i)); all zero means an intact codeword.
170
- const syn = new Array(eccLen).fill(0);
171
- let damaged = false;
172
- for (let i = 0; i < eccLen; i++) {
173
- const s = evalPoly(received, field.exp(base + i), field);
174
- syn[i] = s;
175
- if (s !== 0) damaged = true;
176
- }
177
- if (!damaged) return 0;
178
-
179
- // --- Berlekamp-Massey. Degree-ascending here: lambda[k] is the coefficient
180
- // of x^k, which is how the recurrence is naturally stated.
181
- const lambda = new Array(eccLen + 1).fill(0);
182
- const prev = new Array(eccLen + 1).fill(0);
183
- const tmp = new Array(eccLen + 1).fill(0);
184
- lambda[0] = 1;
185
- prev[0] = 1;
186
- let errCount = 0; // current LFSR length
187
- let shift = 1; // steps since `prev` was last updated
188
- let lastDisc = 1; // discrepancy at that update
189
-
190
- for (let step = 0; step < eccLen; step++) {
191
- let disc = syn[step];
192
- for (let i = 1; i <= errCount; i++) {
193
- disc = field.add(disc, field.mul(lambda[i], syn[step - i]));
194
- }
195
-
196
- if (disc === 0) {
197
- shift++;
198
- continue;
199
- }
200
-
201
- const scale = field.div(disc, lastDisc);
202
- tmp.fill(0);
203
- for (let i = 0; i <= eccLen; i++) tmp[i] = lambda[i];
204
-
205
- for (let i = 0; i + shift <= eccLen; i++) {
206
- if (prev[i] === 0) continue;
207
- lambda[i + shift] = field.sub(lambda[i + shift], field.mul(scale, prev[i]));
208
- }
209
-
210
- if (2 * errCount <= step) {
211
- errCount = step + 1 - errCount;
212
- for (let i = 0; i <= eccLen; i++) prev[i] = tmp[i];
213
- lastDisc = disc;
214
- shift = 1;
215
- } else {
216
- shift++;
217
- }
218
- }
219
-
220
- if (errCount === 0 || errCount > eccLen / 2) {
221
- throw new ChecksumError(
222
- `Reed-Solomon: ${errCount} errors exceeds correction capacity ` +
223
- `${Math.floor(eccLen / 2)} (${field.name})`
224
- );
225
- }
226
-
227
- // --- Chien search. Position p (counted from the low-order end) is in error
228
- // when lambda(a^-p) == 0.
229
- const positions = [];
230
- for (let p = 0; p < n; p++) {
231
- const xInv = field.exp(-p);
232
- let acc = 0;
233
- let term = 1;
234
- for (let i = 0; i <= errCount; i++) {
235
- acc = field.add(acc, field.mul(lambda[i], term));
236
- term = field.mul(term, xInv);
237
- }
238
- if (acc === 0) positions.push(p);
239
- }
240
-
241
- if (positions.length !== errCount) {
242
- throw new ChecksumError(
243
- `Reed-Solomon: located ${positions.length} of ${errCount} error positions`
244
- );
245
- }
246
-
247
- // --- Error evaluator. omega(x) = [S(x) * lambda(x)] mod x^eccLen,
248
- // with S degree-ascending.
249
- const omega = new Array(eccLen).fill(0);
250
- for (let i = 0; i < eccLen; i++) {
251
- let acc = 0;
252
- for (let j = 0; j <= i && j <= errCount; j++) {
253
- acc = field.add(acc, field.mul(lambda[j], syn[i - j]));
254
- }
255
- omega[i] = acc;
256
- }
257
-
258
- // --- Forney. For an error at position p, with X = a^p:
259
- // magnitude = -X^(1-base) * omega(X^-1) / lambda'(X^-1)
260
- // The sign is a no-op in binary fields and load-bearing in GF(929).
261
- let corrected = 0;
262
- for (const p of positions) {
263
- const xInv = field.exp(-p);
264
-
265
- let num = 0;
266
- let term = 1;
267
- for (let i = 0; i < eccLen; i++) {
268
- num = field.add(num, field.mul(omega[i], term));
269
- term = field.mul(term, xInv);
270
- }
271
-
272
- // Formal derivative: only odd-index terms survive in a binary field, but
273
- // in a prime field every term contributes with an integer multiplier.
274
- let den = 0;
275
- term = 1;
276
- for (let i = 1; i <= errCount; i++) {
277
- if (field.prime) {
278
- // i * lambda[i] * x^(i-1), where `i` is repeated addition.
279
- let mult = 0;
280
- const t = field.mul(lambda[i], term);
281
- for (let k = 0; k < i; k++) mult = field.add(mult, t);
282
- den = field.add(den, mult);
283
- } else if (i % 2 === 1) {
284
- den = field.add(den, field.mul(lambda[i], term));
285
- }
286
- term = field.mul(term, xInv);
287
- }
288
-
289
- if (den === 0) {
290
- throw new ChecksumError('Reed-Solomon: singular error locator derivative');
291
- }
292
-
293
- let magnitude = field.div(num, den);
294
- // X^(1-base): one factor of X when base is 0, none when base is 1.
295
- if (base === 0) magnitude = field.mul(magnitude, field.exp(p));
296
- else if (base !== 1) magnitude = field.mul(magnitude, field.exp(p * (1 - base)));
297
- magnitude = field.neg(magnitude);
298
-
299
- const idx = n - 1 - p;
300
- received[idx] = field.sub(received[idx], magnitude);
301
- corrected++;
302
- }
303
-
304
- // Verify: a genuine correction zeroes every syndrome. Without this check,
305
- // damage beyond capacity can produce a plausible-looking wrong answer.
306
- for (let i = 0; i < eccLen; i++) {
307
- if (evalPoly(received, field.exp(base + i), field) !== 0) {
308
- throw new ChecksumError('Reed-Solomon: correction failed verification');
309
- }
310
- }
311
-
312
- return corrected;
313
- }
60
+ *
61
+ * @param {number} eccLen
62
+ * @param {import('./galois-field.js').GaloisField} field
63
+ * @param {number} [base]
64
+ * @returns {number[]} Monic, degree-descending, length eccLen + 1.
65
+ */
66
+ export function generatorPoly(eccLen, field, base = 0) {
67
+ let g = [1];
68
+ for (let i = 0; i < eccLen; i++) {
69
+ const root = field.exp(base + i);
70
+ const next = new Array(g.length + 1).fill(0);
71
+ for (let j = 0; j < g.length; j++) {
72
+ // g[j]*x lands at next[j]; g[j]*(-root) lands at next[j+1].
73
+ next[j] = field.add(next[j], g[j]);
74
+ next[j + 1] = field.sub(next[j + 1], field.mul(g[j], root));
75
+ }
76
+ g = next;
77
+ }
78
+ return g;
79
+ }
80
+
81
+ const generatorCache = new Map();
82
+
83
+ /**
84
+ * Cached {@link generatorPoly}. Encoding the same format repeatedly is the
85
+ * common case and rebuilding the polynomial each time is pure waste.
86
+ *
87
+ * @param {number} eccLen
88
+ * @param {import('./galois-field.js').GaloisField} field
89
+ * @param {number} [base]
90
+ * @returns {number[]}
91
+ */
92
+ function cachedGenerator(eccLen, field, base) {
93
+ const key = `${field.name}|${eccLen}|${base}`;
94
+ let g = generatorCache.get(key);
95
+ if (!g) {
96
+ g = generatorPoly(eccLen, field, base);
97
+ generatorCache.set(key, g);
98
+ }
99
+ return g;
100
+ }
101
+
102
+ /**
103
+ * Compute `eccLen` parity symbols for `data`.
104
+ *
105
+ * @param {ArrayLike<number>} data
106
+ * @param {number} eccLen
107
+ * @param {import('./galois-field.js').GaloisField} field
108
+ * @param {number} [base]
109
+ * @returns {number[]} The parity symbols alone, length eccLen.
110
+ */
111
+ export function rsEncode(data, eccLen, field, base = 0) {
112
+ if (eccLen <= 0) return [];
113
+ const gen = cachedGenerator(eccLen, field, base);
114
+ const res = new Array(data.length + eccLen).fill(0);
115
+ for (let i = 0; i < data.length; i++) res[i] = data[i];
116
+
117
+ // Synthetic division by a monic divisor: the leading coefficient is
118
+ // annihilated each step and its multiple subtracted from the tail.
119
+ for (let i = 0; i < data.length; i++) {
120
+ const coef = res[i];
121
+ if (coef === 0) continue;
122
+ for (let j = 1; j <= eccLen; j++) {
123
+ res[i + j] = field.sub(res[i + j], field.mul(gen[j], coef));
124
+ }
125
+ }
126
+
127
+ const remainder = res.slice(data.length);
128
+
129
+ // The codeword is data(x)*x^eccLen MINUS the remainder, so the parity
130
+ // symbols are the negated remainder. In a binary field negation is the
131
+ // identity and this is invisible; in GF(929) omitting it produces a
132
+ // codeword that is not divisible by the generator, and every symbol fails
133
+ // to decode. Exactly the class of bug the field abstraction exists to stop.
134
+ if (field.prime) {
135
+ for (let i = 0; i < remainder.length; i++) remainder[i] = field.neg(remainder[i]);
136
+ }
137
+ return remainder;
138
+ }
139
+
140
+ /**
141
+ * Evaluate a degree-descending polynomial at x (Horner).
142
+ *
143
+ * @param {ArrayLike<number>} poly
144
+ * @param {number} x
145
+ * @param {import('./galois-field.js').GaloisField} field
146
+ * @returns {number}
147
+ */
148
+ function evalPoly(poly, x, field) {
149
+ let acc = 0;
150
+ for (let i = 0; i < poly.length; i++) {
151
+ acc = field.add(field.mul(acc, x), poly[i]);
152
+ }
153
+ return acc;
154
+ }
155
+
156
+ function multiplyAscending(left, right, field, limit) {
157
+ const out = new Array(Math.min(limit, left.length + right.length - 1)).fill(0);
158
+ for (let i = 0; i < left.length; i++) for (let j = 0; j < right.length && i + j < out.length; j++) {
159
+ out[i + j] = field.add(out[i + j], field.mul(left[i], right[j]));
160
+ }
161
+ return out;
162
+ }
163
+
164
+ function berlekampMassey(syndromes, field) {
165
+ const limit = syndromes.length;
166
+ const lambda = new Array(limit + 1).fill(0);
167
+ const previous = new Array(limit + 1).fill(0);
168
+ const temporary = new Array(limit + 1).fill(0);
169
+ lambda[0] = 1;
170
+ previous[0] = 1;
171
+ let errorCount = 0;
172
+ let shift = 1;
173
+ let lastDiscrepancy = 1;
174
+
175
+ for (let step = 0; step < limit; step++) {
176
+ let discrepancy = syndromes[step];
177
+ for (let i = 1; i <= errorCount; i++) discrepancy = field.add(discrepancy, field.mul(lambda[i], syndromes[step - i]));
178
+ if (discrepancy === 0) { shift++; continue; }
179
+ const scale = field.div(discrepancy, lastDiscrepancy);
180
+ for (let i = 0; i <= limit; i++) temporary[i] = lambda[i];
181
+ for (let i = 0; i + shift <= limit; i++) if (previous[i] !== 0) {
182
+ lambda[i + shift] = field.sub(lambda[i + shift], field.mul(scale, previous[i]));
183
+ }
184
+ if (2 * errorCount <= step) {
185
+ errorCount = step + 1 - errorCount;
186
+ for (let i = 0; i <= limit; i++) previous[i] = temporary[i];
187
+ lastDiscrepancy = discrepancy;
188
+ shift = 1;
189
+ } else shift++;
190
+ }
191
+ return { locator: lambda.slice(0, errorCount + 1), errorCount };
192
+ }
193
+
194
+ /**
195
+ * Correct errors in a received codeword, in place.
196
+ *
197
+ * @param {number[]} received Data followed by parity, degree-descending.
198
+ * @param {number} eccLen
199
+ * @param {import('./galois-field.js').GaloisField} field
200
+ * @param {number} [base]
201
+ * @param {number[]} [erasures] Known damaged indexes, counted from wire order.
202
+ * @returns {number} Number of symbols corrected.
203
+ * @throws {ChecksumError} If the damage exceeds the correction capacity.
204
+ */
205
+ export function rsDecode(received, eccLen, field, base = 0, erasures = []) {
206
+ const n = received.length;
207
+ if (!Array.isArray(erasures) || new Set(erasures).size !== erasures.length || erasures.some((index) => !Number.isInteger(index) || index < 0 || index >= n)) {
208
+ throw new ChecksumError('Reed-Solomon: erasure positions must be unique codeword indexes');
209
+ }
210
+ if (erasures.length > eccLen) throw new ChecksumError(`Reed-Solomon: ${erasures.length} erasures exceeds correction capacity ${eccLen} (${field.name})`);
211
+
212
+ // --- Syndromes. S[i] = R(a^(base+i)); all zero means an intact codeword.
213
+ const syn = new Array(eccLen).fill(0);
214
+ let damaged = false;
215
+ for (let i = 0; i < eccLen; i++) {
216
+ const s = evalPoly(received, field.exp(base + i), field);
217
+ syn[i] = s;
218
+ if (s !== 0) damaged = true;
219
+ }
220
+ if (!damaged) return 0;
221
+
222
+ // Remove the known roots before locating unknown errors. The leading
223
+ // erasureCount terms contain only the known-location transient and are not
224
+ // part of the error-only recurrence.
225
+ let erasureLocator = [1];
226
+ for (const index of erasures) {
227
+ const location = field.exp(n - 1 - index);
228
+ erasureLocator = multiplyAscending(erasureLocator, [1, field.neg(location)], field, eccLen + 1);
229
+ }
230
+ const modified = multiplyAscending(syn, erasureLocator, field, eccLen).slice(erasures.length);
231
+ const { locator: errorLocator, errorCount } = berlekampMassey(modified, field);
232
+ if (2 * errorCount + erasures.length > eccLen) {
233
+ throw new ChecksumError(
234
+ `Reed-Solomon: ${errorCount} errors and ${erasures.length} erasures exceed correction capacity ` +
235
+ `${eccLen} (${field.name})`
236
+ );
237
+ }
238
+ const lambda = multiplyAscending(erasureLocator, errorLocator, field, eccLen + 1);
239
+ const totalCount = errorCount + erasures.length;
240
+
241
+ // --- Chien search. Position p (counted from the low-order end) is in error
242
+ // when lambda(a^-p) == 0.
243
+ const positions = [];
244
+ for (let p = 0; p < n; p++) {
245
+ const xInv = field.exp(-p);
246
+ let acc = 0;
247
+ let term = 1;
248
+ for (let i = 0; i <= totalCount; i++) {
249
+ acc = field.add(acc, field.mul(lambda[i], term));
250
+ term = field.mul(term, xInv);
251
+ }
252
+ if (acc === 0) positions.push(p);
253
+ }
254
+
255
+ if (positions.length !== totalCount) {
256
+ throw new ChecksumError(
257
+ `Reed-Solomon: located ${positions.length} of ${totalCount} error positions`
258
+ );
259
+ }
260
+
261
+ // --- Error evaluator. omega(x) = [S(x) * lambda(x)] mod x^eccLen,
262
+ // with S degree-ascending.
263
+ const omega = new Array(eccLen).fill(0);
264
+ for (let i = 0; i < eccLen; i++) {
265
+ let acc = 0;
266
+ for (let j = 0; j <= i && j <= totalCount; j++) {
267
+ acc = field.add(acc, field.mul(lambda[j], syn[i - j]));
268
+ }
269
+ omega[i] = acc;
270
+ }
271
+
272
+ // --- Forney. For an error at position p, with X = a^p:
273
+ // magnitude = -X^(1-base) * omega(X^-1) / lambda'(X^-1)
274
+ // The sign is a no-op in binary fields and load-bearing in GF(929).
275
+ let corrected = 0;
276
+ for (const p of positions) {
277
+ const xInv = field.exp(-p);
278
+
279
+ let num = 0;
280
+ let term = 1;
281
+ for (let i = 0; i < eccLen; i++) {
282
+ num = field.add(num, field.mul(omega[i], term));
283
+ term = field.mul(term, xInv);
284
+ }
285
+
286
+ // Formal derivative: only odd-index terms survive in a binary field, but
287
+ // in a prime field every term contributes with an integer multiplier.
288
+ let den = 0;
289
+ term = 1;
290
+ for (let i = 1; i <= totalCount; i++) {
291
+ if (field.prime) {
292
+ // i * lambda[i] * x^(i-1), where `i` is repeated addition.
293
+ let mult = 0;
294
+ const t = field.mul(lambda[i], term);
295
+ for (let k = 0; k < i; k++) mult = field.add(mult, t);
296
+ den = field.add(den, mult);
297
+ } else if (i % 2 === 1) {
298
+ den = field.add(den, field.mul(lambda[i], term));
299
+ }
300
+ term = field.mul(term, xInv);
301
+ }
302
+
303
+ if (den === 0) {
304
+ throw new ChecksumError('Reed-Solomon: singular error locator derivative');
305
+ }
306
+
307
+ let magnitude = field.div(num, den);
308
+ // X^(1-base): one factor of X when base is 0, none when base is 1.
309
+ if (base === 0) magnitude = field.mul(magnitude, field.exp(p));
310
+ else if (base !== 1) magnitude = field.mul(magnitude, field.exp(p * (1 - base)));
311
+ magnitude = field.neg(magnitude);
312
+
313
+ const idx = n - 1 - p;
314
+ received[idx] = field.sub(received[idx], magnitude);
315
+ corrected++;
316
+ }
317
+
318
+ // Verify: a genuine correction zeroes every syndrome. Without this check,
319
+ // damage beyond capacity can produce a plausible-looking wrong answer.
320
+ for (let i = 0; i < eccLen; i++) {
321
+ if (evalPoly(received, field.exp(base + i), field) !== 0) {
322
+ throw new ChecksumError('Reed-Solomon: correction failed verification');
323
+ }
324
+ }
325
+
326
+ return corrected;
327
+ }