@sythos/js_barcode_universal 1.5.8 → 1.5.10

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 (179) hide show
  1. package/LICENSE +5 -4
  2. package/NOTICE.md +2 -2
  3. package/README.md +61 -13
  4. package/bundle/sythos-barcode.esm.js +11658 -11244
  5. package/bundle/sythos-barcode.js +11658 -11244
  6. package/package.json +10 -3
  7. package/src/index.d.ts +1 -1
  8. package/src/index.js +508 -516
  9. package/src/js/aztec/decoder.js +208 -199
  10. package/src/js/aztec/detector.js +153 -126
  11. package/src/js/aztec/encoder.js +172 -153
  12. package/src/js/aztec/high-level.js +106 -101
  13. package/src/js/aztec/index.js +1 -12
  14. package/src/js/aztec/tables.js +106 -120
  15. package/src/js/aztecrune/decoder.js +76 -85
  16. package/src/js/aztecrune/detector.js +107 -93
  17. package/src/js/aztecrune/encoder.js +50 -68
  18. package/src/js/aztecrune/index.js +1 -16
  19. package/src/js/aztecrune/tables.js +59 -54
  20. package/src/js/compactpdf417/decoder.js +69 -74
  21. package/src/js/compactpdf417/detector.js +74 -75
  22. package/src/js/compactpdf417/encoder.js +68 -81
  23. package/src/js/compactpdf417/index.js +1 -13
  24. package/src/js/compactpdf417/tables.js +71 -80
  25. package/src/js/core/bit-buffer.js +106 -122
  26. package/src/js/core/bit-matrix.js +196 -194
  27. package/src/js/core/errors.js +13 -15
  28. package/src/js/core/galois-field.js +119 -133
  29. package/src/js/core/index.js +2 -19
  30. package/src/js/core/reed-solomon.js +195 -204
  31. package/src/js/databar/codec.js +93 -108
  32. package/src/js/databar/decoder.js +149 -140
  33. package/src/js/databar/encoder.js +47 -55
  34. package/src/js/databar/gs1.js +122 -123
  35. package/src/js/databar/index.js +4 -36
  36. package/src/js/databar/patterns.js +81 -85
  37. package/src/js/databar/tables.js +51 -52
  38. package/src/js/datamatrix/decoder.js +216 -182
  39. package/src/js/datamatrix/detector.js +161 -132
  40. package/src/js/datamatrix/encoder.js +192 -133
  41. package/src/js/datamatrix/index.js +1 -9
  42. package/src/js/datamatrix/tables.js +68 -69
  43. package/src/js/frameqr/decoder.js +102 -125
  44. package/src/js/frameqr/detector.js +101 -94
  45. package/src/js/frameqr/encoder.js +67 -80
  46. package/src/js/frameqr/index.js +1 -10
  47. package/src/js/frameqr/tables.js +145 -163
  48. package/src/js/image/binarizer.js +146 -162
  49. package/src/js/image/grid-sampler.js +63 -79
  50. package/src/js/image/index.js +0 -2
  51. package/src/js/image/luminance.js +129 -140
  52. package/src/js/image/perspective.js +112 -149
  53. package/src/js/micropdf417/compaction.js +64 -65
  54. package/src/js/micropdf417/decoder.js +106 -109
  55. package/src/js/micropdf417/detector.js +73 -70
  56. package/src/js/micropdf417/encoder.js +129 -154
  57. package/src/js/micropdf417/error-correction.js +6 -11
  58. package/src/js/micropdf417/index.js +2 -16
  59. package/src/js/micropdf417/tables.js +112 -99
  60. package/src/js/microqr/decoder.js +177 -182
  61. package/src/js/microqr/detector.js +240 -256
  62. package/src/js/microqr/encoder.js +239 -194
  63. package/src/js/microqr/index.js +0 -2
  64. package/src/js/microqr/tables.js +208 -200
  65. package/src/js/oned/addons.js +167 -191
  66. package/src/js/oned/index.js +27 -58
  67. package/src/js/oned/patterns.js +194 -213
  68. package/src/js/oned/reader.js +1003 -984
  69. package/src/js/oned/writers.js +411 -466
  70. package/src/js/pdf417/compaction.js +315 -222
  71. package/src/js/pdf417/decoder.js +71 -36
  72. package/src/js/pdf417/detector.js +377 -361
  73. package/src/js/pdf417/encoder.js +57 -46
  74. package/src/js/pdf417/error-correction.js +5 -8
  75. package/src/js/pdf417/tables.js +248 -250
  76. package/src/js/qr/decoder.js +311 -347
  77. package/src/js/qr/detector.js +378 -395
  78. package/src/js/qr/encoder.js +514 -599
  79. package/src/js/qr/index.js +0 -2
  80. package/src/js/qr/tables.js +375 -422
  81. package/src/js/render/image-data.js +57 -62
  82. package/src/js/render/index.js +21 -23
  83. package/src/js/render/options.js +82 -90
  84. package/src/js/render/png.js +144 -169
  85. package/src/js/render/svg.js +41 -44
  86. package/src/js/render/webgl.js +103 -109
  87. package/src/js/render/webgpu.js +205 -217
  88. package/src/js/rmqr/decoder.js +161 -53
  89. package/src/js/rmqr/detector.js +73 -41
  90. package/src/js/rmqr/encoder.js +253 -104
  91. package/src/js/rmqr/index.js +1 -5
  92. package/src/js/rmqr/tables.js +108 -85
  93. package/src/ts/aztec/decoder.ts +317 -0
  94. package/src/ts/aztec/detector.ts +224 -0
  95. package/src/ts/aztec/encoder.ts +257 -0
  96. package/src/ts/aztec/high-level.ts +211 -0
  97. package/src/ts/aztec/index.ts +45 -0
  98. package/src/ts/aztec/tables.ts +210 -0
  99. package/src/ts/aztecrune/decoder.ts +155 -0
  100. package/src/ts/aztecrune/detector.ts +166 -0
  101. package/src/ts/aztecrune/encoder.ts +121 -0
  102. package/src/ts/aztecrune/index.ts +49 -0
  103. package/src/ts/aztecrune/tables.ts +137 -0
  104. package/src/ts/compactpdf417/decoder.ts +128 -0
  105. package/src/ts/compactpdf417/detector.ts +139 -0
  106. package/src/ts/compactpdf417/encoder.ts +140 -0
  107. package/src/ts/compactpdf417/index.ts +17 -0
  108. package/src/ts/compactpdf417/tables.ts +173 -0
  109. package/src/ts/core/bit-buffer.ts +174 -0
  110. package/src/ts/core/bit-matrix.ts +241 -0
  111. package/src/ts/core/errors.ts +61 -0
  112. package/src/ts/core/galois-field.ts +207 -0
  113. package/src/ts/core/index.ts +56 -0
  114. package/src/ts/core/reed-solomon.ts +327 -0
  115. package/src/ts/databar/codec.ts +181 -0
  116. package/src/ts/databar/decoder.ts +215 -0
  117. package/src/ts/databar/encoder.ts +96 -0
  118. package/src/ts/databar/gs1.ts +177 -0
  119. package/src/ts/databar/index.ts +68 -0
  120. package/src/ts/databar/patterns.ts +143 -0
  121. package/src/ts/databar/tables.ts +124 -0
  122. package/src/ts/datamatrix/decoder.ts +262 -0
  123. package/src/ts/datamatrix/detector.ts +225 -0
  124. package/src/ts/datamatrix/encoder.ts +191 -0
  125. package/src/ts/datamatrix/index.ts +42 -0
  126. package/src/ts/datamatrix/tables.ts +123 -0
  127. package/src/ts/frameqr/decoder.ts +239 -0
  128. package/src/ts/frameqr/detector.ts +192 -0
  129. package/src/ts/frameqr/encoder.ts +156 -0
  130. package/src/ts/frameqr/index.ts +42 -0
  131. package/src/ts/frameqr/tables.ts +270 -0
  132. package/src/ts/image/binarizer.ts +270 -0
  133. package/src/ts/image/grid-sampler.ts +164 -0
  134. package/src/ts/image/index.ts +40 -0
  135. package/src/ts/image/luminance.ts +196 -0
  136. package/src/ts/image/perspective.ts +195 -0
  137. package/src/ts/index.d.ts +1 -1
  138. package/src/ts/index.ts +790 -0
  139. package/src/ts/micropdf417/compaction.ts +116 -0
  140. package/src/ts/micropdf417/decoder.ts +183 -0
  141. package/src/ts/micropdf417/detector.ts +149 -0
  142. package/src/ts/micropdf417/encoder.ts +209 -0
  143. package/src/ts/micropdf417/error-correction.ts +55 -0
  144. package/src/ts/micropdf417/index.ts +49 -0
  145. package/src/ts/micropdf417/tables.ts +184 -0
  146. package/src/ts/microqr/decoder.ts +245 -0
  147. package/src/ts/microqr/detector.ts +355 -0
  148. package/src/ts/microqr/encoder.ts +269 -0
  149. package/src/ts/microqr/index.ts +36 -0
  150. package/src/ts/microqr/tables.ts +316 -0
  151. package/src/ts/oned/addons.ts +420 -0
  152. package/src/ts/oned/index.ts +106 -0
  153. package/src/ts/oned/patterns.ts +384 -0
  154. package/src/ts/oned/reader.ts +1364 -0
  155. package/src/ts/oned/writers.ts +746 -0
  156. package/src/ts/pdf417/compaction.ts +298 -0
  157. package/src/ts/pdf417/decoder.ts +75 -0
  158. package/src/ts/pdf417/detector.ts +468 -0
  159. package/src/ts/pdf417/encoder.ts +91 -0
  160. package/src/ts/pdf417/error-correction.ts +47 -0
  161. package/src/ts/pdf417/index.ts +6 -0
  162. package/src/ts/pdf417/tables.ts +317 -0
  163. package/src/ts/qr/decoder.ts +575 -0
  164. package/src/ts/qr/detector.ts +630 -0
  165. package/src/ts/qr/encoder.ts +958 -0
  166. package/src/ts/qr/index.ts +44 -0
  167. package/src/ts/qr/tables.ts +737 -0
  168. package/src/ts/render/image-data.ts +125 -0
  169. package/src/ts/render/index.ts +130 -0
  170. package/src/ts/render/options.ts +160 -0
  171. package/src/ts/render/png.ts +295 -0
  172. package/src/ts/render/svg.ts +120 -0
  173. package/src/ts/render/webgl.ts +206 -0
  174. package/src/ts/render/webgpu.ts +369 -0
  175. package/src/ts/rmqr/decoder.ts +101 -0
  176. package/src/ts/rmqr/detector.ts +90 -0
  177. package/src/ts/rmqr/encoder.ts +172 -0
  178. package/src/ts/rmqr/index.ts +37 -0
  179. package/src/ts/rmqr/tables.ts +154 -0
@@ -0,0 +1,143 @@
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
+ /** Mathematical width construction for GS1 DataBar characters. @module databar/patterns */
32
+
33
+ import { dataBar14GroupFor } from './tables.js';
34
+
35
+ function combinations(n, r) {
36
+ if (n < r || r < 0) return 0;
37
+ if (r === 0 || n === r) return 1;
38
+ let result = 1;
39
+ const k = Math.min(r, n - r);
40
+ for (let i = 1; i <= k; i++) result = result * (n - k + i) / i;
41
+ return result;
42
+ }
43
+
44
+ /**
45
+ * Unrank one constrained positive composition.
46
+ *
47
+ * The rank is the GS1 DataBar symbol-character value inside its group. This
48
+ * implementation follows the combinatorial definition directly: it counts
49
+ * every remaining admissible suffix rather than storing third-party patterns.
50
+ */
51
+ export function dataBarWidths(rank, modules, elements, maximumWidth, noNarrow) {
52
+ if (!Number.isInteger(rank) || rank < 0) throw new RangeError('GS1 DataBar width rank must be non-negative');
53
+ const widths = new Array(elements).fill(0);
54
+ let remaining = modules;
55
+ let narrowMask = 0;
56
+
57
+ for (let bar = 0; bar < elements - 1; bar++) {
58
+ let count = 0;
59
+ for (let width = 1; ; width++) {
60
+ narrowMask |= width === 1 ? 1 << bar : 0;
61
+ count = combinations(remaining - width - 1, elements - bar - 2);
62
+
63
+ if (noNarrow && narrowMask === 0 && remaining - width - (elements - bar - 1) >= elements - bar - 1) {
64
+ count -= combinations(remaining - width - (elements - bar), elements - bar - 2);
65
+ }
66
+
67
+ if (elements - bar - 1 > 1) {
68
+ let tooWide = 0;
69
+ for (let last = remaining - width - (elements - bar - 2); last > maximumWidth; last--) {
70
+ tooWide += combinations(remaining - width - last - 1, elements - bar - 3);
71
+ }
72
+ count -= tooWide * (elements - 1 - bar);
73
+ } else if (remaining - width > maximumWidth) {
74
+ count--;
75
+ }
76
+
77
+ if (rank < count) {
78
+ widths[bar] = width;
79
+ remaining -= width;
80
+ break;
81
+ }
82
+ rank -= count;
83
+ narrowMask &= ~(1 << bar);
84
+ }
85
+ }
86
+ widths[elements - 1] = remaining;
87
+ if (rank !== 0 || widths.some((width) => width < 1 || width > maximumWidth)) {
88
+ throw new RangeError('GS1 DataBar width rank exceeds its character group');
89
+ }
90
+ return widths;
91
+ }
92
+
93
+ /** Convert one DataBar-14 character value into its eight alternating widths. */
94
+ export function dataBar14CharacterWidths(value, kind) {
95
+ const group = dataBar14GroupFor(value, kind);
96
+ const offset = value - group.gsum;
97
+ const outside = kind === 'outside';
98
+ const oddRank = outside ? Math.floor(offset / group.evenTotal) : offset % group.oddTotal;
99
+ const evenRank = outside ? offset % group.evenTotal : Math.floor(offset / group.oddTotal);
100
+ const odd = dataBarWidths(oddRank, group.oddModules, 4, group.oddWidest, !outside);
101
+ const even = dataBarWidths(evenRank, group.evenModules, 4, group.evenWidest, outside);
102
+ const result = [];
103
+ for (let i = 0; i < 4; i++) result.push(odd[i], even[i]);
104
+ return result;
105
+ }
106
+
107
+ const inverseCharacterMaps = new Map();
108
+
109
+ /** Recover a character value from its canonical eight-width representation. */
110
+ export function dataBar14ValueForWidths(widths, kind) {
111
+ if (!Array.isArray(widths) || widths.length !== 8 || widths.some((width) => !Number.isInteger(width) || width < 1)) {
112
+ throw new TypeError('GS1 DataBar character widths must contain eight positive integers');
113
+ }
114
+ if (kind !== 'outside' && kind !== 'inside') throw new RangeError(`Unknown GS1 DataBar character kind "${kind}"`);
115
+ let inverse = inverseCharacterMaps.get(kind);
116
+ if (!inverse) {
117
+ inverse = new Map();
118
+ const maximum = kind === 'outside' ? 2840 : 1596;
119
+ for (let value = 0; value <= maximum; value++) {
120
+ inverse.set(dataBar14CharacterWidths(value, kind).join(','), value);
121
+ }
122
+ inverseCharacterMaps.set(kind, inverse);
123
+ }
124
+ const value = inverse.get(widths.join(','));
125
+ if (value === undefined) throw new RangeError(`Invalid GS1 DataBar ${kind} character widths`);
126
+ return value;
127
+ }
128
+
129
+ /** Nine finder patterns, expressed as normative five-element widths. */
130
+ export const DATABAR14_FINDERS = Object.freeze([
131
+ Object.freeze([3, 8, 2, 1, 1]), Object.freeze([3, 5, 5, 1, 1]),
132
+ Object.freeze([3, 3, 7, 1, 1]), Object.freeze([3, 1, 9, 1, 1]),
133
+ Object.freeze([2, 7, 4, 1, 1]), Object.freeze([2, 5, 6, 1, 1]),
134
+ Object.freeze([2, 3, 8, 1, 1]), Object.freeze([1, 5, 7, 1, 1]),
135
+ Object.freeze([1, 3, 9, 1, 1]),
136
+ ]);
137
+
138
+ /** Weight sequence generated as powers of three modulo 79. */
139
+ export const DATABAR14_CHECKSUM_WEIGHTS = Object.freeze(Array.from({ length: 32 }, (_, index) => {
140
+ let value = 1;
141
+ for (let i = 0; i < index; i++) value = (value * 3) % 79;
142
+ return value;
143
+ }));
@@ -0,0 +1,124 @@
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
+ * Static GS1 DataBar facts used by the GTIN compaction codec.
33
+ *
34
+ * The numbers in the DataBar-14 group tables are the public tables in
35
+ * ISO/IEC 24724:2011, clauses 5.2.2 and 5.2.3. They describe values, not a
36
+ * third-party implementation. Pattern construction deliberately belongs in
37
+ * the renderer/encoder layer so this module stays a small, auditable contract.
38
+ *
39
+ * @module databar/tables
40
+ */
41
+
42
+ const group = (first, last, gsum, oddModules, evenModules, oddWidest, evenWidest, oddTotal, evenTotal) => Object.freeze({
43
+ first, last, gsum, oddModules, evenModules, oddWidest, evenWidest, oddTotal, evenTotal,
44
+ });
45
+
46
+ /** The four GTIN-only layouts sharing the DataBar-14 compaction rules. */
47
+ export const DATABAR14_VARIANTS = Object.freeze({
48
+ omnidirectional: Object.freeze({ id: 'omnidirectional', rows: 1, modules: 96, checksumModulus: 79, pointOfSale: true }),
49
+ truncated: Object.freeze({ id: 'truncated', rows: 1, modules: 96, checksumModulus: 79, pointOfSale: false }),
50
+ stacked: Object.freeze({ id: 'stacked', rows: 2, modules: 50, checksumModulus: 79, pointOfSale: false }),
51
+ 'stacked-omnidirectional': Object.freeze({ id: 'stacked-omnidirectional', rows: 2, modules: 50, checksumModulus: 79, pointOfSale: true }),
52
+ });
53
+
54
+ /** GS1 DataBar Limited is a distinct two-character symbology. */
55
+ export const DATABAR_LIMITED_VARIANT = Object.freeze({
56
+ id: 'limited', rows: 1, checksumModulus: 89, pointOfSale: false,
57
+ permittedIndicatorDigits: Object.freeze([0, 1]),
58
+ });
59
+
60
+ /** (16,4) outside character groups, ISO/IEC 24724:2011 Table 1. */
61
+ export const DATABAR14_OUTSIDE_GROUPS = Object.freeze([
62
+ group(0, 160, 0, 12, 4, 8, 1, 161, 1),
63
+ group(161, 960, 161, 10, 6, 6, 3, 80, 10),
64
+ group(961, 2014, 961, 8, 8, 4, 5, 31, 34),
65
+ group(2015, 2714, 2015, 6, 10, 3, 6, 10, 70),
66
+ group(2715, 2840, 2715, 4, 12, 1, 8, 1, 126),
67
+ ]);
68
+
69
+ /** (15,4) inside character groups, ISO/IEC 24724:2011 Table 2. */
70
+ export const DATABAR14_INSIDE_GROUPS = Object.freeze([
71
+ group(0, 335, 0, 5, 10, 2, 7, 4, 84),
72
+ group(336, 1035, 336, 7, 8, 4, 5, 20, 35),
73
+ group(1036, 1515, 1036, 9, 6, 6, 3, 48, 10),
74
+ group(1516, 1596, 1516, 11, 4, 8, 1, 81, 1),
75
+ ]);
76
+
77
+ /** Number of values carried by an inside (15,4) character. */
78
+ export const DATABAR14_INSIDE_RADIX = 1597;
79
+ /** Number of values carried by one outside/inside character pair. */
80
+ export const DATABAR14_PAIR_RADIX = 4537077;
81
+ /** Stand-alone and composite DataBar-14 payload domain, including linkage. */
82
+ export const DATABAR14_SYMBOL_LIMIT = 20000000000000n;
83
+
84
+ /** GS1 DataBar Limited divides its 13 data digits into two character values. */
85
+ export const DATABAR_LIMITED_PAIR_RADIX = 2013571;
86
+ /** Offset that switches a DataBar Limited value from stand-alone to composite. */
87
+ export const DATABAR_LIMITED_LINKAGE_OFFSET = 2015133531096n;
88
+ /** DataBar Limited carries GTIN values whose first digit is zero or one. */
89
+ export const DATABAR_LIMITED_DATA_LIMIT = 2000000000000n;
90
+
91
+ /** Locate the value group that an outside or inside character belongs to. */
92
+ export function dataBar14GroupFor(value, kind) {
93
+ if (!Number.isInteger(value)) throw new TypeError('GS1 DataBar character value must be an integer');
94
+ const groups = kind === 'outside' ? DATABAR14_OUTSIDE_GROUPS
95
+ : kind === 'inside' ? DATABAR14_INSIDE_GROUPS : null;
96
+ if (!groups) throw new RangeError(`Unknown GS1 DataBar character kind "${kind}"`);
97
+ const found = groups.find((entry) => value >= entry.first && value <= entry.last);
98
+ if (!found) throw new RangeError(`GS1 DataBar ${kind} character value ${value} is out of range`);
99
+ return found;
100
+ }
101
+ /** Check the independently represented table identities. */
102
+ export function validateDataBarTables() {
103
+ const problems = [];
104
+ const validateGroups = (name, groups, expectedLast) => {
105
+ let next = 0;
106
+ for (const entry of groups) {
107
+ if (entry.first !== next) problems.push(`${name}: gap before ${entry.first}`);
108
+ if (entry.last < entry.first) problems.push(`${name}: inverted range ${entry.first}-${entry.last}`);
109
+ if (entry.oddTotal * entry.evenTotal !== entry.last - entry.first + 1) {
110
+ problems.push(`${name}: combination count mismatch at ${entry.first}`);
111
+ }
112
+ next = entry.last + 1;
113
+ }
114
+ if (next - 1 !== expectedLast) problems.push(`${name}: final value is ${next - 1}, expected ${expectedLast}`);
115
+ };
116
+ validateGroups('outside', DATABAR14_OUTSIDE_GROUPS, 2840);
117
+ validateGroups('inside', DATABAR14_INSIDE_GROUPS, 1596);
118
+ if (DATABAR14_PAIR_RADIX !== 2841 * DATABAR14_INSIDE_RADIX) problems.push('pair radix mismatch');
119
+ if (DATABAR14_SYMBOL_LIMIT !== 2n * 10000000000000n) problems.push('symbol limit mismatch');
120
+ if (DATABAR_LIMITED_LINKAGE_OFFSET !== BigInt(DATABAR_LIMITED_PAIR_RADIX) * 1000776n) {
121
+ problems.push('limited linkage offset mismatch');
122
+ }
123
+ return problems;
124
+ }
@@ -0,0 +1,262 @@
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
+ * Data Matrix ECC 200 decoder for an already sampled symbol.
33
+ *
34
+ * The detector owns locating, perspective correction and orientation. This
35
+ * module starts with the complete, upright symbol including its finder borders.
36
+ * The table entry is deliberately read through a small normalizer so table data
37
+ * remains declarative: it needs total rows/columns, one data-region's rows and
38
+ * columns, data/ECC codeword counts, and either a block count or data block
39
+ * lengths. The standard 144x144 uneven data blocks are supported.
40
+ *
41
+ * @module datamatrix/decoder
42
+ */
43
+
44
+ import { ChecksumError, FormatError } from '../core/errors.js';
45
+ import { GF256_DM } from '../core/galois-field.js';
46
+ import { rsDecode } from '../core/reed-solomon.js';
47
+ import { SYMBOLS } from './tables.js';
48
+
49
+ const CW_PAD = 129;
50
+ const CW_BASE256 = 231;
51
+
52
+ /** @param {object} entry @param {...string} names @returns {number | undefined} */
53
+ function numberField(entry, ...names) {
54
+ for (const name of names) if (Number.isInteger(entry[name])) return entry[name];
55
+ return undefined;
56
+ }
57
+
58
+ /** Normalize the public table entry into the decoder's geometry contract. */
59
+ function layoutFor(width, height) {
60
+ const entry = SYMBOLS.find((s) =>
61
+ numberField(s, 'columns', 'cols', 'matrixColumns', 'width') === width &&
62
+ numberField(s, 'rows', 'matrixRows', 'height') === height);
63
+ if (!entry) throw new FormatError(`Data Matrix: ${width}x${height} is not an ECC 200 symbol size`);
64
+
65
+ const regionRows = numberField(entry, 'dataRegionRows', 'regionRows') ??
66
+ (numberField(entry, 'regionHeight') ? numberField(entry, 'regionHeight') - 2 : undefined);
67
+ const regionCols = numberField(entry, 'dataRegionColumns', 'dataRegionCols', 'regionColumns') ??
68
+ (numberField(entry, 'regionWidth') ? numberField(entry, 'regionWidth') - 2 : undefined);
69
+ const dataCount = numberField(entry, 'dataCodewords', 'dataCapacity');
70
+ const eccCount = numberField(entry, 'errorCodewords', 'eccCodewords');
71
+ const blockCount = numberField(entry, 'interleavedBlocks', 'interleavedBlockCount', 'blockCount', 'rsBlocks') || 1;
72
+ if (!regionRows || !regionCols || dataCount === undefined || eccCount === undefined ||
73
+ height % (regionRows + 2) || width % (regionCols + 2) || eccCount % blockCount) {
74
+ throw new FormatError(`Data Matrix: invalid table layout for ${width}x${height}`);
75
+ }
76
+
77
+ const rows = height / (regionRows + 2);
78
+ const cols = width / (regionCols + 2);
79
+ const blockData = Array.isArray(entry.blockDataCodewords) ? entry.blockDataCodewords.slice() :
80
+ Array.isArray(entry.dataCodewordsPerBlock) ? entry.dataCodewordsPerBlock.slice() : null;
81
+ let dataLengths;
82
+ if (blockData) {
83
+ dataLengths = blockData;
84
+ } else {
85
+ // The sole uneven ECC 200 distribution is 144x144: its first eight of ten
86
+ // blocks contain one extra data codeword. This derives it instead of hiding
87
+ // a magic size check in the deinterleaver.
88
+ const short = Math.floor(dataCount / blockCount);
89
+ dataLengths = new Array(blockCount).fill(short);
90
+ for (let i = 0; i < dataCount % blockCount; i++) dataLengths[i]++;
91
+ }
92
+ if (dataLengths.length !== blockCount || dataLengths.reduce((a, b) => a + b, 0) !== dataCount) {
93
+ throw new FormatError(`Data Matrix: inconsistent block layout for ${width}x${height}`);
94
+ }
95
+ return { entry, regionRows, regionCols, regionRowCount: rows, regionColCount: cols,
96
+ dataRows: rows * regionRows, dataCols: cols * regionCols, dataCount, eccCount,
97
+ blockCount, eccPerBlock: eccCount / blockCount, dataLengths };
98
+ }
99
+
100
+ /** Remove the L/finders from every data region, retaining only placement modules. */
101
+ function extractDataModules(matrix, layout) {
102
+ const data = new Uint8Array(layout.dataRows * layout.dataCols);
103
+ for (let regionY = 0; regionY < layout.regionRowCount; regionY++) {
104
+ for (let regionX = 0; regionX < layout.regionColCount; regionX++) {
105
+ const sourceX = regionX * (layout.regionCols + 2) + 1;
106
+ const sourceY = regionY * (layout.regionRows + 2) + 1;
107
+ for (let y = 0; y < layout.regionRows; y++) {
108
+ const targetY = regionY * layout.regionRows + y;
109
+ for (let x = 0; x < layout.regionCols; x++) {
110
+ data[targetY * layout.dataCols + regionX * layout.regionCols + x] =
111
+ matrix.get(sourceX + x, sourceY + y) ? 1 : 0;
112
+ }
113
+ }
114
+ }
115
+ }
116
+ return data;
117
+ }
118
+
119
+ /** Read placement codewords using the ECC 200 Utah sweep (the inverse writer path). */
120
+ function readPlacement(modules, rows, cols, count) {
121
+ const seen = new Uint8Array(rows * cols);
122
+ const out = new Uint8Array(count);
123
+ const get = (row, col) => modules[row * cols + col] !== 0;
124
+ const module = (row, col) => {
125
+ if (row < 0) { row += rows; col += 4 - ((rows + 4) % 8); }
126
+ if (col < 0) { col += cols; row += 4 - ((cols + 4) % 8); }
127
+ if (row < 0 || row >= rows || col < 0 || col >= cols) {
128
+ throw new FormatError('Data Matrix: placement coordinate escaped data region');
129
+ }
130
+ seen[row * cols + col] = 1;
131
+ return get(row, col) ? 1 : 0;
132
+ };
133
+ const bits = (coords) => coords.reduce((value, p) => (value << 1) | module(p[0], p[1]), 0);
134
+ const utah = (row, col) => bits([[row - 2, col - 2], [row - 2, col - 1], [row - 1, col - 2], [row - 1, col - 1],
135
+ [row - 1, col], [row, col - 2], [row, col - 1], [row, col]]);
136
+ const corner1 = () => bits([[rows - 1, 0], [rows - 1, 1], [rows - 1, 2], [0, cols - 2], [0, cols - 1], [1, cols - 1], [2, cols - 1], [3, cols - 1]]);
137
+ const corner2 = () => bits([[rows - 3, 0], [rows - 2, 0], [rows - 1, 0], [0, cols - 4], [0, cols - 3], [0, cols - 2], [0, cols - 1], [1, cols - 1]]);
138
+ const corner3 = () => bits([[rows - 3, 0], [rows - 2, 0], [rows - 1, 0], [0, cols - 2], [0, cols - 1], [1, cols - 1], [2, cols - 1], [3, cols - 1]]);
139
+ const corner4 = () => bits([[rows - 1, 0], [rows - 1, cols - 1], [0, cols - 3], [0, cols - 2], [0, cols - 1], [1, cols - 3], [1, cols - 2], [1, cols - 1]]);
140
+
141
+ let row = 4, col = 0, n = 0;
142
+ const put = (value) => { if (n < count) out[n++] = value; };
143
+ do {
144
+ if (row === rows && col === 0) put(corner1());
145
+ if (row === rows - 2 && col === 0 && cols % 4 !== 0) put(corner2());
146
+ if (row === rows - 2 && col === 0 && cols % 8 === 4) put(corner3());
147
+ if (row === rows + 4 && col === 2 && cols % 8 === 0) put(corner4());
148
+ do { if (row < rows && col >= 0 && !seen[row * cols + col]) put(utah(row, col)); row -= 2; col += 2; } while (row >= 0 && col < cols);
149
+ row += 1; col += 3;
150
+ do { if (row >= 0 && col < cols && !seen[row * cols + col]) put(utah(row, col)); row += 2; col -= 2; } while (row < rows && col >= 0);
151
+ row += 3; col += 1;
152
+ } while (row < rows || col < cols);
153
+ if (n !== count) throw new FormatError(`Data Matrix: placement yielded ${n}, expected ${count} codewords`);
154
+ return out;
155
+ }
156
+
157
+ /** Restore RS blocks, correct them, then concatenate their data portions. */
158
+ function deinterleaveAndCorrect(codewords, layout) {
159
+ if (codewords.length !== layout.dataCount + layout.eccCount) throw new FormatError('Data Matrix: codeword count mismatch');
160
+ const blocks = layout.dataLengths.map((len) => new Uint8Array(len + layout.eccPerBlock));
161
+ // Data codewords arrive in their original stream order. ECC 200 deals that
162
+ // stream round-robin across the RS blocks, so the inverse is determined by
163
+ // the wire index rather than by splitting it into consecutive block-sized
164
+ // chunks. For 144x144, indices 1550..1557 naturally land in the eight long
165
+ // blocks while the two short blocks remain at 155 data codewords.
166
+ for (let i = 0; i < layout.dataCount; i++) {
167
+ blocks[i % layout.blockCount][Math.floor(i / layout.blockCount)] = codewords[i];
168
+ }
169
+
170
+ // Parity normally begins with block zero. The uneven 144x144 layout rotates
171
+ // the parity wire order to begin with its first short block; derive the same
172
+ // mapping from the declarative lengths instead of keying it to dimensions.
173
+ const longest = Math.max(...layout.dataLengths);
174
+ const firstShort = layout.dataLengths.findIndex((length) => length < longest);
175
+ const rotation = firstShort < 0 ? 0 : firstShort;
176
+ let at = layout.dataCount;
177
+ for (let i = 0; i < layout.eccPerBlock; i++) {
178
+ for (let slot = 0; slot < layout.blockCount; slot++) {
179
+ const block = (slot + rotation) % layout.blockCount;
180
+ blocks[block][layout.dataLengths[block] + i] = codewords[at++];
181
+ }
182
+ }
183
+
184
+ let corrections = 0;
185
+ const data = new Uint8Array(layout.dataCount);
186
+ for (let b = 0; b < blocks.length; b++) {
187
+ corrections += rsDecode(blocks[b], layout.eccPerBlock, GF256_DM, 1);
188
+ }
189
+ // Rebuild the original high-level codeword stream after correction. Keeping
190
+ // this in wire-index order is essential: concatenating block data passes
191
+ // single-block round trips but scrambles every multi-block payload.
192
+ for (let i = 0; i < layout.dataCount; i++) {
193
+ data[i] = blocks[i % layout.blockCount][Math.floor(i / layout.blockCount)];
194
+ }
195
+ return { data, corrections };
196
+ }
197
+
198
+ function unrandomize(value, position) {
199
+ const pseudo = ((149 * position) % 255) + 1;
200
+ return value - pseudo >= 0 ? value - pseudo : value - pseudo + 256;
201
+ }
202
+
203
+ /** Decode ASCII plus Base 256, preserving semantic bytes alongside text. */
204
+ function parseData(data) {
205
+ let text = '';
206
+ const bytes = [];
207
+ let upperShift = false;
208
+ let gs1 = false;
209
+ for (let i = 0; i < data.length;) {
210
+ const cw = data[i++];
211
+ if (cw === CW_PAD) break;
212
+ if (cw <= 128) {
213
+ const value = cw - 1 + (upperShift ? 128 : 0);
214
+ upperShift = false;
215
+ text += String.fromCharCode(value); bytes.push(value); continue;
216
+ }
217
+ if (cw <= 229) {
218
+ const pair = cw - 130;
219
+ const digits = String(pair).padStart(2, '0'); text += digits; bytes.push(digits.charCodeAt(0), digits.charCodeAt(1)); continue;
220
+ }
221
+ if (cw === 232) {
222
+ if (i === 1) gs1 = true;
223
+ else { text += '\x1d'; bytes.push(29); }
224
+ continue;
225
+ }
226
+ if (cw === 235) { upperShift = true; continue; }
227
+ if (cw === CW_BASE256) {
228
+ if (i >= data.length) throw new FormatError('Data Matrix: Base 256 length is missing');
229
+ let length = unrandomize(data[i], i + 1); i++;
230
+ if (length === 0) length = data.length - i;
231
+ else if (length >= 250) {
232
+ if (i >= data.length) throw new FormatError('Data Matrix: Base 256 extended length is missing');
233
+ length = 250 * (length - 249) + unrandomize(data[i], i + 1); i++;
234
+ }
235
+ if (i + length > data.length) throw new FormatError('Data Matrix: Base 256 segment exceeds data capacity');
236
+ const segment = new Uint8Array(length);
237
+ for (let n = 0; n < length; n++, i++) segment[n] = unrandomize(data[i], i + 1);
238
+ bytes.push(...segment);
239
+ for (let n = 0; n < segment.length; n++) text += String.fromCharCode(segment[n]);
240
+ continue;
241
+ }
242
+ throw new FormatError(`Data Matrix: unsupported encoding codeword ${cw}`);
243
+ }
244
+ return { text, bytes: Uint8Array.from(bytes), gs1 };
245
+ }
246
+
247
+ /**
248
+ * Decode an upright, sampled Data Matrix ECC 200 symbol.
249
+ *
250
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix Full symbol, no quiet zone.
251
+ * @returns {{text: string, bytes: Uint8Array, correctedErrors: number, symbol: object}}
252
+ */
253
+ export function decodeDataMatrix(matrix) {
254
+ if (!matrix || !Number.isInteger(matrix.width) || !Number.isInteger(matrix.height)) throw new FormatError('Data Matrix: no matrix supplied');
255
+ const layout = layoutFor(matrix.width, matrix.height);
256
+ const placement = readPlacement(extractDataModules(matrix, layout), layout.dataRows, layout.dataCols, layout.dataCount + layout.eccCount);
257
+ const { data, corrections } = deinterleaveAndCorrect(placement, layout);
258
+ const result = parseData(data);
259
+ return { ...result, corrections, correctedErrors: corrections, symbol: layout.entry };
260
+ }
261
+
262
+ export { ChecksumError };