@sythos/js_barcode_universal 1.0.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 (57) hide show
  1. package/LICENSE +16 -17
  2. package/NOTICE.md +24 -22
  3. package/README.md +137 -60
  4. package/bundle/sythos-barcode.esm.js +3380 -216
  5. package/bundle/sythos-barcode.js +3368 -216
  6. package/examples/create.html +2 -0
  7. package/examples/read.html +341 -341
  8. package/licenses/README.md +58 -29
  9. package/licenses/aztec-code.license +74 -0
  10. package/licenses/codabar.license +9 -9
  11. package/licenses/code-11.license +9 -9
  12. package/licenses/code-128.license +6 -6
  13. package/licenses/code-39.license +6 -6
  14. package/licenses/code-93.license +7 -7
  15. package/licenses/data-matrix.license +11 -11
  16. package/licenses/ean-13.license +6 -6
  17. package/licenses/ean-8.license +6 -6
  18. package/licenses/gs1-128.license +6 -6
  19. package/licenses/isbn.license +7 -7
  20. package/licenses/itf-14.license +6 -6
  21. package/licenses/itf.license +6 -6
  22. package/licenses/micropdf417.license +96 -0
  23. package/licenses/msi-plessey.license +7 -7
  24. package/licenses/pdf417.license +37 -0
  25. package/licenses/pharmacode.license +7 -7
  26. package/licenses/qr-code.license +6 -6
  27. package/licenses/upc-a.license +7 -7
  28. package/licenses/upc-e.license +6 -6
  29. package/package.json +13 -3
  30. package/src/aztec/decoder.js +317 -0
  31. package/src/aztec/detector.js +224 -0
  32. package/src/aztec/encoder.js +257 -0
  33. package/src/aztec/high-level.js +211 -0
  34. package/src/aztec/index.js +45 -0
  35. package/src/aztec/tables.js +210 -0
  36. package/src/core/galois-field.js +3 -0
  37. package/src/core/reed-solomon.js +64 -50
  38. package/src/datamatrix/decoder.js +262 -262
  39. package/src/datamatrix/detector.js +225 -225
  40. package/src/datamatrix/encoder.js +191 -191
  41. package/src/datamatrix/index.js +42 -42
  42. package/src/datamatrix/tables.js +123 -123
  43. package/src/index.js +113 -3
  44. package/src/micropdf417/compaction.js +116 -0
  45. package/src/micropdf417/decoder.js +183 -0
  46. package/src/micropdf417/detector.js +149 -0
  47. package/src/micropdf417/encoder.js +209 -0
  48. package/src/micropdf417/error-correction.js +55 -0
  49. package/src/micropdf417/index.js +49 -0
  50. package/src/micropdf417/tables.js +184 -0
  51. package/src/pdf417/compaction.js +298 -0
  52. package/src/pdf417/decoder.js +75 -0
  53. package/src/pdf417/detector.js +468 -0
  54. package/src/pdf417/encoder.js +91 -0
  55. package/src/pdf417/error-correction.js +47 -0
  56. package/src/pdf417/index.js +6 -0
  57. package/src/pdf417/tables.js +317 -0
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Sythos Barcode Suite v1.0.0
2
+ * Sythos Barcode Suite v1.2.5
3
3
  *
4
4
  * MIT License
5
5
  *
@@ -2917,6 +2917,9 @@ const GF256_QR = new GaloisField({ size: 256, primitive: 0x011d, name: 'GF(256)/
2917
2917
  /** Data Matrix ECC200. x^8 + x^5 + x^3 + x^2 + 1 */
2918
2918
  const GF256_DM = new GaloisField({ size: 256, primitive: 0x012d, name: 'GF(256)/DataMatrix' });
2919
2919
 
2920
+ /** Aztec's eight-bit data field is algebraically identical to Data Matrix's. */
2921
+ const GF256_AZTEC = GF256_DM;
2922
+
2920
2923
  /** PDF417. Prime field; 3 is a primitive root modulo 929. */
2921
2924
  const GF929 = new GaloisField({ size: 929, prime: true, generator: 3, name: 'GF(929)' });
2922
2925
 
@@ -2929,6 +2932,7 @@ const GF4096 = new GaloisField({ size: 4096, primitive: 0x1069, name: 'GF(4096)'
2929
2932
  __exports.GaloisField = GaloisField;
2930
2933
  __exports.GF256_QR = GF256_QR;
2931
2934
  __exports.GF256_DM = GF256_DM;
2935
+ __exports.GF256_AZTEC = GF256_AZTEC;
2932
2936
  __exports.GF929 = GF929;
2933
2937
  __exports.GF16 = GF16;
2934
2938
  __exports.GF64 = GF64;
@@ -2964,7 +2968,7 @@ const { ChecksumError } = __require("core/errors.js");
2964
2968
  *
2965
2969
  * g(x) = product over i of (x - a^(base + i)), i = 0 .. eccLen-1
2966
2970
  *
2967
- * `base` is 0 for QR and Aztec; 1 for Data Matrix and PDF417.
2971
+ * `base` is 0 for QR; 1 for Aztec, Data Matrix and PDF417.
2968
2972
  *
2969
2973
  * @param {number} eccLen
2970
2974
  * @param {import('./galois-field.js').GaloisField} field
@@ -3061,6 +3065,44 @@ function evalPoly(poly, x, field) {
3061
3065
  return acc;
3062
3066
  }
3063
3067
 
3068
+ function multiplyAscending(left, right, field, limit) {
3069
+ const out = new Array(Math.min(limit, left.length + right.length - 1)).fill(0);
3070
+ for (let i = 0; i < left.length; i++) for (let j = 0; j < right.length && i + j < out.length; j++) {
3071
+ out[i + j] = field.add(out[i + j], field.mul(left[i], right[j]));
3072
+ }
3073
+ return out;
3074
+ }
3075
+
3076
+ function berlekampMassey(syndromes, field) {
3077
+ const limit = syndromes.length;
3078
+ const lambda = new Array(limit + 1).fill(0);
3079
+ const previous = new Array(limit + 1).fill(0);
3080
+ const temporary = new Array(limit + 1).fill(0);
3081
+ lambda[0] = 1;
3082
+ previous[0] = 1;
3083
+ let errorCount = 0;
3084
+ let shift = 1;
3085
+ let lastDiscrepancy = 1;
3086
+
3087
+ for (let step = 0; step < limit; step++) {
3088
+ let discrepancy = syndromes[step];
3089
+ for (let i = 1; i <= errorCount; i++) discrepancy = field.add(discrepancy, field.mul(lambda[i], syndromes[step - i]));
3090
+ if (discrepancy === 0) { shift++; continue; }
3091
+ const scale = field.div(discrepancy, lastDiscrepancy);
3092
+ for (let i = 0; i <= limit; i++) temporary[i] = lambda[i];
3093
+ for (let i = 0; i + shift <= limit; i++) if (previous[i] !== 0) {
3094
+ lambda[i + shift] = field.sub(lambda[i + shift], field.mul(scale, previous[i]));
3095
+ }
3096
+ if (2 * errorCount <= step) {
3097
+ errorCount = step + 1 - errorCount;
3098
+ for (let i = 0; i <= limit; i++) previous[i] = temporary[i];
3099
+ lastDiscrepancy = discrepancy;
3100
+ shift = 1;
3101
+ } else shift++;
3102
+ }
3103
+ return { locator: lambda.slice(0, errorCount + 1), errorCount };
3104
+ }
3105
+
3064
3106
  /**
3065
3107
  * Correct errors in a received codeword, in place.
3066
3108
  *
@@ -3068,11 +3110,16 @@ function evalPoly(poly, x, field) {
3068
3110
  * @param {number} eccLen
3069
3111
  * @param {import('./galois-field.js').GaloisField} field
3070
3112
  * @param {number} [base]
3113
+ * @param {number[]} [erasures] Known damaged indexes, counted from wire order.
3071
3114
  * @returns {number} Number of symbols corrected.
3072
3115
  * @throws {ChecksumError} If the damage exceeds the correction capacity.
3073
3116
  */
3074
- function rsDecode(received, eccLen, field, base = 0) {
3117
+ function rsDecode(received, eccLen, field, base = 0, erasures = []) {
3075
3118
  const n = received.length;
3119
+ if (!Array.isArray(erasures) || new Set(erasures).size !== erasures.length || erasures.some((index) => !Number.isInteger(index) || index < 0 || index >= n)) {
3120
+ throw new ChecksumError('Reed-Solomon: erasure positions must be unique codeword indexes');
3121
+ }
3122
+ if (erasures.length > eccLen) throw new ChecksumError(`Reed-Solomon: ${erasures.length} erasures exceeds correction capacity ${eccLen} (${field.name})`);
3076
3123
 
3077
3124
  // --- Syndromes. S[i] = R(a^(base+i)); all zero means an intact codeword.
3078
3125
  const syn = new Array(eccLen).fill(0);
@@ -3084,53 +3131,24 @@ function rsDecode(received, eccLen, field, base = 0) {
3084
3131
  }
3085
3132
  if (!damaged) return 0;
3086
3133
 
3087
- // --- Berlekamp-Massey. Degree-ascending here: lambda[k] is the coefficient
3088
- // of x^k, which is how the recurrence is naturally stated.
3089
- const lambda = new Array(eccLen + 1).fill(0);
3090
- const prev = new Array(eccLen + 1).fill(0);
3091
- const tmp = new Array(eccLen + 1).fill(0);
3092
- lambda[0] = 1;
3093
- prev[0] = 1;
3094
- let errCount = 0; // current LFSR length
3095
- let shift = 1; // steps since `prev` was last updated
3096
- let lastDisc = 1; // discrepancy at that update
3097
-
3098
- for (let step = 0; step < eccLen; step++) {
3099
- let disc = syn[step];
3100
- for (let i = 1; i <= errCount; i++) {
3101
- disc = field.add(disc, field.mul(lambda[i], syn[step - i]));
3102
- }
3103
-
3104
- if (disc === 0) {
3105
- shift++;
3106
- continue;
3107
- }
3108
-
3109
- const scale = field.div(disc, lastDisc);
3110
- tmp.fill(0);
3111
- for (let i = 0; i <= eccLen; i++) tmp[i] = lambda[i];
3112
-
3113
- for (let i = 0; i + shift <= eccLen; i++) {
3114
- if (prev[i] === 0) continue;
3115
- lambda[i + shift] = field.sub(lambda[i + shift], field.mul(scale, prev[i]));
3116
- }
3117
-
3118
- if (2 * errCount <= step) {
3119
- errCount = step + 1 - errCount;
3120
- for (let i = 0; i <= eccLen; i++) prev[i] = tmp[i];
3121
- lastDisc = disc;
3122
- shift = 1;
3123
- } else {
3124
- shift++;
3125
- }
3126
- }
3127
-
3128
- if (errCount === 0 || errCount > eccLen / 2) {
3134
+ // Remove the known roots before locating unknown errors. The leading
3135
+ // erasureCount terms contain only the known-location transient and are not
3136
+ // part of the error-only recurrence.
3137
+ let erasureLocator = [1];
3138
+ for (const index of erasures) {
3139
+ const location = field.exp(n - 1 - index);
3140
+ erasureLocator = multiplyAscending(erasureLocator, [1, field.neg(location)], field, eccLen + 1);
3141
+ }
3142
+ const modified = multiplyAscending(syn, erasureLocator, field, eccLen).slice(erasures.length);
3143
+ const { locator: errorLocator, errorCount } = berlekampMassey(modified, field);
3144
+ if (2 * errorCount + erasures.length > eccLen) {
3129
3145
  throw new ChecksumError(
3130
- `Reed-Solomon: ${errCount} errors exceeds correction capacity ` +
3131
- `${Math.floor(eccLen / 2)} (${field.name})`
3146
+ `Reed-Solomon: ${errorCount} errors and ${erasures.length} erasures exceed correction capacity ` +
3147
+ `${eccLen} (${field.name})`
3132
3148
  );
3133
3149
  }
3150
+ const lambda = multiplyAscending(erasureLocator, errorLocator, field, eccLen + 1);
3151
+ const totalCount = errorCount + erasures.length;
3134
3152
 
3135
3153
  // --- Chien search. Position p (counted from the low-order end) is in error
3136
3154
  // when lambda(a^-p) == 0.
@@ -3139,16 +3157,16 @@ function rsDecode(received, eccLen, field, base = 0) {
3139
3157
  const xInv = field.exp(-p);
3140
3158
  let acc = 0;
3141
3159
  let term = 1;
3142
- for (let i = 0; i <= errCount; i++) {
3160
+ for (let i = 0; i <= totalCount; i++) {
3143
3161
  acc = field.add(acc, field.mul(lambda[i], term));
3144
3162
  term = field.mul(term, xInv);
3145
3163
  }
3146
3164
  if (acc === 0) positions.push(p);
3147
3165
  }
3148
3166
 
3149
- if (positions.length !== errCount) {
3167
+ if (positions.length !== totalCount) {
3150
3168
  throw new ChecksumError(
3151
- `Reed-Solomon: located ${positions.length} of ${errCount} error positions`
3169
+ `Reed-Solomon: located ${positions.length} of ${totalCount} error positions`
3152
3170
  );
3153
3171
  }
3154
3172
 
@@ -3157,7 +3175,7 @@ function rsDecode(received, eccLen, field, base = 0) {
3157
3175
  const omega = new Array(eccLen).fill(0);
3158
3176
  for (let i = 0; i < eccLen; i++) {
3159
3177
  let acc = 0;
3160
- for (let j = 0; j <= i && j <= errCount; j++) {
3178
+ for (let j = 0; j <= i && j <= totalCount; j++) {
3161
3179
  acc = field.add(acc, field.mul(lambda[j], syn[i - j]));
3162
3180
  }
3163
3181
  omega[i] = acc;
@@ -3181,7 +3199,7 @@ function rsDecode(received, eccLen, field, base = 0) {
3181
3199
  // in a prime field every term contributes with an integer multiplier.
3182
3200
  let den = 0;
3183
3201
  term = 1;
3184
- for (let i = 1; i <= errCount; i++) {
3202
+ for (let i = 1; i <= totalCount; i++) {
3185
3203
  if (field.prime) {
3186
3204
  // i * lambda[i] * x^(i-1), where `i` is repeated addition.
3187
3205
  let mult = 0;
@@ -7210,218 +7228,3244 @@ const __reexport3 = __require("qr/tables.js"); __exports.validateTables = __reex
7210
7228
 
7211
7229
  };
7212
7230
 
7213
- __modules["render/options.js"] = function (__require, __exports) {
7231
+ __modules["aztec/high-level.js"] = function (__require, __exports) {
7214
7232
  /**
7215
- * Shared render options, normalised once so every backend agrees.
7233
+ * Aztec high-level stream writer.
7216
7234
  *
7217
- * @module render/options
7235
+ * The output is deliberately a `BitWriter`, rather than a byte array: Aztec's
7236
+ * text controls and binary-shift lengths are not byte aligned. This module is
7237
+ * also the boundary where JavaScript strings become UTF-8. Passing a byte
7238
+ * view bypasses that conversion and preserves every octet unchanged.
7239
+ *
7240
+ * The initial state mandated by the symbology is UPPER. The greedy text pass
7241
+ * uses UPPER, LOWER, DIGIT and PUNCT tables, selecting the shortest available
7242
+ * latch at each byte. Bytes without a text-table representation are emitted
7243
+ * through the standard B/S (binary shift) escape. B/S is available from
7244
+ * UPPER and makes this a complete, lossless representation of UTF-8 payloads.
7245
+ *
7246
+ * @module aztec/high-level
7218
7247
  */
7219
- const { BitMatrix } = __require("core/bit-matrix.js");
7248
+ const { BitWriter } = __require("core/bit-buffer.js");
7249
+ const { EncodeError } = __require("core/errors.js");
7220
7250
 
7221
- /**
7222
- * @typedef {object} RenderOptions
7223
- * @property {number} [scale] Pixels per module. Default 8.
7224
- * @property {number} [margin] Quiet-zone modules on every side. Default 4.
7225
- * @property {string} [dark] Colour of set modules. Default '#000000'.
7226
- * @property {string} [light] Colour of clear modules, or 'none' for transparent.
7227
- * @property {number} [barHeight] For 1D symbols: total bar height in pixels.
7228
- */
7251
+ /** Aztec high-level table identifiers, exposed for decoder/API symmetry. */
7252
+ const HIGH_LEVEL_MODE = Object.freeze({
7253
+ UPPER: 0,
7254
+ LOWER: 1,
7255
+ DIGIT: 2,
7256
+ MIXED: 3,
7257
+ PUNCT: 4,
7258
+ });
7259
+
7260
+ /** Maximum number of bytes represented by one B/S escape. */
7261
+ const MAX_BINARY_SHIFT = 2078;
7229
7262
 
7230
7263
  /**
7231
- * Expand and pad the matrix, and resolve every dimension.
7232
- *
7233
- * Linear symbols arrive one module tall. They are stretched to `barHeight`
7234
- * *before* the quiet zone is applied, so the margin ends up uniform on all
7235
- * four sides — padding first would leave a quiet zone one module tall against
7236
- * bars a hundred pixels tall, which no scanner would accept.
7264
+ * Convert accepted public input to its encoded octets.
7237
7265
  *
7238
- * @param {BitMatrix} matrix
7239
- * @param {RenderOptions} options
7266
+ * @param {string|ArrayBuffer|ArrayBufferView} value
7267
+ * @param {'utf-8'} [charset]
7268
+ * @returns {Uint8Array}
7240
7269
  */
7241
- function normalizeOptions(matrix, options = {}) {
7242
- const scale = Math.max(1, Math.floor(options.scale ?? 8));
7243
- const margin = Math.max(0, Math.floor(options.margin ?? 4));
7244
- const dark = options.dark ?? '#000000';
7245
- const light = options.light ?? '#ffffff';
7246
- const barHeight = options.barHeight ?? null;
7270
+ function aztecBytes(value, charset = 'utf-8') {
7271
+ if (charset !== 'utf-8') throw new EncodeError(`Aztec: unsupported charset "${charset}"`);
7272
+ if (typeof value === 'string') return new TextEncoder().encode(value);
7273
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
7274
+ if (ArrayBuffer.isView(value)) {
7275
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
7276
+ }
7277
+ throw new EncodeError('Aztec: value must be a string, ArrayBuffer, or byte view');
7278
+ }
7247
7279
 
7248
- let base = matrix;
7249
- const is1D = matrix.height === 1;
7280
+ /** @param {number} byte @returns {number} UPPER-table value, or -1. */
7281
+ function upperValue(byte) {
7282
+ if (byte === 0x20) return 1;
7283
+ if (byte >= 0x41 && byte <= 0x5a) return byte - 0x41 + 2;
7284
+ return -1;
7285
+ }
7250
7286
 
7251
- if (is1D) {
7252
- // Default to a bar height that stays scannable: tall enough that a laser
7253
- // crossing at a slight angle still passes through the whole symbol.
7254
- const targetPixels = barHeight ?? Math.max(40, Math.round(matrix.width * scale * 0.15));
7255
- const rows = Math.max(1, Math.round(targetPixels / scale));
7256
- base = new BitMatrix(matrix.width, rows);
7257
- for (let x = 0; x < matrix.width; x++) {
7258
- if (!matrix.get(x, 0)) continue;
7259
- for (let y = 0; y < rows; y++) base.set(x, y);
7260
- }
7287
+ /** Aztec's latch table, packed as `(bitCount << 16) | bits`. */
7288
+ const LATCH = Object.freeze([
7289
+ [0, 327708, 327710, 327709, 656318],
7290
+ [590318, 0, 327710, 327709, 656318],
7291
+ [262158, 590300, 0, 590301, 932798],
7292
+ [327709, 327708, 656322, 0, 327710],
7293
+ [327711, 656380, 656382, 656381, 0],
7294
+ ]);
7295
+
7296
+ /** @param {number} byte @returns {number} */
7297
+ function lowerValue(byte) {
7298
+ if (byte === 0x20) return 1;
7299
+ if (byte >= 0x61 && byte <= 0x7a) return byte - 0x61 + 2;
7300
+ return -1;
7301
+ }
7302
+
7303
+ /** @param {number} byte @returns {number} */
7304
+ function digitValue(byte) {
7305
+ if (byte === 0x20) return 1;
7306
+ if (byte >= 0x30 && byte <= 0x39) return byte - 0x30 + 2;
7307
+ if (byte === 0x2c) return 12;
7308
+ if (byte === 0x2e) return 13;
7309
+ return -1;
7310
+ }
7311
+
7312
+ const PUNCT = new Map([
7313
+ [0x0d, 1], [0x21, 6], [0x22, 7], [0x23, 8], [0x24, 9], [0x25, 10],
7314
+ [0x26, 11], [0x27, 12], [0x28, 13], [0x29, 14], [0x2a, 15], [0x2b, 16],
7315
+ [0x2c, 17], [0x2d, 18], [0x2e, 19], [0x2f, 20], [0x3a, 21], [0x3b, 22],
7316
+ [0x3c, 23], [0x3d, 24], [0x3e, 25], [0x3f, 26], [0x5b, 27], [0x5d, 28],
7317
+ [0x7b, 29], [0x7d, 30],
7318
+ ]);
7319
+
7320
+ /** @param {number} byte @param {number} mode @returns {number} */
7321
+ function textValue(byte, mode) {
7322
+ switch (mode) {
7323
+ case HIGH_LEVEL_MODE.UPPER: return upperValue(byte);
7324
+ case HIGH_LEVEL_MODE.LOWER: return lowerValue(byte);
7325
+ case HIGH_LEVEL_MODE.DIGIT: return digitValue(byte);
7326
+ case HIGH_LEVEL_MODE.PUNCT: return PUNCT.get(byte) ?? -1;
7327
+ default: return -1;
7261
7328
  }
7329
+ }
7262
7330
 
7263
- const source = margin > 0 ? base.withMargin(margin) : base;
7331
+ /** @param {BitWriter} writer @param {number} from @param {number} to */
7332
+ function latch(writer, from, to) {
7333
+ if (from === to) return;
7334
+ const packed = LATCH[from][to];
7335
+ writer.put(packed & 0xffff, packed >>> 16);
7336
+ }
7264
7337
 
7265
- return {
7266
- scale,
7267
- margin,
7268
- dark,
7269
- light,
7270
- is1D,
7271
- source,
7272
- rowHeight: scale,
7273
- pixelWidth: source.width * scale,
7274
- pixelHeight: source.height * scale,
7275
- };
7338
+ /** @param {number} mode @returns {number} */
7339
+ function characterWidth(mode) {
7340
+ return mode === HIGH_LEVEL_MODE.DIGIT ? 4 : 5;
7276
7341
  }
7277
7342
 
7278
7343
  /**
7279
- * Parse a CSS colour into RGBA bytes.
7344
+ * Write an Aztec binary-shift segment while in UPPER mode.
7280
7345
  *
7281
- * Supports the forms a barcode actually needs: #rgb, #rgba, #rrggbb,
7282
- * #rrggbbaa, rgb(), rgba(), plus 'none' and 'transparent'.
7346
+ * B/S is `11111`; its five-bit length directly covers 1..31 bytes. A zero
7347
+ * length selects the extended eleven-bit form, whose stored value is n - 31.
7348
+ * Splitting at 2078 keeps each control representable and makes arbitrarily
7349
+ * long byte input well-defined.
7283
7350
  *
7284
- * @param {string} colour
7285
- * @returns {[number, number, number, number]}
7351
+ * @param {BitWriter} writer
7352
+ * @param {Uint8Array} bytes
7353
+ * @param {number} start
7354
+ * @param {number} length
7286
7355
  */
7287
- function parseColor(colour) {
7288
- const value = String(colour).trim().toLowerCase();
7289
-
7290
- if (value === 'none' || value === 'transparent') return [0, 0, 0, 0];
7291
- if (value === 'white') return [255, 255, 255, 255];
7292
- if (value === 'black') return [0, 0, 0, 255];
7293
-
7294
- if (value[0] === '#') {
7295
- const hex = value.slice(1);
7296
- const expand = (c) => parseInt(c + c, 16);
7297
- if (hex.length === 3) {
7298
- return [expand(hex[0]), expand(hex[1]), expand(hex[2]), 255];
7299
- }
7300
- if (hex.length === 4) {
7301
- return [expand(hex[0]), expand(hex[1]), expand(hex[2]), expand(hex[3])];
7302
- }
7303
- if (hex.length === 6) {
7304
- return [
7305
- parseInt(hex.slice(0, 2), 16),
7306
- parseInt(hex.slice(2, 4), 16),
7307
- parseInt(hex.slice(4, 6), 16),
7308
- 255,
7309
- ];
7310
- }
7311
- if (hex.length === 8) {
7312
- return [
7313
- parseInt(hex.slice(0, 2), 16),
7314
- parseInt(hex.slice(2, 4), 16),
7315
- parseInt(hex.slice(4, 6), 16),
7316
- parseInt(hex.slice(6, 8), 16),
7317
- ];
7356
+ function writeBinaryShift(writer, bytes, start, length) {
7357
+ let at = start;
7358
+ let left = length;
7359
+ while (left > 0) {
7360
+ const count = Math.min(left, MAX_BINARY_SHIFT);
7361
+ writer.put(31, 5); // UPPER B/S
7362
+ if (count <= 31) writer.put(count, 5);
7363
+ else {
7364
+ writer.put(0, 5);
7365
+ writer.put(count - 31, 11);
7318
7366
  }
7367
+ for (let i = 0; i < count; i++) writer.put(bytes[at + i], 8);
7368
+ at += count;
7369
+ left -= count;
7319
7370
  }
7371
+ }
7320
7372
 
7321
- const fn = value.match(/^rgba?\(([^)]+)\)$/);
7322
- if (fn) {
7323
- const parts = fn[1].split(/[,/\s]+/).filter(Boolean);
7324
- const channel = (s) => (s.endsWith('%')
7325
- ? Math.round((parseFloat(s) / 100) * 255)
7326
- : Math.round(parseFloat(s)));
7327
- const r = channel(parts[0]);
7328
- const g = channel(parts[1]);
7329
- const b = channel(parts[2]);
7330
- let a = 255;
7331
- if (parts.length > 3) {
7332
- a = parts[3].endsWith('%')
7333
- ? Math.round((parseFloat(parts[3]) / 100) * 255)
7334
- : Math.round(parseFloat(parts[3]) * 255);
7373
+ /**
7374
+ * Build a valid Aztec high-level bitstream.
7375
+ *
7376
+ * @param {string|ArrayBuffer|ArrayBufferView} value
7377
+ * @param {{charset?: 'utf-8'}} [options]
7378
+ * @returns {BitWriter}
7379
+ */
7380
+ function encodeHighLevel(value, options = {}) {
7381
+ const bytes = aztecBytes(value, options.charset ?? 'utf-8');
7382
+ const writer = new BitWriter();
7383
+ let mode = HIGH_LEVEL_MODE.UPPER;
7384
+
7385
+ for (let at = 0; at < bytes.length;) {
7386
+ let bestMode = -1;
7387
+ let bestValue = -1;
7388
+ let bestCost = Number.POSITIVE_INFINITY;
7389
+ for (const candidate of [HIGH_LEVEL_MODE.UPPER, HIGH_LEVEL_MODE.LOWER, HIGH_LEVEL_MODE.DIGIT, HIGH_LEVEL_MODE.PUNCT]) {
7390
+ const value = textValue(bytes[at], candidate);
7391
+ if (value < 0) continue;
7392
+ const latchCost = candidate === mode ? 0 : LATCH[mode][candidate] >>> 16;
7393
+ const cost = latchCost + characterWidth(candidate);
7394
+ if (cost < bestCost) { bestCost = cost; bestMode = candidate; bestValue = value; }
7395
+ }
7396
+ if (bestMode >= 0) {
7397
+ latch(writer, mode, bestMode);
7398
+ writer.put(bestValue, characterWidth(bestMode));
7399
+ mode = bestMode;
7400
+ at++;
7401
+ } else {
7402
+ // B/S is defined from UPPER; the latch is retained after the shift.
7403
+ latch(writer, mode, HIGH_LEVEL_MODE.UPPER);
7404
+ mode = HIGH_LEVEL_MODE.UPPER;
7405
+ const start = at;
7406
+ while (at < bytes.length && ![HIGH_LEVEL_MODE.UPPER, HIGH_LEVEL_MODE.LOWER, HIGH_LEVEL_MODE.DIGIT, HIGH_LEVEL_MODE.PUNCT].some((m) => textValue(bytes[at], m) >= 0)) at++;
7407
+ writeBinaryShift(writer, bytes, start, at - start);
7335
7408
  }
7336
- return [r, g, b, a];
7337
7409
  }
7338
-
7339
- // Unrecognised: fall back to opaque black rather than throwing, so an
7340
- // unusual colour never costs someone a barcode.
7341
- return [0, 0, 0, 255];
7410
+ return writer;
7342
7411
  }
7343
7412
 
7344
- __exports.normalizeOptions = normalizeOptions;
7345
- __exports.parseColor = parseColor;
7413
+ __exports.HIGH_LEVEL_MODE = HIGH_LEVEL_MODE;
7414
+ __exports.MAX_BINARY_SHIFT = MAX_BINARY_SHIFT;
7415
+ __exports.aztecBytes = aztecBytes;
7416
+ __exports.writeBinaryShift = writeBinaryShift;
7417
+ __exports.encodeHighLevel = encodeHighLevel;
7346
7418
  };
7347
7419
 
7348
- __modules["render/svg.js"] = function (__require, __exports) {
7420
+ __modules["aztec/tables.js"] = function (__require, __exports) {
7349
7421
  /**
7350
- * SVG output.
7422
+ * Aztec Code layer geometry and Reed-Solomon parameters.
7351
7423
  *
7352
- * Dark modules are emitted as a single `<path>` with horizontal runs merged,
7353
- * not as one `<rect>` per module. A version 40 QR symbol has 31329 modules; the
7354
- * naive rendering is a megabyte of XML that browsers choke on, while the merged
7355
- * path is a few kilobytes and draws identically.
7424
+ * `totalBits` counts the payload ring before its leading pad bits are added;
7425
+ * consequently only `usableBits` can be partitioned into codewords. Compact
7426
+ * symbols have no reference grid. Full symbols insert alternating reference
7427
+ * rows and columns every 16 modules around the centre.
7356
7428
  *
7357
- * @module render/svg
7429
+ * The five data fields use generator base 1. GF(256)/DataMatrix is also the
7430
+ * Aztec 8-bit field: both use primitive polynomial 0x12d.
7431
+ *
7432
+ * @module aztec/tables
7358
7433
  */
7359
- const { normalizeOptions } = __require("render/options.js");
7434
+ const { GF16, GF64, GF256_AZTEC, GF1024, GF4096 } = __require("core/galois-field.js");
7435
+
7436
+ /** Reed-Solomon generator base defined for Aztec parameter and data fields. */
7437
+ const AZTEC_RS_GENERATOR_BASE = 1;
7438
+
7439
+ /** Minimum recommended error correction: 23 percent plus three codewords. */
7440
+ const AZTEC_DEFAULT_ECC_PERCENT = 23;
7441
+ const AZTEC_MIN_ECC_WORDS = 3;
7442
+
7443
+ /** Word size selected solely by the number of layers. */
7444
+ function wordSizeForLayers(layers) {
7445
+ if (!Number.isInteger(layers) || layers < 1 || layers > 32) {
7446
+ throw new RangeError(`Aztec: layers must be an integer from 1 to 32 (got ${layers})`);
7447
+ }
7448
+ if (layers <= 2) return 6;
7449
+ if (layers <= 8) return 8;
7450
+ if (layers <= 22) return 10;
7451
+ return 12;
7452
+ }
7453
+
7454
+ /** Return the field used by Aztec codewords of `wordSize` bits. */
7455
+ function fieldForWordSize(wordSize) {
7456
+ switch (wordSize) {
7457
+ case 4: return GF16; // Mode message only.
7458
+ case 6: return GF64;
7459
+ case 8: return GF256_AZTEC;
7460
+ case 10: return GF1024;
7461
+ case 12: return GF4096;
7462
+ default: throw new RangeError(`Aztec: unsupported codeword size ${wordSize}`);
7463
+ }
7464
+ }
7465
+
7466
+ /** Return the data field selected for a symbol with `layers` layers. */
7467
+ function fieldForLayers(layers) {
7468
+ return fieldForWordSize(wordSizeForLayers(layers));
7469
+ }
7470
+
7471
+ /** Matrix side length, including Full-mode reference grid lines. */
7472
+ function aztecSymbolSize(layers, compact = false) {
7473
+ if (!Number.isInteger(layers) || layers < 1 || layers > (compact ? 4 : 32)) {
7474
+ throw new RangeError(`Aztec: ${compact ? 'Compact' : 'Full'} layers out of range: ${layers}`);
7475
+ }
7476
+ if (compact) return 11 + 4 * layers;
7477
+ const baseMatrixSize = 14 + 4 * layers;
7478
+ return baseMatrixSize + 1 + 2 * Math.floor((baseMatrixSize / 2 - 1) / 15);
7479
+ }
7480
+
7481
+ function layer(layers, compact) {
7482
+ const wordSize = wordSizeForLayers(layers);
7483
+ const totalBits = ((compact ? 88 : 112) + 16 * layers) * layers;
7484
+ const usableBits = totalBits - totalBits % wordSize;
7485
+ const totalCodewords = usableBits / wordSize;
7486
+ const baseMatrixSize = (compact ? 11 : 14) + 4 * layers;
7487
+ return Object.freeze({
7488
+ compact,
7489
+ layers,
7490
+ wordSize,
7491
+ totalBits,
7492
+ usableBits,
7493
+ totalCodewords,
7494
+ // Compact mode encodes the count in six bits and can therefore hold no
7495
+ // more than 64 data codewords even where the ring itself is larger.
7496
+ maxDataCodewords: compact ? Math.min(totalCodewords, 64) : totalCodewords,
7497
+ baseMatrixSize,
7498
+ symbolSize: aztecSymbolSize(layers, compact),
7499
+ modeMessageDataWords: compact ? 2 : 4,
7500
+ modeMessageWords: compact ? 7 : 10,
7501
+ modeMessageBits: compact ? 28 : 40,
7502
+ rsGeneratorBase: AZTEC_RS_GENERATOR_BASE,
7503
+ });
7504
+ }
7505
+
7506
+ /** Compact Aztec layers 1 through 4, in encoding preference order. */
7507
+ const AZTEC_COMPACT_LAYERS = Object.freeze(
7508
+ Array.from({ length: 4 }, (_, i) => layer(i + 1, true)),
7509
+ );
7510
+
7511
+ /** Full Aztec layers 1 through 32, in ascending layer order. */
7512
+ const AZTEC_FULL_LAYERS = Object.freeze(
7513
+ Array.from({ length: 32 }, (_, i) => layer(i + 1, false)),
7514
+ );
7515
+
7516
+ /** All allowed symbols. Compact entries precede Full entries for automatic selection. */
7517
+ const AZTEC_LAYERS = Object.freeze([
7518
+ ...AZTEC_COMPACT_LAYERS,
7519
+ ...AZTEC_FULL_LAYERS,
7520
+ ]);
7521
+
7522
+ /** Return one immutable layer record. */
7523
+ function aztecLayer(layers, compact = false) {
7524
+ if (!Number.isInteger(layers) || layers < 1 || layers > (compact ? 4 : 32)) {
7525
+ throw new RangeError(`Aztec: ${compact ? 'Compact' : 'Full'} layers out of range: ${layers}`);
7526
+ }
7527
+ return (compact ? AZTEC_COMPACT_LAYERS : AZTEC_FULL_LAYERS)[layers - 1];
7528
+ }
7360
7529
 
7361
7530
  /**
7362
- * @param {string} value
7363
- * @returns {string}
7531
+ * Calculate the minimum parity count for a data word count.
7532
+ *
7533
+ * The percentage is rounded up because a fractional codeword cannot be
7534
+ * emitted. The mandatory three words protect short payloads, where a bare
7535
+ * percentage would otherwise round to zero.
7364
7536
  */
7365
- function escapeAttr(value) {
7366
- return String(value)
7367
- .replace(/&/g, '&amp;')
7368
- .replace(/</g, '&lt;')
7369
- .replace(/>/g, '&gt;')
7370
- .replace(/"/g, '&quot;');
7537
+ function eccCodewordsFor(dataCodewords, eccPercent = AZTEC_DEFAULT_ECC_PERCENT) {
7538
+ if (!Number.isInteger(dataCodewords) || dataCodewords < 0) {
7539
+ throw new RangeError(`Aztec: data codewords must be a non-negative integer (got ${dataCodewords})`);
7540
+ }
7541
+ if (!Number.isFinite(eccPercent) || eccPercent < 0 || eccPercent > 100) {
7542
+ throw new RangeError(`Aztec: ECC percent must be between 0 and 100 (got ${eccPercent})`);
7543
+ }
7544
+ return Math.ceil(dataCodewords * eccPercent / 100) + AZTEC_MIN_ECC_WORDS;
7371
7545
  }
7372
7546
 
7373
7547
  /**
7374
- * Render to an SVG document.
7548
+ * Choose the first symbol which holds an already stuffed payload.
7375
7549
  *
7376
- * @param {import('../core/bit-matrix.js').BitMatrix} matrix
7377
- * @param {import('./options.js').RenderOptions} [options]
7378
- * @returns {string}
7550
+ * `dataBits` must be a multiple of the candidate word size; callers which
7551
+ * start from high-level bits must stuff separately per candidate word size.
7379
7552
  */
7380
- function toSVG(matrix, options = {}) {
7381
- const opts = normalizeOptions(matrix, options);
7382
- const { scale, source, pixelWidth, pixelHeight, rowHeight } = opts;
7553
+ function selectAztecLayer(dataBits, {
7554
+ eccPercent = AZTEC_DEFAULT_ECC_PERCENT,
7555
+ layers = null,
7556
+ compact = null,
7557
+ } = {}) {
7558
+ if (!Number.isInteger(dataBits) || dataBits < 0) {
7559
+ throw new RangeError(`Aztec: data bits must be a non-negative integer (got ${dataBits})`);
7560
+ }
7561
+ if (compact !== null && typeof compact !== 'boolean') {
7562
+ throw new TypeError('Aztec: compact must be true, false or null');
7563
+ }
7383
7564
 
7384
- let path = '';
7385
- for (let y = 0; y < source.height; y++) {
7386
- let x = 0;
7387
- while (x < source.width) {
7388
- if (!source.get(x, y)) { x++; continue; }
7389
- let run = 1;
7390
- while (x + run < source.width && source.get(x + run, y)) run++;
7391
- // Relative horizontal-vertical path commands: shorter than rects and
7392
- // free of the seams that appear between adjacent rects at some zooms.
7393
- path += `M${x * scale} ${y * rowHeight}h${run * scale}v${rowHeight}h${-run * scale}z`;
7394
- x += run;
7565
+ let candidates;
7566
+ if (layers !== null) {
7567
+ if (compact === null) throw new TypeError('Aztec: compact must be specified when layers is specified');
7568
+ candidates = [aztecLayer(layers, compact)];
7569
+ } else if (compact === null) {
7570
+ candidates = AZTEC_LAYERS;
7571
+ } else {
7572
+ candidates = compact ? AZTEC_COMPACT_LAYERS : AZTEC_FULL_LAYERS;
7573
+ }
7574
+
7575
+ for (const candidate of candidates) {
7576
+ if (dataBits % candidate.wordSize !== 0) continue;
7577
+ const dataCodewords = dataBits / candidate.wordSize;
7578
+ const eccCodewords = eccCodewordsFor(dataCodewords, eccPercent);
7579
+ if (dataCodewords <= candidate.maxDataCodewords &&
7580
+ dataCodewords + eccCodewords <= candidate.totalCodewords) {
7581
+ return Object.freeze({ ...candidate, dataCodewords, eccCodewords });
7395
7582
  }
7396
7583
  }
7397
7584
 
7398
- const bg = opts.light === 'none'
7399
- ? ''
7400
- : `<rect width="${pixelWidth}" height="${pixelHeight}" fill="${escapeAttr(opts.light)}"/>`;
7585
+ throw new RangeError('Aztec: payload and requested error correction do not fit an available symbol');
7586
+ }
7401
7587
 
7402
- return `<svg xmlns="http://www.w3.org/2000/svg" width="${pixelWidth}" height="${pixelHeight}" ` +
7403
- `viewBox="0 0 ${pixelWidth} ${pixelHeight}" shape-rendering="crispEdges">` +
7404
- bg +
7405
- `<path d="${path}" fill="${escapeAttr(opts.dark)}"/>` +
7406
- '</svg>';
7588
+ /** Check static identities so table corruption fails explicitly in tests. */
7589
+ function validateAztecTables() {
7590
+ const issues = [];
7591
+ for (const entry of AZTEC_LAYERS) {
7592
+ if (entry.usableBits % entry.wordSize !== 0) issues.push(`${entry.compact ? 'C' : 'F'}${entry.layers}: unaligned usable bits`);
7593
+ if (entry.totalCodewords !== entry.usableBits / entry.wordSize) issues.push(`${entry.compact ? 'C' : 'F'}${entry.layers}: codeword mismatch`);
7594
+ if (entry.symbolSize !== aztecSymbolSize(entry.layers, entry.compact)) issues.push(`${entry.compact ? 'C' : 'F'}${entry.layers}: matrix size mismatch`);
7595
+ if (entry.rsGeneratorBase !== AZTEC_RS_GENERATOR_BASE) issues.push(`${entry.compact ? 'C' : 'F'}${entry.layers}: generator base mismatch`);
7596
+ if (entry.compact && entry.maxDataCodewords > 64) issues.push(`C${entry.layers}: Compact data-word limit exceeded`);
7597
+ }
7598
+ return issues;
7407
7599
  }
7408
7600
 
7601
+ __exports.AZTEC_RS_GENERATOR_BASE = AZTEC_RS_GENERATOR_BASE;
7602
+ __exports.AZTEC_DEFAULT_ECC_PERCENT = AZTEC_DEFAULT_ECC_PERCENT;
7603
+ __exports.AZTEC_MIN_ECC_WORDS = AZTEC_MIN_ECC_WORDS;
7604
+ __exports.wordSizeForLayers = wordSizeForLayers;
7605
+ __exports.fieldForWordSize = fieldForWordSize;
7606
+ __exports.fieldForLayers = fieldForLayers;
7607
+ __exports.aztecSymbolSize = aztecSymbolSize;
7608
+ __exports.AZTEC_COMPACT_LAYERS = AZTEC_COMPACT_LAYERS;
7609
+ __exports.AZTEC_FULL_LAYERS = AZTEC_FULL_LAYERS;
7610
+ __exports.AZTEC_LAYERS = AZTEC_LAYERS;
7611
+ __exports.aztecLayer = aztecLayer;
7612
+ __exports.eccCodewordsFor = eccCodewordsFor;
7613
+ __exports.selectAztecLayer = selectAztecLayer;
7614
+ __exports.validateAztecTables = validateAztecTables;
7615
+ };
7616
+
7617
+ __modules["aztec/encoder.js"] = function (__require, __exports) {
7409
7618
  /**
7410
- * Base64 that works identically in Node and the browser.
7619
+ * Aztec encoder: high-level bits, bit stuffing, Reed-Solomon and matrix layout.
7411
7620
  *
7412
- * `btoa` is byte-oriented, so the UTF-8 encoding has to happen first — passing
7413
- * it a string with any character above U+00FF throws.
7621
+ * `tables.js` is intentionally the source of geometry and field selection.
7622
+ * Its `aztecLayer(layers, compact)` entries must expose `totalBits`,
7623
+ * `totalCodewords`, `baseMatrixSize` and `symbolSize`; `fieldForLayers()` must
7624
+ * return the matching binary field. All Aztec Reed-Solomon generators start
7625
+ * at alpha^1, hence the explicit base `1` in both data and mode messages.
7414
7626
  *
7415
- * @param {string} text
7416
- * @returns {string}
7627
+ * @module aztec/encoder
7417
7628
  */
7418
- function toBase64(text) {
7419
- const bytes = new TextEncoder().encode(text);
7420
- let binary = '';
7421
- for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
7422
- if (typeof btoa === 'function') return btoa(binary);
7423
- // Node before btoa was global, and non-browser embedders.
7424
- /* eslint-disable-next-line no-undef */
7629
+ const { BitWriter } = __require("core/bit-buffer.js");
7630
+ const { BitMatrix } = __require("core/bit-matrix.js");
7631
+ const { EncodeError } = __require("core/errors.js");
7632
+ const { rsEncode } = __require("core/reed-solomon.js");
7633
+ const { encodeHighLevel } = __require("aztec/high-level.js");
7634
+ const { AZTEC_COMPACT_LAYERS, AZTEC_FULL_LAYERS, aztecLayer, eccCodewordsFor, fieldForLayers, fieldForWordSize, wordSizeForLayers } = __require("aztec/tables.js");
7635
+
7636
+ /** @param {BitWriter} bits @param {number} at @returns {boolean} */
7637
+ function bitAt(bits, at) {
7638
+ return at >= 0 && at < bits.length && ((bits.bytes[at >>> 3] >>> (7 - (at & 7))) & 1) !== 0;
7639
+ }
7640
+
7641
+ /** @param {BitWriter} bits @param {number} from @param {number} count @returns {number} */
7642
+ function readBits(bits, from, count) {
7643
+ let value = 0;
7644
+ for (let i = 0; i < count; i++) value = (value << 1) | (bitAt(bits, from + i) ? 1 : 0);
7645
+ return value;
7646
+ }
7647
+
7648
+ /**
7649
+ * Prevent all-zero and all-one codewords except their final bit. The final
7650
+ * bit is intentionally re-consumed after a stuffed word; it is the mechanism
7651
+ * that makes the transform injective and reversible.
7652
+ *
7653
+ * @param {BitWriter} bits @param {number} wordSize @returns {BitWriter}
7654
+ */
7655
+ function stuffBits(bits, wordSize) {
7656
+ const out = new BitWriter();
7657
+ const reserved = (1 << wordSize) - 2;
7658
+ for (let at = 0; at < bits.length; at += wordSize) {
7659
+ const word = readBits(bits, at, wordSize);
7660
+ if ((word & reserved) === reserved) {
7661
+ out.put(word & reserved, wordSize);
7662
+ at--;
7663
+ } else if ((word & reserved) === 0) {
7664
+ out.put(word | 1, wordSize);
7665
+ at--;
7666
+ } else {
7667
+ out.put(word, wordSize);
7668
+ }
7669
+ }
7670
+ return out;
7671
+ }
7672
+
7673
+ /**
7674
+ * Add systematic Aztec Reed-Solomon parity and the leading alignment bits.
7675
+ * @param {BitWriter} data @param {number} totalBits @param {number} wordSize
7676
+ * @param {import('../core/galois-field.js').GaloisField} field
7677
+ * @returns {{bits: BitWriter, dataWords: number, eccWords: number}}
7678
+ */
7679
+ function addCheckWords(data, totalBits, wordSize, field) {
7680
+ const totalWords = Math.floor(totalBits / wordSize);
7681
+ const dataWords = Math.ceil(data.length / wordSize);
7682
+ if (dataWords > totalWords) throw new EncodeError('Aztec: data codewords exceed layer capacity');
7683
+ const eccWords = totalWords - dataWords;
7684
+ const words = new Array(dataWords);
7685
+ for (let i = 0; i < dataWords; i++) words[i] = readBits(data, i * wordSize, wordSize);
7686
+ const ecc = rsEncode(words, eccWords, field, 1);
7687
+ const out = new BitWriter();
7688
+ out.put(0, totalBits % wordSize);
7689
+ for (const word of words) out.put(word, wordSize);
7690
+ for (const word of ecc) out.put(word, wordSize);
7691
+ return { bits: out, dataWords, eccWords };
7692
+ }
7693
+
7694
+ /** @param {number} layers @param {number} dataWords @param {boolean} compact @returns {BitWriter} */
7695
+ function modeMessage(layers, dataWords, compact) {
7696
+ const raw = new BitWriter();
7697
+ if (compact) {
7698
+ raw.put(layers - 1, 2);
7699
+ raw.put(dataWords - 1, 6);
7700
+ return addCheckWords(raw, 28, 4, fieldForWordSize(4)).bits;
7701
+ }
7702
+ raw.put(layers - 1, 5);
7703
+ raw.put(dataWords - 1, 11);
7704
+ return addCheckWords(raw, 40, 4, fieldForWordSize(4)).bits;
7705
+ }
7706
+
7707
+ /** @param {BitMatrix} matrix @param {number} center @param {number} size */
7708
+ function drawBullsEye(matrix, center, size) {
7709
+ for (let ring = 0; ring < size; ring += 2) {
7710
+ for (let p = center - ring; p <= center + ring; p++) {
7711
+ matrix.set(p, center - ring); matrix.set(p, center + ring);
7712
+ matrix.set(center - ring, p); matrix.set(center + ring, p);
7713
+ }
7714
+ }
7715
+ matrix.set(center - size, center - size);
7716
+ matrix.set(center - size + 1, center - size);
7717
+ matrix.set(center - size, center - size + 1);
7718
+ matrix.set(center + size, center - size);
7719
+ matrix.set(center + size, center - size + 1);
7720
+ matrix.set(center + size, center + size - 1);
7721
+ }
7722
+
7723
+ /** @param {BitMatrix} matrix @param {BitWriter} message @param {boolean} compact @param {number} center */
7724
+ function drawModeMessage(matrix, message, compact, center) {
7725
+ if (compact) {
7726
+ for (let i = 0; i < 7; i++) {
7727
+ const offset = center - 3 + i;
7728
+ if (bitAt(message, i)) matrix.set(offset, center - 5);
7729
+ if (bitAt(message, i + 7)) matrix.set(center + 5, offset);
7730
+ if (bitAt(message, 20 - i)) matrix.set(offset, center + 5);
7731
+ if (bitAt(message, 27 - i)) matrix.set(center - 5, offset);
7732
+ }
7733
+ } else {
7734
+ for (let i = 0; i < 10; i++) {
7735
+ const offset = center - 5 + i + Math.floor(i / 5);
7736
+ if (bitAt(message, i)) matrix.set(offset, center - 7);
7737
+ if (bitAt(message, i + 10)) matrix.set(center + 7, offset);
7738
+ if (bitAt(message, 29 - i)) matrix.set(offset, center + 7);
7739
+ if (bitAt(message, 39 - i)) matrix.set(center - 7, offset);
7740
+ }
7741
+ }
7742
+ }
7743
+
7744
+ /**
7745
+ * Lay low-level bits in the four-sided, inward Aztec spiral.
7746
+ * @param {BitWriter} bits @param {{layers:number,compact:boolean,baseMatrixSize:number,symbolSize:number}} symbol
7747
+ * @returns {BitMatrix}
7748
+ */
7749
+ function buildAztecMatrix(bits, symbol) {
7750
+ const { layers, compact, baseMatrixSize, symbolSize } = symbol;
7751
+ const matrix = new BitMatrix(symbolSize);
7752
+ const alignment = new Int32Array(baseMatrixSize);
7753
+ const center = Math.floor(symbolSize / 2);
7754
+
7755
+ if (compact) {
7756
+ for (let i = 0; i < baseMatrixSize; i++) alignment[i] = i;
7757
+ } else {
7758
+ const originalCenter = Math.floor(baseMatrixSize / 2);
7759
+ for (let i = 0; i < originalCenter; i++) {
7760
+ const offset = i + Math.floor(i / 15);
7761
+ alignment[originalCenter - i - 1] = center - offset - 1;
7762
+ alignment[originalCenter + i] = center + offset + 1;
7763
+ }
7764
+ }
7765
+
7766
+ let bit = 0;
7767
+ for (let layer = 0; layer < layers; layer++) {
7768
+ const rowSize = (layers - layer) * 4 + (compact ? 9 : 12);
7769
+ const low = layer * 2;
7770
+ const high = baseMatrixSize - 1 - low;
7771
+ for (let j = 0; j < rowSize; j++) {
7772
+ const offset = j * 2;
7773
+ for (let k = 0; k < 2; k++) {
7774
+ if (bitAt(bits, bit + offset + k)) matrix.set(alignment[low + k], alignment[low + j]);
7775
+ if (bitAt(bits, bit + rowSize * 2 + offset + k)) matrix.set(alignment[low + j], alignment[high - k]);
7776
+ if (bitAt(bits, bit + rowSize * 4 + offset + k)) matrix.set(alignment[high - k], alignment[high - j]);
7777
+ if (bitAt(bits, bit + rowSize * 6 + offset + k)) matrix.set(alignment[high - j], alignment[low + k]);
7778
+ }
7779
+ }
7780
+ bit += rowSize * 8;
7781
+ }
7782
+ if (bit !== bits.length) throw new EncodeError(`Aztec: layout consumed ${bit} of ${bits.length} bits`);
7783
+
7784
+ const mode = modeMessage(layers, symbol.dataWords, compact);
7785
+ drawModeMessage(matrix, mode, compact, center);
7786
+ drawBullsEye(matrix, center, compact ? 5 : 7);
7787
+
7788
+ if (!compact) {
7789
+ for (let i = 0, offset = 0; i < Math.floor(baseMatrixSize / 2) - 1; i += 15, offset += 16) {
7790
+ for (let p = center & 1; p < symbolSize; p += 2) {
7791
+ matrix.set(center - offset, p); matrix.set(center + offset, p);
7792
+ matrix.set(p, center - offset); matrix.set(p, center + offset);
7793
+ }
7794
+ }
7795
+ }
7796
+ return matrix;
7797
+ }
7798
+
7799
+ /** @param {number | undefined} layers @param {boolean | undefined} compact */
7800
+ function candidates(layers, compact) {
7801
+ if (layers !== undefined) {
7802
+ if (!Number.isInteger(layers) || layers < 1 || layers > 32) throw new EncodeError('Aztec: layers must be an integer 1..32');
7803
+ if (compact === true && layers > 4) throw new EncodeError('Aztec: compact symbols support layers 1..4');
7804
+ return [aztecLayer(layers, compact === true)];
7805
+ }
7806
+ if (compact === true) return AZTEC_COMPACT_LAYERS;
7807
+ if (compact === false) return AZTEC_FULL_LAYERS;
7808
+ return [...AZTEC_COMPACT_LAYERS, ...AZTEC_FULL_LAYERS];
7809
+ }
7810
+
7811
+ /**
7812
+ * Encode a UTF-8 string or bytes into an Aztec Code matrix.
7813
+ *
7814
+ * @param {string|ArrayBuffer|ArrayBufferView} value
7815
+ * @param {{layers?:number,compact?:boolean,eccPercent?:number,charset?:'utf-8'}} [options]
7816
+ * @returns {BitMatrix & {format?:string,layers?:number,compact?:boolean,eccPercent?:number,dataCodewords?:number}}
7817
+ */
7818
+ function encodeAztec(value, options = {}) {
7819
+ const eccPercent = options.eccPercent ?? 23;
7820
+ if (!Number.isFinite(eccPercent) || eccPercent < 5 || eccPercent > 95) {
7821
+ throw new EncodeError('Aztec: eccPercent must be between 5 and 95');
7822
+ }
7823
+ const high = encodeHighLevel(value, { charset: options.charset ?? 'utf-8' });
7824
+ for (const candidate of candidates(options.layers, options.compact)) {
7825
+ if (!candidate) continue;
7826
+ const wordSize = wordSizeForLayers(candidate.layers);
7827
+ const stuffed = stuffBits(high, wordSize);
7828
+ const dataWords = Math.ceil(stuffed.length / wordSize);
7829
+ const eccWords = eccCodewordsFor(dataWords, eccPercent);
7830
+ if (dataWords > candidate.maxDataCodewords || dataWords + eccWords > candidate.totalCodewords) continue;
7831
+ const checked = addCheckWords(stuffed, candidate.totalBits, wordSize, fieldForLayers(candidate.layers));
7832
+ // `addCheckWords` uses every remaining word as parity. This is stronger
7833
+ // than the requested percentage, never weaker, and canonical for a chosen
7834
+ // layer/data-word combination.
7835
+ const symbol = { ...candidate, dataWords: checked.dataWords };
7836
+ const matrix = buildAztecMatrix(checked.bits, symbol);
7837
+ matrix.format = 'aztec'; matrix.layers = candidate.layers; matrix.compact = candidate.compact;
7838
+ matrix.eccPercent = Math.round(checked.eccWords * wordSize * 100 / Math.max(1, stuffed.length));
7839
+ matrix.dataCodewords = checked.dataWords;
7840
+ return matrix;
7841
+ }
7842
+ throw new EncodeError('Aztec: payload does not fit the requested layers and error correction');
7843
+ }
7844
+
7845
+ __exports.stuffBits = stuffBits;
7846
+ __exports.addCheckWords = addCheckWords;
7847
+ __exports.modeMessage = modeMessage;
7848
+ __exports.buildAztecMatrix = buildAztecMatrix;
7849
+ __exports.encodeAztec = encodeAztec;
7850
+ };
7851
+
7852
+ __modules["aztec/decoder.js"] = function (__require, __exports) {
7853
+ /**
7854
+ * Decoder for a sampled Aztec symbol.
7855
+ *
7856
+ * This module deliberately accepts only a square, module-aligned BitMatrix.
7857
+ * Locating a bull's-eye in a photograph and perspective sampling are detector
7858
+ * concerns. Keeping the two stages apart makes all bit order and ECC rules
7859
+ * testable without image-processing noise.
7860
+ *
7861
+ * Contract with tables.js:
7862
+ * - aztecSymbolForLayers(compact, layers) returns the nominal symbol data;
7863
+ * - aztecWordSizeForLayers(layers) returns 6, 8, 10 or 12;
7864
+ * - aztecFieldForLayers(layers) returns the matching binary Galois field;
7865
+ * - aztecMatrixSize(compact, layers) returns the rendered square size.
7866
+ *
7867
+ * @module aztec/decoder
7868
+ */
7869
+ const { FormatError } = __require("core/errors.js");
7870
+ const { rsDecode } = __require("core/reed-solomon.js");
7871
+ const { aztecLayer: aztecSymbolForLayers, wordSizeForLayers: aztecWordSizeForLayers, fieldForLayers: aztecFieldForLayers, fieldForWordSize, aztecSymbolSize: aztecMatrixSize } = __require("aztec/tables.js");
7872
+
7873
+ const UPPER = ['CTRL_PS', ' ', ...'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'CTRL_LL', 'CTRL_ML', 'CTRL_DL', 'CTRL_BS'];
7874
+ const LOWER = ['CTRL_PS', ' ', ...'abcdefghijklmnopqrstuvwxyz', 'CTRL_US', 'CTRL_ML', 'CTRL_DL', 'CTRL_BS'];
7875
+ const MIXED = [
7876
+ 'CTRL_PS', ' ', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\b', '\t', '\n', '\x0b', '\f', '\r', '\x1b',
7877
+ '\x1c', '\x1d', '\x1e', '\x1f', '@', '\\', '^', '_', '`', '|', '~', '\x7f', 'CTRL_LL', 'CTRL_UL', 'CTRL_PL', 'CTRL_BS',
7878
+ ];
7879
+ const PUNCT = ['FLG(n)', '\r', '\r\n', '. ', ', ', ': ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}', 'CTRL_UL'];
7880
+ const DIGIT = ['CTRL_PS', ' ', ...'0123456789', ',', '.', 'CTRL_UL'];
7881
+ const TABLES = { UPPER, LOWER, MIXED, PUNCT, DIGIT };
7882
+
7883
+ /** @param {boolean[]} bits @param {number} offset @param {number} count */
7884
+ function readBits(bits, offset, count) {
7885
+ if (offset + count > bits.length) throw new FormatError('Aztec: truncated high-level stream');
7886
+ let value = 0;
7887
+ for (let i = 0; i < count; i++) value = (value << 1) | (bits[offset + i] ? 1 : 0);
7888
+ return value;
7889
+ }
7890
+
7891
+ /** @param {number} value @param {number} count @param {boolean[]} out */
7892
+ function appendBits(value, count, out) {
7893
+ for (let i = count - 1; i >= 0; i--) out.push(((value >>> i) & 1) !== 0);
7894
+ }
7895
+
7896
+ /**
7897
+ * Decode an Aztec high-level bit stream to its exact byte payload.
7898
+ *
7899
+ * Text tables contribute their ISO-8859-1 byte values; Binary Shift appends
7900
+ * raw bytes. ECI markers are consumed but intentionally not emitted: callers
7901
+ * receive the transported byte payload and may select their own charset.
7902
+ *
7903
+ * @param {boolean[]} bits
7904
+ * @returns {Uint8Array}
7905
+ */
7906
+ function decodeHighLevelBits(bits) {
7907
+ const output = [];
7908
+ let latch = 'UPPER';
7909
+ let shift = 'UPPER';
7910
+ let offset = 0;
7911
+
7912
+ while (offset < bits.length) {
7913
+ if (shift === 'BINARY') {
7914
+ if (offset + 5 > bits.length) break; // legal trailing pad
7915
+ let length = readBits(bits, offset, 5);
7916
+ offset += 5;
7917
+ if (length === 0) {
7918
+ if (offset + 11 > bits.length) throw new FormatError('Aztec: truncated Binary Shift length');
7919
+ length = readBits(bits, offset, 11) + 31;
7920
+ offset += 11;
7921
+ }
7922
+ if (offset + length * 8 > bits.length) throw new FormatError('Aztec: truncated Binary Shift data');
7923
+ for (let i = 0; i < length; i++) {
7924
+ output.push(readBits(bits, offset, 8));
7925
+ offset += 8;
7926
+ }
7927
+ shift = latch;
7928
+ continue;
7929
+ }
7930
+
7931
+ const size = shift === 'DIGIT' ? 4 : 5;
7932
+ if (offset + size > bits.length) break; // trailing pad after unstuffing
7933
+ const code = readBits(bits, offset, size);
7934
+ offset += size;
7935
+ const table = TABLES[shift];
7936
+ const token = table[code];
7937
+ if (token === undefined) throw new FormatError(`Aztec: invalid ${shift} code ${code}`);
7938
+
7939
+ if (token === 'FLG(n)') {
7940
+ if (offset + 3 > bits.length) throw new FormatError('Aztec: truncated FLG(n)');
7941
+ const count = readBits(bits, offset, 3);
7942
+ offset += 3;
7943
+ if (count === 0) output.push(0x1d); // FNC1 / GS
7944
+ else if (count <= 6) {
7945
+ // ECI assignment number, encoded as count decimal digits. It changes
7946
+ // interpretation, not the wire bytes, so consume it without output.
7947
+ for (let i = 0; i < count; i++) {
7948
+ if (offset + 4 > bits.length) throw new FormatError('Aztec: truncated ECI');
7949
+ const digit = readBits(bits, offset, 4);
7950
+ offset += 4;
7951
+ if (digit < 2 || digit > 11) throw new FormatError('Aztec: invalid ECI digit');
7952
+ }
7953
+ } else {
7954
+ throw new FormatError(`Aztec: unsupported FLG(${count})`);
7955
+ }
7956
+ shift = latch;
7957
+ continue;
7958
+ }
7959
+
7960
+ if (token.startsWith('CTRL_')) {
7961
+ const targetCode = token.slice(5, -1);
7962
+ const latchMode = token.endsWith('L');
7963
+ const target = ({ P: 'PUNCT', L: 'LOWER', M: 'MIXED', D: 'DIGIT', U: 'UPPER', B: 'BINARY' })[targetCode];
7964
+ if (!target) throw new FormatError(`Aztec: invalid control ${token}`);
7965
+ shift = target;
7966
+ if (latchMode) latch = shift;
7967
+ continue;
7968
+ }
7969
+
7970
+ for (let i = 0; i < token.length; i++) output.push(token.charCodeAt(i));
7971
+ shift = latch;
7972
+ }
7973
+ return Uint8Array.from(output);
7974
+ }
7975
+
7976
+ /** @param {boolean} compact @param {number} layers */
7977
+ function alignmentMap(compact, layers) {
7978
+ const baseSize = (compact ? 11 : 14) + layers * 4;
7979
+ if (compact) return Array.from({ length: baseSize }, (_, i) => i);
7980
+ const size = aztecMatrixSize(layers, false);
7981
+ const map = new Array(baseSize);
7982
+ const baseCenter = baseSize >> 1;
7983
+ const center = size >> 1;
7984
+ for (let i = 0; i < baseCenter; i++) {
7985
+ const offset = i + Math.floor(i / 15);
7986
+ map[baseCenter - i - 1] = center - offset - 1;
7987
+ map[baseCenter + i] = center + offset + 1;
7988
+ }
7989
+ return map;
7990
+ }
7991
+
7992
+ /**
7993
+ * Read the four sides of the parameter message. The order mirrors the
7994
+ * clockwise write order and is independent of the data spiral.
7995
+ *
7996
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix
7997
+ * @param {boolean} compact
7998
+ * @returns {boolean[]}
7999
+ */
8000
+ function readModeBits(matrix, compact) {
8001
+ const center = matrix.width >> 1;
8002
+ const side = compact ? 7 : 10;
8003
+ const offset = compact ? 5 : 7;
8004
+ // Full symbols skip the reference grid line through the bull's-eye. This
8005
+ // exact sequence is also used by drawModeMessage() in encoder.js.
8006
+ const positions = Array.from(
8007
+ { length: side },
8008
+ (_, i) => compact ? center - 3 + i : center - 5 + i + Math.floor(i / 5),
8009
+ );
8010
+ const bits = [];
8011
+ for (let i = 0; i < side; i++) bits.push(matrix.get(positions[i], center - offset));
8012
+ for (let i = 0; i < side; i++) bits.push(matrix.get(center + offset, positions[i]));
8013
+ for (let i = 0; i < side; i++) bits.push(matrix.get(positions[side - 1 - i], center + offset));
8014
+ for (let i = 0; i < side; i++) bits.push(matrix.get(center - offset, positions[side - 1 - i]));
8015
+ return bits;
8016
+ }
8017
+
8018
+ /** @param {boolean[]} bits @param {boolean} compact */
8019
+ function decodeModeMessage(bits, compact) {
8020
+ const total = compact ? 7 : 10;
8021
+ const dataWords = compact ? 2 : 4;
8022
+ const words = new Array(total);
8023
+ for (let i = 0; i < total; i++) words[i] = readBits(bits, i * 4, 4);
8024
+ const corrections = rsDecode(words, total - dataWords, fieldForWordSize(4), 1);
8025
+ let data = 0;
8026
+ for (let i = 0; i < dataWords; i++) data = (data << 4) | words[i];
8027
+ const layers = compact ? (data >>> 6) + 1 : (data >>> 11) + 1;
8028
+ const dataCodewords = compact ? (data & 0x3f) + 1 : (data & 0x7ff) + 1;
8029
+ return { layers, dataCodewords, corrections };
8030
+ }
8031
+
8032
+ /** @param {boolean} compact @param {number} layers */
8033
+ function totalBitsInLayers(compact, layers) {
8034
+ return ((compact ? 88 : 112) + 16 * layers) * layers;
8035
+ }
8036
+
8037
+ /**
8038
+ * Extract raw, stuffed codeword bits in logical ring order.
8039
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix
8040
+ * @param {boolean} compact @param {number} layers
8041
+ * @returns {boolean[]}
8042
+ */
8043
+ function extractBits(matrix, compact, layers) {
8044
+ const baseSize = (compact ? 11 : 14) + layers * 4;
8045
+ const map = alignmentMap(compact, layers);
8046
+ const raw = new Array(totalBitsInLayers(compact, layers));
8047
+ let offset = 0;
8048
+ for (let layer = 0; layer < layers; layer++) {
8049
+ const rowSize = (layers - layer) * 4 + (compact ? 9 : 12);
8050
+ for (let j = 0; j < rowSize; j++) {
8051
+ const col = j * 2;
8052
+ for (let k = 0; k < 2; k++) {
8053
+ raw[offset + col + k] = matrix.get(map[layer * 2 + k], map[layer * 2 + j]);
8054
+ raw[offset + rowSize * 2 + col + k] = matrix.get(map[layer * 2 + j], map[baseSize - 1 - layer * 2 - k]);
8055
+ raw[offset + rowSize * 4 + col + k] = matrix.get(map[baseSize - 1 - layer * 2 - k], map[baseSize - 1 - layer * 2 - j]);
8056
+ raw[offset + rowSize * 6 + col + k] = matrix.get(map[baseSize - 1 - layer * 2 - j], map[layer * 2 + k]);
8057
+ }
8058
+ }
8059
+ offset += rowSize * 8;
8060
+ }
8061
+ return raw;
8062
+ }
8063
+
8064
+ /** @param {boolean[]} raw @param {number} layers @param {number} dataCodewords */
8065
+ function correctAndUnstuff(raw, layers, dataCodewords) {
8066
+ const wordSize = aztecWordSizeForLayers(layers);
8067
+ const totalWords = Math.floor(raw.length / wordSize);
8068
+ if (dataCodewords <= 0 || dataCodewords > totalWords) throw new FormatError('Aztec: invalid data word count');
8069
+ const start = raw.length % wordSize;
8070
+ const words = new Array(totalWords);
8071
+ for (let i = 0; i < totalWords; i++) words[i] = readBits(raw, start + i * wordSize, wordSize);
8072
+ const corrections = rsDecode(words, totalWords - dataCodewords, aztecFieldForLayers(layers), 1);
8073
+ const mask = (1 << wordSize) - 1;
8074
+ const corrected = [];
8075
+ for (let i = 0; i < dataCodewords; i++) {
8076
+ const word = words[i];
8077
+ if (word === 0 || word === mask) throw new FormatError('Aztec: invalid stuffed codeword');
8078
+ if (word === 1 || word === mask - 1) {
8079
+ for (let j = 0; j < wordSize - 1; j++) corrected.push(word === mask - 1);
8080
+ } else {
8081
+ appendBits(word, wordSize, corrected);
8082
+ }
8083
+ }
8084
+ return { bits: corrected, corrections };
8085
+ }
8086
+
8087
+ /** @param {Uint8Array} bytes */
8088
+ function bytesToText(bytes) {
8089
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
8090
+ catch { return new TextDecoder('latin1').decode(bytes); }
8091
+ }
8092
+
8093
+ /**
8094
+ * Decode a square Aztec symbol with one bit per module and no quiet zone.
8095
+ * The matrix must already be oriented with the mode message at the top.
8096
+ *
8097
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix
8098
+ * @returns {{text: string, bytes: Uint8Array, compact: boolean, layers: number, corrections: number, eccPercent: number}}
8099
+ */
8100
+ function decodeAztec(matrix) {
8101
+ if (!matrix || matrix.width !== matrix.height) throw new FormatError('Aztec: expected a square BitMatrix');
8102
+ let compact;
8103
+ let mode;
8104
+ // Compact and full dimensions are disjoint; trying both also makes malformed
8105
+ // candidate handling deterministic for the future image detector.
8106
+ for (const candidate of [true, false]) {
8107
+ try {
8108
+ const value = decodeModeMessage(readModeBits(matrix, candidate), candidate);
8109
+ if (value.layers < 1 || value.layers > (candidate ? 4 : 32)) continue;
8110
+ if (aztecMatrixSize(value.layers, candidate) !== matrix.width) continue;
8111
+ compact = candidate;
8112
+ mode = value;
8113
+ break;
8114
+ } catch { /* Try the other family. */ }
8115
+ }
8116
+ if (compact === undefined || !mode) throw new FormatError('Aztec: invalid mode message or dimensions');
8117
+ // Ensure the declared layer data agrees with the table module, so a future
8118
+ // tables refactor cannot silently make decoder capacity calculations stale.
8119
+ aztecSymbolForLayers(mode.layers, compact);
8120
+ const raw = extractBits(matrix, compact, mode.layers);
8121
+ const payload = correctAndUnstuff(raw, mode.layers, mode.dataCodewords);
8122
+ const bytes = decodeHighLevelBits(payload.bits);
8123
+ const totalWords = Math.floor(raw.length / aztecWordSizeForLayers(mode.layers));
8124
+ return {
8125
+ text: bytesToText(bytes),
8126
+ bytes,
8127
+ compact,
8128
+ layers: mode.layers,
8129
+ corrections: mode.corrections + payload.corrections,
8130
+ eccPercent: Math.round(((totalWords - mode.dataCodewords) * 100) / totalWords),
8131
+ };
8132
+ }
8133
+
8134
+ __exports.decodeHighLevelBits = decodeHighLevelBits;
8135
+ __exports.decodeAztec = decodeAztec;
8136
+ };
8137
+
8138
+ __modules["aztec/detector.js"] = function (__require, __exports) {
8139
+ /**
8140
+ * Aztec image detection.
8141
+ *
8142
+ * Aztec has no finder pattern at its outer border. Its reliable geometric
8143
+ * anchor is instead the alternating square bull's-eye in the centre: five
8144
+ * rings in Compact symbols, seven rings in Full symbols. The detector finds
8145
+ * isolated central modules, verifies those rings at module centres, then
8146
+ * samples each legal symbol dimension. The decoder is deliberately the final
8147
+ * arbiter: its mode-message Reed--Solomon check rejects accidental concentric
8148
+ * artwork and tells us which of the compact/full dimensions is real.
8149
+ *
8150
+ * Sampling uses a quadrilateral, not a cropped bitmap, so the detected
8151
+ * rotation is corrected before decoding. The ring search covers arbitrary
8152
+ * in-plane rotations (four-degree coarse search; at normal camera scales its
8153
+ * positional error remains well inside a module). The optional inverse pass
8154
+ * supports light modules on a dark field.
8155
+ *
8156
+ * @module aztec/detector
8157
+ */
8158
+ const { NotFoundError } = __require("core/errors.js");
8159
+ const { sampleQuad } = __require("image/grid-sampler.js");
8160
+ const { decodeAztec } = __require("aztec/decoder.js");
8161
+
8162
+ /** @typedef {{x:number, y:number}} Point */
8163
+ /** @typedef {{corners: Point[], dimension: number, compact: boolean, moduleSize: number, matrix: import('../core/bit-matrix.js').BitMatrix}} Detection */
8164
+
8165
+ // Compact: 11 + 4 layers. Full symbols add reference-grid rows/columns every
8166
+ // 15 modules measured from their central 14-module base, not every 15 layers.
8167
+ const DIMENSIONS = [
8168
+ ...[1, 2, 3, 4].map((layers) => ({ compact: true, dimension: 11 + 4 * layers })),
8169
+ ...Array.from({ length: 32 }, (_, index) => {
8170
+ const layers = index + 1;
8171
+ return { compact: false, dimension: 15 + 4 * layers + 2 * Math.floor((2 * layers + 6) / 15) };
8172
+ }),
8173
+ ];
8174
+
8175
+ function pixel(image, x, y) {
8176
+ const ix = Math.round(x);
8177
+ const iy = Math.round(y);
8178
+ return ix >= 0 && iy >= 0 && ix < image.width && iy < image.height && image.get(ix, iy);
8179
+ }
8180
+
8181
+ /** Connected components of either polarity, retaining only plausible modules. */
8182
+ function components(image, value) {
8183
+ const seen = new Uint8Array(image.width * image.height);
8184
+ const out = [];
8185
+ const maximumArea = Math.max(4, Math.floor(image.width * image.height * 0.08));
8186
+ for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
8187
+ const start = y * image.width + x;
8188
+ if (seen[start] || image.get(x, y) !== value) continue;
8189
+ const xs = [x];
8190
+ const ys = [y];
8191
+ seen[start] = 1;
8192
+ let head = 0;
8193
+ let minX = x; let maxX = x; let minY = y; let maxY = y;
8194
+ while (head < xs.length) {
8195
+ const px = xs[head]; const py = ys[head++];
8196
+ if (px < minX) minX = px; if (px > maxX) maxX = px;
8197
+ if (py < minY) minY = py; if (py > maxY) maxY = py;
8198
+ for (const [nx, ny] of [[px - 1, py], [px + 1, py], [px, py - 1], [px, py + 1]]) {
8199
+ if (nx < 0 || ny < 0 || nx >= image.width || ny >= image.height) continue;
8200
+ const at = ny * image.width + nx;
8201
+ if (!seen[at] && image.get(nx, ny) === value) {
8202
+ seen[at] = 1; xs.push(nx); ys.push(ny);
8203
+ }
8204
+ }
8205
+ }
8206
+ const width = maxX - minX + 1;
8207
+ const height = maxY - minY + 1;
8208
+ const area = width * height;
8209
+ // The central module is solid and approximately square. This filter is
8210
+ // intentionally permissive because a rotated raster module is diamond-ish.
8211
+ if (xs.length <= maximumArea && Math.abs(width - height) <= Math.max(1, Math.ceil(Math.max(width, height) * 0.35)) &&
8212
+ xs.length >= area * 0.45) {
8213
+ out.push({ x: (minX + maxX) / 2, y: (minY + maxY) / 2, width, height, pixels: xs.length });
8214
+ }
8215
+ }
8216
+ return out.sort((a, b) => b.pixels - a.pixels).slice(0, 2000);
8217
+ }
8218
+
8219
+ function expectedDark(ring, inverted) {
8220
+ return inverted ? (ring & 1) === 1 : (ring & 1) === 0;
8221
+ }
8222
+
8223
+ /** Score one square bull's-eye at an angle and a candidate module pitch. */
8224
+ function ringScore(image, centre, pitch, angle, inverted, rings) {
8225
+ const cos = Math.cos(angle);
8226
+ const sin = Math.sin(angle);
8227
+ let correct = 0;
8228
+ let total = 0;
8229
+ for (let ring = 0; ring < rings; ring++) {
8230
+ const wanted = expectedDark(ring, inverted);
8231
+ for (let j = -ring; j <= ring; j++) for (let i = -ring; i <= ring; i++) {
8232
+ if (ring && Math.abs(i) !== ring && Math.abs(j) !== ring) continue;
8233
+ const x = centre.x + (i * cos - j * sin) * pitch;
8234
+ const y = centre.y + (i * sin + j * cos) * pitch;
8235
+ if (pixel(image, x, y) === wanted) correct++;
8236
+ total++;
8237
+ }
8238
+ }
8239
+ return correct / total;
8240
+ }
8241
+
8242
+ function rotateCorners(corners, turn) {
8243
+ return corners.slice(turn).concat(corners.slice(0, turn));
8244
+ }
8245
+
8246
+ function invert(matrix) {
8247
+ const out = matrix.clone();
8248
+ for (let y = 0; y < out.height; y++) for (let x = 0; x < out.width; x++) out.flip(x, y);
8249
+ return out;
8250
+ }
8251
+
8252
+ function cornersFor(centre, pitch, angle, dimension) {
8253
+ const half = dimension * pitch / 2;
8254
+ const cos = Math.cos(angle);
8255
+ const sin = Math.sin(angle);
8256
+ const point = (x, y) => ({ x: centre.x + x * cos - y * sin, y: centre.y + x * sin + y * cos });
8257
+ return [point(-half, -half), point(half, -half), point(half, half), point(-half, half)];
8258
+ }
8259
+
8260
+ /**
8261
+ * Find an Aztec symbol in a binarized image.
8262
+ *
8263
+ * The returned matrix is in the orientation accepted by the Aztec decoder.
8264
+ * A valid mode message is required before a geometric candidate is returned,
8265
+ * making false positives from decorative concentric squares very unlikely.
8266
+ *
8267
+ * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage Set bit = dark.
8268
+ * @returns {Detection | null}
8269
+ */
8270
+ function detectAztec(binaryImage) {
8271
+ if (!binaryImage || !binaryImage.width || !binaryImage.height) {
8272
+ throw new NotFoundError('detectAztec: no image supplied');
8273
+ }
8274
+ const candidates = [];
8275
+ for (const inverted of [false, true]) {
8276
+ for (const core of components(binaryImage, !inverted)) {
8277
+ // A non-rotated one-module component directly gives its pitch. For
8278
+ // rotated modules its bounding box grows by |sin| + |cos|, compensated
8279
+ // below for every tested angle.
8280
+ for (let degrees = 0; degrees < 180; degrees += 4) {
8281
+ const angle = degrees * Math.PI / 180;
8282
+ const scale = Math.abs(Math.cos(angle)) + Math.abs(Math.sin(angle));
8283
+ const pitch = ((core.width + core.height) / 2) / scale;
8284
+ if (pitch < 0.8) continue;
8285
+ // Test Full first: its seven rings also exclude Compact candidates.
8286
+ const fullScore = ringScore(binaryImage, core, pitch, angle, inverted, 7);
8287
+ const rings = fullScore >= 0.88 ? 7 : 5;
8288
+ const score = rings === 7 ? fullScore : ringScore(binaryImage, core, pitch, angle, inverted, 5);
8289
+ if (score < 0.91) continue;
8290
+ const symbolKinds = rings === 7 ? DIMENSIONS.filter((item) => !item.compact) : DIMENSIONS.filter((item) => item.compact);
8291
+ for (const kind of symbolKinds) {
8292
+ const baseCorners = cornersFor(core, pitch, angle, kind.dimension);
8293
+ for (let turn = 0; turn < 4; turn++) {
8294
+ const corners = rotateCorners(baseCorners, turn);
8295
+ let matrix;
8296
+ try { matrix = sampleQuad(binaryImage, kind.dimension, corners); } catch (e) { continue; }
8297
+ if (inverted) matrix = invert(matrix);
8298
+ try {
8299
+ // The decoder verifies the mode-message ECC and exact geometry.
8300
+ // We do not expose its result here so callers can use pure
8301
+ // detection without treating payload decoding as an API contract.
8302
+ decodeAztec(matrix);
8303
+ candidates.push({ corners, dimension: kind.dimension, compact: kind.compact,
8304
+ moduleSize: pitch, matrix, score });
8305
+ } catch (e) { /* Not an Aztec mode message at this dimension. */ }
8306
+ }
8307
+ }
8308
+ }
8309
+ }
8310
+ }
8311
+ candidates.sort((a, b) => b.score - a.score || b.moduleSize - a.moduleSize);
8312
+ const best = candidates[0];
8313
+ if (!best) return null;
8314
+ delete best.score;
8315
+ return best;
8316
+ }
8317
+
8318
+ /**
8319
+ * Detect then decode an Aztec symbol. Detection failure is a normal result for
8320
+ * images without an Aztec code, therefore invalid candidates return null.
8321
+ *
8322
+ * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage
8323
+ * @returns {(import('./decoder.js').DecodeResult & {corners: Point[]}) | null}
8324
+ */
8325
+ function detectAndDecodeAztec(binaryImage) {
8326
+ let detection;
8327
+ try { detection = detectAztec(binaryImage); } catch (e) { return null; }
8328
+ if (!detection) return null;
8329
+ try { return Object.assign({ corners: detection.corners }, decodeAztec(detection.matrix)); }
8330
+ catch (e) { return null; }
8331
+ }
8332
+
8333
+ __exports.detectAztec = detectAztec;
8334
+ __exports.detectAndDecodeAztec = detectAndDecodeAztec;
8335
+ };
8336
+
8337
+ __modules["aztec/index.js"] = function (__require, __exports) {
8338
+ /** Aztec Code entry points. @module aztec */
8339
+ const __reexport0 = __require("aztec/encoder.js"); __exports.encodeAztec = __reexport0.encodeAztec;
8340
+ const __reexport1 = __require("aztec/decoder.js"); __exports.decodeAztec = __reexport1.decodeAztec;
8341
+ const __reexport2 = __require("aztec/detector.js"); __exports.detectAztec = __reexport2.detectAztec; __exports.detectAndDecodeAztec = __reexport2.detectAndDecodeAztec;
8342
+ const __reexport3 = __require("aztec/tables.js"); __exports.AZTEC_COMPACT_LAYERS = __reexport3.AZTEC_COMPACT_LAYERS; __exports.AZTEC_FULL_LAYERS = __reexport3.AZTEC_FULL_LAYERS; __exports.AZTEC_LAYERS = __reexport3.AZTEC_LAYERS; __exports.AZTEC_DEFAULT_ECC_PERCENT = __reexport3.AZTEC_DEFAULT_ECC_PERCENT; __exports.AZTEC_RS_GENERATOR_BASE = __reexport3.AZTEC_RS_GENERATOR_BASE; __exports.aztecLayer = __reexport3.aztecLayer; __exports.aztecSymbolSize = __reexport3.aztecSymbolSize; __exports.validateAztecTables = __reexport3.validateAztecTables;
8343
+
8344
+
8345
+ };
8346
+
8347
+ __modules["pdf417/compaction.js"] = function (__require, __exports) {
8348
+ /** PDF417 high-level text, byte and numeric compaction. @module pdf417/compaction */
8349
+ const { EncodeError, FormatError } = __require("core/errors.js");
8350
+
8351
+ const ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ ';
8352
+ const LOWER = 'abcdefghijklmnopqrstuvwxyz ';
8353
+ const MIXED = '0123456789&\r\t,:#-.$/+%*=^';
8354
+ const PUNCT = ';<>@[\\]_`~!\r\t,:\n-.$/"|*()?{}\'';
8355
+
8356
+ function packBase30(values) {
8357
+ const out = [];
8358
+ for (let i = 0; i < values.length; i += 2) out.push(values[i] * 30 + (i + 1 < values.length ? values[i + 1] : 29));
8359
+ return out;
8360
+ }
8361
+
8362
+ /** Compact a value using the PDF417 Text Compaction alphabet. */
8363
+ function compactPdf417Text(value) {
8364
+ if (typeof value !== 'string') throw new EncodeError('PDF417 text: value must be a string');
8365
+ const values = [];
8366
+ let submode = 'alpha';
8367
+ for (const character of value) {
8368
+ const inAlpha = ALPHA.indexOf(character), inLower = LOWER.indexOf(character);
8369
+ const inMixed = MIXED.indexOf(character), inPunct = PUNCT.indexOf(character);
8370
+ if (submode === 'alpha') {
8371
+ if (inAlpha >= 0) values.push(inAlpha);
8372
+ else if (inLower >= 0) { values.push(27, inLower); submode = 'lower'; }
8373
+ else if (inMixed >= 0 || character === ' ') { values.push(28, character === ' ' ? 26 : inMixed); submode = 'mixed'; }
8374
+ else if (inPunct >= 0) values.push(29, inPunct);
8375
+ else throw new EncodeError(`PDF417 text: unsupported character ${JSON.stringify(character)}`);
8376
+ } else if (submode === 'lower') {
8377
+ if (inLower >= 0) values.push(inLower);
8378
+ else if (inAlpha >= 0) values.push(27, inAlpha);
8379
+ else if (inMixed >= 0 || character === ' ') { values.push(28, character === ' ' ? 26 : inMixed); submode = 'mixed'; }
8380
+ else if (inPunct >= 0) values.push(29, inPunct);
8381
+ else throw new EncodeError(`PDF417 text: unsupported character ${JSON.stringify(character)}`);
8382
+ } else {
8383
+ if (inMixed >= 0) values.push(inMixed);
8384
+ else if (character === ' ') values.push(26);
8385
+ else if (inAlpha >= 0) { values.push(28); submode = 'alpha'; values.push(inAlpha); }
8386
+ else if (inLower >= 0) { values.push(27); submode = 'lower'; values.push(inLower); }
8387
+ else if (inPunct >= 0) values.push(29, inPunct);
8388
+ else throw new EncodeError(`PDF417 text: unsupported character ${JSON.stringify(character)}`);
8389
+ }
8390
+ }
8391
+ return packBase30(values);
8392
+ }
8393
+
8394
+ function asBytes(value) {
8395
+ if (value instanceof Uint8Array) return value;
8396
+ if (ArrayBuffer.isView(value)) return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
8397
+ if (typeof value === 'string') return new TextEncoder().encode(value);
8398
+ throw new EncodeError('PDF417 byte: value must be text or a byte array');
8399
+ }
8400
+
8401
+ /** Compact bytes using latch 924 for exact six-byte blocks and 901 otherwise. */
8402
+ function compactPdf417Bytes(value) {
8403
+ const bytes = asBytes(value);
8404
+ const utf8 = typeof value === 'string' && /[^\x00-\x7f]/.test(value);
8405
+ const out = utf8 ? [927, 26] : [];
8406
+ out.push(bytes.length > 0 && bytes.length % 6 === 0 ? 924 : 901);
8407
+ let at = 0;
8408
+ while (at + 6 <= bytes.length) {
8409
+ let number = 0n;
8410
+ for (let i = 0; i < 6; i++) number = (number << 8n) | BigInt(bytes[at++]);
8411
+ const group = new Array(5);
8412
+ for (let i = 4; i >= 0; i--) { group[i] = Number(number % 900n); number /= 900n; }
8413
+ out.push(...group);
8414
+ }
8415
+ while (at < bytes.length) out.push(bytes[at++]);
8416
+ return out;
8417
+ }
8418
+
8419
+ /** Compact decimal digits using latch 902 and groups of at most 44 digits. */
8420
+ function compactPdf417Numeric(value) {
8421
+ if (typeof value !== 'string' || !/^\d+$/.test(value)) throw new EncodeError('PDF417 numeric: value must contain decimal digits only');
8422
+ const out = [902];
8423
+ for (let at = 0; at < value.length; at += 44) {
8424
+ let number = BigInt(`1${value.slice(at, at + 44)}`);
8425
+ const group = [];
8426
+ do { group.unshift(Number(number % 900n)); number /= 900n; } while (number > 0n);
8427
+ out.push(...group);
8428
+ }
8429
+ return out;
8430
+ }
8431
+
8432
+ /** Compact a single value, selecting text, numeric or byte mode. */
8433
+ function compactPdf417(value, options = {}) {
8434
+ const mode = options.compaction ?? 'auto';
8435
+ if (mode === 'text') return compactPdf417Text(value);
8436
+ if (mode === 'byte') return compactPdf417Bytes(value);
8437
+ if (mode === 'numeric') return compactPdf417Numeric(value);
8438
+ if (mode !== 'auto') throw new EncodeError(`PDF417: unsupported compaction mode ${JSON.stringify(mode)}`);
8439
+ if (typeof value === 'string' && /^\d{13,}$/.test(value)) return compactPdf417Numeric(value);
8440
+ if (typeof value === 'string') {
8441
+ try { return compactPdf417Text(value); } catch (error) { if (!(error instanceof EncodeError)) throw error; }
8442
+ }
8443
+ return compactPdf417Bytes(value);
8444
+ }
8445
+
8446
+ function assertCodeword(codeword) {
8447
+ if (!Number.isInteger(codeword) || codeword < 0 || codeword > 928) throw new FormatError('PDF417: codeword is outside 0..928');
8448
+ }
8449
+
8450
+ function decodeUtf8(bytes, eci) {
8451
+ if (eci === 3) return Array.from(bytes, (byte) => String.fromCharCode(byte)).join('');
8452
+ if (eci !== 26) throw new FormatError(`PDF417 ECI: unsupported assignment number ${eci}`);
8453
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(new Uint8Array(bytes)); }
8454
+ catch { throw new FormatError('PDF417 byte: invalid UTF-8 sequence'); }
8455
+ }
8456
+
8457
+ function decodeByteSegment(codewords, at, eci, sixOnly = false) {
8458
+ const values = [];
8459
+ while (at < codewords.length && codewords[at] < 900) values.push(codewords[at++]);
8460
+ if (sixOnly && values.length % 5) throw new FormatError('PDF417 byte: 924 segment must contain complete six-byte groups');
8461
+ const bytes = [];
8462
+ // In 901 mode an encoder can use five terminal literal codewords. The
8463
+ // unambiguous groups are therefore the ones followed by another codeword;
8464
+ // 924 is available whenever a segment consists exclusively of six-byte groups.
8465
+ const groupCount = sixOnly ? values.length / 5 : Math.max(0, Math.floor((values.length - 1) / 5));
8466
+ for (let groupAt = 0; groupAt < groupCount * 5; groupAt += 5) {
8467
+ let number = 0n;
8468
+ for (let i = 0; i < 5; i++) number = number * 900n + BigInt(values[groupAt + i]);
8469
+ const group = new Uint8Array(6);
8470
+ for (let i = 5; i >= 0; i--) { group[i] = Number(number & 255n); number >>= 8n; }
8471
+ if (number !== 0n) throw new FormatError('PDF417 byte: base-900 group exceeds six bytes');
8472
+ bytes.push(...group);
8473
+ }
8474
+ for (let i = groupCount * 5; i < values.length; i++) {
8475
+ if (values[i] > 255) throw new FormatError('PDF417 byte: literal tail is outside 0..255');
8476
+ bytes.push(values[i]);
8477
+ }
8478
+ return { at, text: decodeUtf8(bytes, eci), bytes: Uint8Array.from(bytes) };
8479
+ }
8480
+
8481
+ function decodeTextSegment(codewords, at, eci) {
8482
+ let mode = 'alpha';
8483
+ let output = '';
8484
+ let shift = null;
8485
+ let shiftedBytes = [];
8486
+ const bytes = [];
8487
+ const flushShiftedBytes = () => {
8488
+ if (shiftedBytes.length) {
8489
+ output += decodeUtf8(shiftedBytes, eci);
8490
+ bytes.push(...shiftedBytes);
8491
+ shiftedBytes = [];
8492
+ }
8493
+ };
8494
+ const emit = (alphabet, value) => {
8495
+ if (value < 0 || value >= alphabet.length) throw new FormatError('PDF417 text: invalid submode value');
8496
+ output += alphabet[value];
8497
+ };
8498
+ const process = (value) => {
8499
+ if (shift) { emit(shift === 'alpha' ? ALPHA : PUNCT, value); shift = null; return; }
8500
+ if (mode === 'alpha') {
8501
+ if (value < 26) emit(ALPHA, value);
8502
+ else if (value === 26) output += ' ';
8503
+ else if (value === 27) mode = 'lower';
8504
+ else if (value === 28) mode = 'mixed';
8505
+ else if (value === 29) shift = 'punct';
8506
+ } else if (mode === 'lower') {
8507
+ if (value < 26) emit(LOWER, value);
8508
+ else if (value === 26) output += ' ';
8509
+ else if (value === 27) shift = 'alpha';
8510
+ else if (value === 28) mode = 'mixed';
8511
+ else if (value === 29) shift = 'punct';
8512
+ } else if (mode === 'mixed') {
8513
+ if (value < 25) emit(MIXED, value);
8514
+ else if (value === 25) mode = 'punct';
8515
+ else if (value === 26) output += ' ';
8516
+ else if (value === 27) mode = 'lower';
8517
+ else if (value === 28) mode = 'alpha';
8518
+ else if (value === 29) shift = 'punct';
8519
+ } else {
8520
+ if (value < 29) emit(PUNCT, value);
8521
+ else if (value === 29) mode = 'alpha';
8522
+ }
8523
+ };
8524
+ while (at < codewords.length) {
8525
+ const codeword = codewords[at];
8526
+ if (codeword >= 900 && codeword !== 913) break;
8527
+ at++;
8528
+ if (codeword === 913) {
8529
+ if (at >= codewords.length || codewords[at] > 255) throw new FormatError('PDF417 text: invalid byte shift');
8530
+ shiftedBytes.push(codewords[at++]);
8531
+ continue;
8532
+ }
8533
+ flushShiftedBytes();
8534
+ process(Math.floor(codeword / 30));
8535
+ process(codeword % 30);
8536
+ }
8537
+ flushShiftedBytes();
8538
+ return { at, text: output, bytes: Uint8Array.from(bytes) };
8539
+ }
8540
+
8541
+ function decodeNumericSegment(codewords, at) {
8542
+ let output = '';
8543
+ while (at < codewords.length && codewords[at] < 900) {
8544
+ const end = Math.min(at + 15, codewords.length);
8545
+ let number = 0n;
8546
+ for (; at < end && codewords[at] < 900; at++) number = number * 900n + BigInt(codewords[at]);
8547
+ const decimal = number.toString();
8548
+ if (!decimal.startsWith('1')) throw new FormatError('PDF417 numeric: missing leading sentinel');
8549
+ output += decimal.slice(1);
8550
+ }
8551
+ return { at, text: output, bytes: new Uint8Array(0) };
8552
+ }
8553
+
8554
+ /**
8555
+ * Decode PDF417 compaction while preserving raw Byte Compaction and byte-shift
8556
+ * payloads. Text and Numeric Compaction do not manufacture bytes: their text
8557
+ * is available on each segment, while `bytes` contains only octets carried by
8558
+ * modes that encode octets explicitly.
8559
+ */
8560
+ function decodePdf417CompactionDetailed(codewords) {
8561
+ if (!Array.isArray(codewords) && !ArrayBuffer.isView(codewords)) throw new FormatError('PDF417: codewords must be an array');
8562
+ for (const codeword of codewords) assertCodeword(codeword);
8563
+ let at = 0;
8564
+ // ISO/IEC 8859-1 is the PDF417 default; UTF-8 is selected explicitly with ECI 26.
8565
+ let eci = 3;
8566
+ let output = '';
8567
+ const bytes = [];
8568
+ const segments = [];
8569
+ while (at < codewords.length) {
8570
+ const codeword = codewords[at];
8571
+ if (codeword < 900 || codeword === 900 || codeword === 913) {
8572
+ const start = at;
8573
+ const latch = codeword === 900 ? codeword : null;
8574
+ if (latch !== null) at++;
8575
+ const segment = decodeTextSegment(codewords, at, eci);
8576
+ at = segment.at;
8577
+ output += segment.text;
8578
+ bytes.push(...segment.bytes);
8579
+ if (segment.text.length || segment.bytes.length) segments.push({ mode: 'text', text: segment.text, bytes: segment.bytes, eci, latch, codewordStart: start, codewordEnd: at });
8580
+ continue;
8581
+ }
8582
+ const start = at;
8583
+ at++;
8584
+ if (codeword === 901) {
8585
+ const segment = decodeByteSegment(codewords, at, eci);
8586
+ at = segment.at;
8587
+ output += segment.text;
8588
+ bytes.push(...segment.bytes);
8589
+ segments.push({ mode: 'byte', text: segment.text, bytes: segment.bytes, eci, latch: codeword, codewordStart: start, codewordEnd: at });
8590
+ } else if (codeword === 924) {
8591
+ const segment = decodeByteSegment(codewords, at, eci, true);
8592
+ at = segment.at;
8593
+ output += segment.text;
8594
+ bytes.push(...segment.bytes);
8595
+ segments.push({ mode: 'byte', text: segment.text, bytes: segment.bytes, eci, latch: codeword, codewordStart: start, codewordEnd: at });
8596
+ } else if (codeword === 902) {
8597
+ const segment = decodeNumericSegment(codewords, at);
8598
+ at = segment.at;
8599
+ output += segment.text;
8600
+ segments.push({ mode: 'numeric', text: segment.text, bytes: segment.bytes, eci, latch: codeword, codewordStart: start, codewordEnd: at });
8601
+ } else if (codeword === 927) {
8602
+ if (at >= codewords.length || codewords[at] > 899) throw new FormatError('PDF417 ECI: missing assignment number');
8603
+ eci = codewords[at++];
8604
+ } else {
8605
+ throw new FormatError(`PDF417: unsupported compaction codeword ${codeword}`);
8606
+ }
8607
+ }
8608
+ return { text: output, bytes: Uint8Array.from(bytes), segments };
8609
+ }
8610
+
8611
+ /** Decode PDF417 Text, Byte, Numeric and UTF-8 ECI compaction segments in source order. */
8612
+ function decodePdf417Compaction(codewords) {
8613
+ return decodePdf417CompactionDetailed(codewords).text;
8614
+ }
8615
+
8616
+ __exports.compactPdf417Text = compactPdf417Text;
8617
+ __exports.compactPdf417Bytes = compactPdf417Bytes;
8618
+ __exports.compactPdf417Numeric = compactPdf417Numeric;
8619
+ __exports.compactPdf417 = compactPdf417;
8620
+ __exports.decodePdf417CompactionDetailed = decodePdf417CompactionDetailed;
8621
+ __exports.decodePdf417Compaction = decodePdf417Compaction;
8622
+ };
8623
+
8624
+ __modules["pdf417/error-correction.js"] = function (__require, __exports) {
8625
+ const { EncodeError } = __require("core/errors.js");
8626
+ const { GF929 } = __require("core/galois-field.js");
8627
+ const { rsDecode, rsEncode } = __require("core/reed-solomon.js");
8628
+ function pdf417EccLength(level) {
8629
+ if (!Number.isInteger(level) || level < 0 || level > 8) throw new EncodeError('PDF417: error correction level must be in 0..8');
8630
+ return 1 << (level + 1);
8631
+ }
8632
+ function pdf417ErrorCorrection(data, level) {
8633
+ return rsEncode(data, pdf417EccLength(level), GF929, 1);
8634
+ }
8635
+
8636
+ /** Correct PDF417 codewords, optionally marking unreadable codewords as erasures. */
8637
+ function pdf417CorrectErrors(codewords, level, erasures = []) {
8638
+ return rsDecode(codewords, pdf417EccLength(level), GF929, 1, erasures);
8639
+ }
8640
+
8641
+ __exports.pdf417EccLength = pdf417EccLength;
8642
+ __exports.pdf417ErrorCorrection = pdf417ErrorCorrection;
8643
+ __exports.pdf417CorrectErrors = pdf417CorrectErrors;
8644
+ };
8645
+
8646
+ __modules["pdf417/tables.js"] = function (__require, __exports) {
8647
+ /** PDF417 symbol-character pattern table. @module pdf417/tables */
8648
+ const PDF417_CLUSTER_NUMBERS = Object.freeze([0, 3, 6]);
8649
+ const PDF417_CODEWORDS_PER_CLUSTER = 929;
8650
+
8651
+ // Transcribed from the normative AIM USS PDF417 specification, Appendix H,
8652
+ // Table H1 (Bar-Space Sequence Table), from a publicly accessible copy hosted
8653
+ // at https://expresscorp.com/wp-content/uploads/2023/02/USS-PDF-417.pdf.
8654
+ // ISO/IEC 15438:2015 is the current ISO specification for PDF417.
8655
+ // Each eight-digit sequence is ordered bar, space, bar, space, bar, space,
8656
+ // bar, space and is indexed by its codeword value from 0 through 928.
8657
+ const WIDTH_SEQUENCES = Object.freeze([
8658
+ '3111113641111144511111523111123541111243511112512111132631111334211114251111151621111524111116152111213631112144' +
8659
+ '4111215221112235311122434111225111112326211123341111242511113136211131443111315211113235211132433111325111113334' +
8660
+ '2111334211114144211141521111424321114251111151525111611131121135411211435112115121121226311212344112124221121325' +
8661
+ '3112133311121416211214243112143211121515211215231112161421122135311221434112215111122226211222343112224211122325' +
8662
+ '2112233331122341111224242112243211123135211231433112315111123234211232421112333321123341111241432112415111124242' +
8663
+ '1112434121131126311311344113114221131225311312334113124111131316211313243113133211131415211314231113151411131613' +
8664
+ '1113212621132134311321421113222521132233311322411113232421132332111324231113252211133134211331421113323321133241' +
8665
+ '1113333211134142211411253114113341141141111412162114122431141232111413152114132331141331111414142114142211141513' +
8666
+ '2114152111142125211421333114214111142224211422321114232321142331111424221114252121143141111433311115111621151124' +
8667
+ '3115113211151215211512233115123111151314211513221115141321151421111515121115212411152223111523221116111531161131' +
8668
+ '2116122221161321111615113211113542111143521111512211122632111234421112422211132532111333421113411211141622111424' +
8669
+ '1211151522112135321121434211215112112226221122343211224212112325221123331211242412112523121131352211314332113151' +
8670
+ '1211323422113242121133331211343212114143221141511211424212115151312111264121113451211142312112254121123351211241' +
8671
+ '2121131631211324412113322121141531211423412114312121151431211522221211263212113442121142212121262212122532121233' +
8672
+ '4212124121212225312122334121224111212316121214152212142332121431112124152121242311212514121221262212213432122142' +
8673
+ '1121312612122225221222333212224111213225212132333121324111213324121224231121342312123134221231421121413412123233' +
8674
+ '2212324111214233212142411121433212124142112151421212424111215241312211254122113351221141212212163122122441221232' +
8675
+ '2122131531221323412213312122141431221422212215132122161222131125321311334213114121222125221312243213123211222216' +
8676
+ '1213131531222232321313311122231512131414221314221122241421222422221315211213161212132125221321333213214111223125' +
8677
+ '1213222422132232112232242122323222132331112233231213242212132521121331332213314111224133121332321122423212133331' +
8678
+ '1122433111225141212311163123112441231132212312153123122341231231212313143123132221231413312314212123151221231611' +
8679
+ '1214111622141124321411321123211612141215221412233214123111232215212322233123223111232314121414132214142111232413' +
8680
+ '2123242111232512121421242214213211233124121422232214223111233223212332311123332212142421112334211123413211234231' +
8681
+ '2124111531241123412411312124121431241222212413133124132121241412212415111215111522151123321511311124211512151214' +
8682
+ '2215122211242214212422222215132111242313121514121124241212151511121521231124312311243222112433213125112231251221' +
8683
+ '2125141122161122121612131125221311252312112524112311112633111134431111422311122533111233131113162311132433111332' +
8684
+ '1311141523111423131115141311161313112126231121343311214213112225231122333311224113112324231123321311242313112522' +
8685
+ '1311313423113142131132332311324113113332131141421311424132211125422111335221114122211216322112244221123222211315' +
8686
+ '3221132342211331222114143221142222211513322115212312112533121133431211412221212523121224331212321221221613121315' +
8687
+ '3221223233121331122123152221232323121422122124141312151312212513131221252312213333122141122131251312222432213141' +
8688
+ '1221322422213232231223311221332313122422122134221312313323123141122141331312323212214232131233311312414112215141' +
8689
+ '3131111641311124513111323131121541311223513112313131131441311322313114134131142131311512222211163222112442221132' +
8690
+ '2131211622221215413121324222123121312215313122234131223121312314222214133222142121312413313124212222161113131116' +
8691
+ '2313112433131132122221161313121523131223331312311131311612222215222222233222223111313215213132233131323123131421' +
8692
+ '1131331412222413222224211131341313131611131321242313213212223124131322232313223111314124122232232222323111314223' +
8693
+ '2131423113132421122234211313313212224132131332311131513212224231313211154132112351321131313212144132122231321313' +
8694
+ '4132132131321412313215112223111532231123422311312132211522231214413221312132221431322222322313212132231322231412' +
8695
+ '2132241222231511213225111314111523141123331411311223211513141214231412221132311512232214222322222314132111323214' +
8696
+ '2132322213141412113233131223241213141511122325111314212323142131122331231314222211324123122332221314232111324222' +
8697
+ '1223332113143131113251313133111441331122313312134133122131331312313314112224111432241122213321142224121332241221' +
8698
+ '2133221331332221213323122224141121332411131511142315112212242114131512132315122111333114122422132224222111333213' +
8699
+ '2133322113151411113333121224241111333411122431221133412211334221413411213134131132251121222512122225131113161113' +
8700
+ '1225211311343113131613111225231124111125141112162411122414111315241113233411133114111414241114221411151324111521' +
8701
+ '1411212524112133341121411411222424112232141123232411233114112422141125211411313324113141141132321411333114114141' +
8702
+ '2321111633211124432111322321121533211223232113143321132223211413332114212321151214121116241211243412113213212116' +
8703
+ '1412121533212132341212311321221523212223332122311321231414121413241214211321241323212421141216111412212424122132' +
8704
+ '1321312414122223241222311321322323213231132133221412242114123132132141321412323113214231323111154231112352311131' +
8705
+ '3231121442311222323113134231132132311412323115112322111533221123223121152322121433221222223122143231222233221321' +
8706
+ '2231231323221412223124122322151122312511141311152413112313222115141312143322213112313115132222142322222224131321' +
8707
+ '1231321422313222141314121231331313222412141315111322251114132123241321311322312314132222123141231322322214132321' +
8708
+ '1231422213223321141331311322413112315131414111145141112241411213514112214141131241411411323211144232112231412114' +
8709
+ '4141212242321221314122134141222131412312323214113141241123231114332311222232211423231213332312212141311422322213' +
8710
+ '3232222121413213314132212323141121413312223224112141341114141114241411221323211414141213241412211232311413232213' +
8711
+ '2323222111414114123232132232322114141411114142132141422113232411114143121414212213233122141422211232412213233221' +
8712
+ '1141512212324221114152214142111351421121414212124142131132331113423311213142211341422121314222123233131131422311' +
8713
+ '2324111333241121223321132324121221423113223322122324131121423212223323112142331114151113241511211324211323242121' +
8714
+ '1233311313242212141513111142411312333212132423111142421212333311114243111324312111425121414312113143211231432211' +
8715
+ '2234211221433112214332111325211212343112114341121143421115111116151112152511122315111314151114131511151215112124' +
8716
+ '1511222315112322151124211511313215113231242111152421121434211222242113133421132124211412242115111512111525121123' +
8717
+ '1421211524212123251212221421221424212222142123132421232114212412151215111421251115122123251221311421312324213131' +
8718
+ '1421322215122321142133211512313114214131333111143331121333311312333114112422111423312114333121223422122123312213' +
8719
+ '3331222123312312242214112331241115131114142221141513121325131221133131141422221315131312133132131422231215131411' +
8720
+ '1331331214222411151321221422312215132221133141221422322113314221424111134241121242411311333211133241211342412121' +
8721
+ '3241221233321311324123112423111334231121233221133332212122413113233222122423131122413212233223112241331115141113' +
8722
+ '2514112114232113242321211332311314232212151413111241411313323212142323111241421213323311151421211423312113324121' +
8723
+ '1241512151511112515112114242111241512112424212114151221133331112324221123333121131513112324222113151321124241112' +
8724
+ '2333211224241211224231122333221121514112',
8725
+ '5111112561111133411112165111122461111232411113155111132361111331411114145111142241111513511115214111161241112125' +
8726
+ '5111213361112141311122164111222451112232311123154111232351112331311124144111242231112513411125213111261231113125' +
8727
+ '4111313351113141211132163111322441113232211133153111332341113331211134143111342221113513311135212111361221114125' +
8728
+ '3111413341114141111142162111422431114232111143152111432331114331111144142111442211114513211145211111512521115133' +
8729
+ '3111514111115224211152321111532321115331111154221111613321116141111162321111633141121116511211246112113241121215' +
8730
+ '5112122361121231411213145112132241121413511214214112151241121611311221164112212451122132311222154112222351122231' +
8731
+ '3112231441122322311224134112242131122512311226112112311631123124411231322112321531123223411232312112331431123322' +
8732
+ '2112341331123421211235122112361111124116211241243112413211124215211242233112423111124314211243221112441321124421' +
8733
+ '1112451211125124211251321112522321125231111253221112542111126132111262314113111551131123611311314113121451131222' +
8734
+ '4113131351131321411314124113151131132115411321235113213131132214411322223113231341132321311324123113251121133115' +
8735
+ '3113312341133131211332143113322221133313311333212113341221133511111341152113412331134131111342142113422211134313' +
8736
+ '2113432111134412111345111113512321135131111352221113532111136131411411145114112241141213511412214114131241141411' +
8737
+ '3114211441142122311422134114222131142312311424112114311431143122211432133114322121143312211434111114411421144122' +
8738
+ '1114421321144221111443121114441111145122111452214115111351151121411512124115131131152113411521213115221231152311' +
8739
+ '2115311331153121211532122115331111154113211541211115421211154311411611124116121131162112311622112116311221163211' +
8740
+ '4211111652111124621111324211121552111223621112314211131452111322421114135211142142111512421116113211211642112124' +
8741
+ '5211213232112215421122235211223132112314421123223211241342112421321125123211261122113116321131244211313222113215' +
8742
+ '3211322342113231221133143211332222113413321134212211351222113611121141162211412432114132121142152211422332114231' +
8743
+ '1211431422114322121144132211442112114512121151242211513212115223221152311211532212115421121161321211623151211115' +
8744
+ '6121112311211164512112146121122211211263512113136121132111211362512114125121151142121115521211236212113141212115' +
8745
+ '4212121461212131412122145121222252121321412123134212141241212412421215114121251132122115421221235212213131213115' +
8746
+ '3212221442122222312132144121322242122321312133133212241231213412321225113121351122123115321231234212313121214115' +
8747
+ '2212321432123222212142143121422232123321212143132212341221214412221235112121451112124115221241233212413111215115' +
8748
+ '1212421422124222112152142121522222124321112153131212441211215412121245111212512322125131112161231212522211216222' +
8749
+ '1212532111216321121261315122111461221122112211635122121361221221112212625122131211221361512214114213111452131122' +
8750
+ '4122211442131213521312214122221351222221412223124213141141222411321321144213212231223114321322134213222131223213' +
8751
+ '4122322131223312321324113122341122133114321331222122411422133213321332212122421331224221212243122213341121224411' +
8752
+ '1213411422134122112251141213421322134221112252132122522111225312121344111122541112135122112261221213522111226221' +
8753
+ '5123111361231121112311625123121211231261512313114214111352141121412321135123212141232212421413114123231132142113' +
8754
+ '4214212131233113321422123123321232142311312333112214311332143121212341133123412121234212221433112123431112144113' +
8755
+ '2214412111235113121442121123521212144311112353111214512111236121512411121124116151241211421511124124211242151211' +
8756
+ '4124221132152112312431123215221131243211221531122124411222153211212442111215411211245112121542111124521151251111' +
8757
+ '4216111141252111321621113125311122163111212541114311111553111123631111314311121453111222431113135311132143111412' +
8758
+ '4311151133112115431121235311213133112214431122223311231343112321331124123311251123113115331131234311313123113214' +
8759
+ '3311322223113313331133212311341223113511131141152311412333114131131142142311422213114313231143211311441213114511' +
8760
+ '1311512323115131131152221311532113116131522111146221112212211163522112136221122112211262522113121221136152211411' +
8761
+ '4312111453121122422121144312121353121221422122135221222142212312431214114221241133122114431221223221311433122213' +
8762
+ '4312222132213213422132213221331233122411322134112312311433123122222141142312321333123221222142133221422122214312' +
8763
+ '2312341122214411131241142312412212215114131242132312422112215213222152211221531213124411122154111312512212216122' +
8764
+ '1312522112216221613111131131115421311162613112121131125321311261613113111131135211311451522211136222112112221162' +
8765
+ '5131211361312121113121621222126151312212522213111131226151312311431311135313112142222113431312124131311351313121' +
8766
+ '4313131141313212422223114131331133132113431321213222311333132212313141133222321233132311313142123222331131314311' +
8767
+ '2313311333133121222241132313321221315113222242122313331121315212222243112131531113134113231341211222511313134212' +
8768
+ '1131611312225212131343111131621212225311113163111313512112226121613211121132115321321161613212111132125211321351' +
8769
+ '5223111212231161513221125223121111322161513222114314111242232112431412114132311242232211413232113314211232233112' +
8770
+ '3314221131324112322332113132421123143112222341122314321121325112222342112132521113144112122351121314421111326112' +
8771
+ '1223521111326211613311111133115211331251522411115133211143151111422421114133311133152111322431113133411123153111' +
8772
+ '2224411121335111131541111224511111336111113411514411111454111122441112135411122144111312441114113411211444112122' +
8773
+ '3411221344112221341123123411241124113114341131222411321334113221241133122411341114114114241141221411421324114221' +
8774
+ '1411431214114411141151221411522153211113632111211321116253211212132112615321131144121113541211214321211344121212' +
8775
+ '4321221244121311432123113412211344122121332131133412221233213212341223113321331124123113341231212321411324123212' +
8776
+ '2321421224123311232143111412411324124121132151131412421213215212141243111321531114125121132161216231111212311153' +
8777
+ '2231116162311211123112521231135153221112132211615231211253221211123121615231221144131112432221124413121142313112' +
8778
+ '4322221142313211341321123322311234132211323141123322321132314211241331122322411224133211223151122322421122315211' +
8779
+ '1413411213225112141342111231611213225211123162111141114421411152114112432141125111411342114114416232111112321152' +
8780
+ '6141211111412152123212511141225153231111523221115141311144141111432321114232311141414111341421113323311132324111' +
8781
+ '3141511124143111232341112232511121416111141441111323511112326111114211432142115111421242114213411233115111422151' +
8782
+ '1143114211431241114411414511111345111212451113113511211345112121351122123511231125113113351131212511321225113311' +
8783
+ '1511411325114121151142121511431115115121542111121421116154211211451211124421211245121211442122113512211234213112' +
8784
+ '3512221134213211251231122421411225123211242142111512411214215112151242111421521163311111133111521331125154221111' +
8785
+ '5331211145131111442221114331311135132111342231113331411125133111242241112331511115134111142251111331611112411143' +
8786
+ '2241115112411242124113411332115112412151115111342151114211511233215112411151133211511431124211421151214212421241' +
8787
+ '1151224111521133215211411152123211521331124311411152214111531132115312311154113136112112361122112611311226113211' +
8788
+ '1611411216114211452121113612211135213111261231112521411116124111152151111431115113411142134112411251113322511141' +
8789
+ '1251123212511331134211411251214111611124216111321161122321611231116113221161142112521132116121321252123111612231' +
8790
+ '1162112321621131116212221162132112531131116221311163112211631221144111411351113213511231126111232261113112611222' +
8791
+ '1261132113521131126121311262112212621221',
8792
+ '2111115531111163111112462111125431111262111113452111135331111361111114442111145211111543611121141111215521112163' +
8793
+ '6111221311112254211122626111231211112353211123616111241111112452511131146111312211113163511132136111322111113262' +
8794
+ '5111331211113361511134114111411451114122411142135111422141114312411144113111511441115122311152134111522131115312' +
8795
+ '3111541121116114311161222111621331116221211163121112114621121154311211621112124521121253311212611112134421121352' +
8796
+ '1112144321121451111215426112211311122154211221626112221211122253211222616112231111122352111224515112311361123121' +
8797
+ '1112316251123212111232615112331141124113511241214112421241124311311251134112512131125212311253112112611331126121' +
8798
+ '2112621221126311111311452113115331131161111312442113125211131343211313511113144211131541611321121113215321132161' +
8799
+ '6113221111132252111323515113311211133161511332114113411241134211311351123113521121136112211362111114114421141152' +
8800
+ '1114124321141251111413421114144161142111111421521114225151143111411441113114511111151143211511511115124211151341' +
8801
+ '1115215111161142111612411211114622111154321111621211124522111253321112611211134422111352121114432211145112111542' +
8802
+ '6211211312112154221121626211221212112253221122616211231112112352121124515211311362113121121131625211321212113261' +
8803
+ '5211331142114113521141214211421242114311321151134211512132115212321153112211611332116121221162122211631121211145' +
8804
+ '3121115341211161112112362121124431211252112113352121134331211351112114342121144211211533212115411121163212121145' +
8805
+ '2212115332121161112121451212124422121252112122442121225222121351112123431212144211212442121215411121254162122112' +
8806
+ '1212215322122161612131126212221111213153121222526121321111213252121223511121335152123112121231615121411252123211' +
8807
+ '1121416151214211421241124121511242124211412152113212511231216112321252113121621122126112221262111122113621221144' +
8808
+ '3122115211221235212212433122125111221334212213421122143321221441112215321122163112131144221311521122214412131243' +
8809
+ '2213125111222243212222511122234212131441112224416213211112132152612231111122315212132251112232515213311151224111' +
8810
+ '4213411141225111321351113122611122136111112311352123114331231151112312342123124211231333212313411123143211231531' +
8811
+ '1214114322141151112321431214124211232242121413411123234112142151112331511124113421241142112412332124124111241332' +
8812
+ '1124143112151142112421421215124111242241112511332125114111251232112513311216114111252141112611321126123113111145' +
8813
+ '2311115333111161131112442311125213111343231113511311144213111541631121121311215323112161631122111311225213112351' +
8814
+ '5311311213113161531132114311411243114211331151123311521123116112231162111221113622211144322111521221123522211243' +
8815
+ '3221125112211334222113421221143322211441122115321221163113121144231211521221214413121243231212511221224322212251' +
8816
+ '1221234213121441122124416312211113122152622131111221315213122251122132515312311152214111431241114221511133125111' +
8817
+ '3221611123126111213111353131114341311151113112262131123431311242113113252131133331311341113114242131143211311523' +
8818
+ '2131153111311622122211352222114332221151113121351222123422221242113122342131224222221341113123331222143211312432' +
8819
+ '1222153111312531131311432313115112222143131312421131314312222242131313411131324212222341113133411313215112223151' +
8820
+ '1131415111321126213211343132114211321225213212333132124111321324213213321132142321321431113215221132162112231134' +
8821
+ '2223114211322134122312332223124111322233213222411132233212231431113224311314114212232142131412411132314212232241' +
8822
+ '1132324111331125213311333133114111331224213312321133132321331331113314221133152112241133222411411133213312241232' +
8823
+ '1133223212241331113323311315114112242141113331411134112421341132113412232134123111341322113414211225113211342132' +
8824
+ '1225123111342231113511232135113111351222113513211226113111352131113611221136122114111144241111521411124324111251' +
8825
+ '1411134214111441141121521411225154113111441141113411511124116111132111352321114333211151132112342321124213211333' +
8826
+ '2321134113211432132115311412114324121151132121431412124213212242141213411321234114122151132131511231112622311134' +
8827
+ '3231114212311225223112333231124112311324223113321231142322311431123115221231162113221134232211421231213413221233' +
8828
+ '2322124112312233132213321231233213221431123124311413114213222142141312411231314213222241123132412141112531411133' +
8829
+ '4141114111411216214112243141123211411315214113233141133111411414214114221141151321411521114116121232112522321133' +
8830
+ '3232114111412125123212242232123211412224214122322232133111412323123214221141242212321521114125211323113323231141' +
8831
+ '1232213313231232114131331232223213231331114132321232233111413331141411411323214112323141114141411142111621421124' +
8832
+ '3142113211421215214212233142123111421314214213221142141321421421114215121142161112331124223311321142212412331223' +
8833
+ '2233123111422223214222311142232212331421114224211324113212332132132412311142313212332231114232311143111521431123' +
8834
+ '3143113111431214214312221143131321431321114314121143151112341123223411311143212312341222114322221234132111432321' +
8835
+ '1325113112342131114331311144111421441122114412132144122111441312114414111235112211442122123512211144222111451113' +
8836
+ '2145112111451212114513111236112111452121151111432511115115111242151113411511215114211134242111421421123324211241' +
8837
+ '1421133214211431151211421421214215121241142122411331112523311133333111411331122423311232133113232331133113311422' +
8838
+ '1331152114221133242211411331213314221232133122321422133113312331151311411422214113313141124111162241112432411132' +
8839
+ '1241121522411223324112311241131422411322124114132241142112411512124116111332112423321132124121241332122323321231' +
8840
+ '1241222322412231124123221332142112412421142311321332213214231231124131321332223112413231215111153151112341511131' +
8841
+ '2151121431511222215113133151132121511412215115111242111522421123324211311151211512421214224212221151221421512222' +
8842
+ '2242132111512313124214121151241212421511115125111333112323331131124221231333122211513123124222221333132111513222' +
8843
+ '1242232111513321142411311333213112423131115141312152111431521122215212133152122121521312215214111243111422431122' +
8844
+ '1152211412431213224312211152221321522221115223121243141111522411133411221243212213341221115231221243222111523221' +
8845
+ '2153111331531121215312122153131112441113224411211153211312441212115322121244131111532311133511211244212111533121' +
8846
+ '2154111221541211124511121154211212451211115422111611114216111241152111332521114115211232152113311612114115212141' +
8847
+ '1431112424311132143112232431123114311322143114211522113214312132152212311431223113411115234111233341113113411214' +
8848
+ '2341122213411313234113211341141213411511143211232432113113412123234121311341222214321321134123211523113114322131' +
8849
+ '1341313122511114325111222251121332511221225113122251141113421114234211221251211422512122234212211251221313421312' +
8850
+ '1251231213421411125124111433112213422122143312211251312213422221125132213161111341611121316112123161131122521113' +
8851
+ '3252112121612113225212122161221222521311216123111343111323431121125221131343121211613113125222121343131111613212' +
8852
+ '1252231111613311143411211343212112523121116141213162111231621211225311122162211222531211216222111344111212532112' +
8853
+ '1344121111623112125322111162321131631111225411112163211113451111125421111163311116211132162112311531112325311131' +
8854
+ '1531122215311321162211311531213114411114244111221441121324411221144113121441141115321122144121221532122114412221' +
8855
+ '2351111333511121235112122351131114421113244211211351211323512121135122121442131113512311153311211442212113513121' +
8856
+ '3261111232611211235211122261211223521211226122111443111213522112144312111261311213522211126132113262111123531111' +
8857
+ '2262211114441111135321111262311116311122163112211541111325411121154112121541131116321121154121212451111224511211' +
8858
+ '1542111214512112154212111451221133611111',
8859
+ ]);
8860
+
8861
+ function patternFromWidths(sequence) {
8862
+ let pattern = 0;
8863
+ for (let element = 0; element < 8; element++) {
8864
+ const width = sequence.charCodeAt(element) - 48;
8865
+ const dark = (element & 1) === 0;
8866
+ for (let i = 0; i < width; i++) pattern = (pattern << 1) | (dark ? 1 : 0);
8867
+ }
8868
+ return pattern;
8869
+ }
8870
+
8871
+ /** Return the cluster discriminator for an eight-element bar/space sequence. */
8872
+ function pdf417ClusterForWidths(widths) {
8873
+ if (!widths || widths.length !== 8) throw new Error('PDF417: a character requires eight element widths');
8874
+ return ((widths[0] - widths[2] + widths[4] - widths[6]) % 9 + 9) % 9;
8875
+ }
8876
+
8877
+ function buildPatternTable() {
8878
+ const tables = WIDTH_SEQUENCES.map((source, tableIndex) => {
8879
+ if (source.length !== PDF417_CODEWORDS_PER_CLUSTER * 8) throw new Error('PDF417: corrupt pattern-table length');
8880
+ const expectedCluster = PDF417_CLUSTER_NUMBERS[tableIndex];
8881
+ const table = new Int32Array(PDF417_CODEWORDS_PER_CLUSTER);
8882
+ const seen = new Set();
8883
+ for (let codeword = 0; codeword < PDF417_CODEWORDS_PER_CLUSTER; codeword++) {
8884
+ const sequence = source.slice(codeword * 8, codeword * 8 + 8);
8885
+ const widths = Array.from(sequence, (digit) => digit.charCodeAt(0) - 48);
8886
+ if (widths.some((width) => width < 1 || width > 6) || widths.reduce((sum, width) => sum + width, 0) !== 17) {
8887
+ throw new Error('PDF417: corrupt pattern-table width');
8888
+ }
8889
+ if (pdf417ClusterForWidths(widths) !== expectedCluster) throw new Error('PDF417: corrupt pattern-table cluster');
8890
+ const pattern = patternFromWidths(sequence);
8891
+ if (seen.has(pattern)) throw new Error('PDF417: duplicate pattern in cluster');
8892
+ seen.add(pattern);
8893
+ table[codeword] = pattern;
8894
+ }
8895
+ return Object.freeze(Array.from(table));
8896
+ });
8897
+ return Object.freeze(tables);
8898
+ }
8899
+
8900
+ /** Pattern table indexed by cluster index (0, 1, 2) and codeword value. */
8901
+ const PDF417_PATTERN_TABLE = buildPatternTable();
8902
+ const PATTERN_TO_CODEWORD = new Map();
8903
+ for (let index = 0; index < PDF417_PATTERN_TABLE.length; index++) {
8904
+ for (let codeword = 0; codeword < PDF417_CODEWORDS_PER_CLUSTER; codeword++) {
8905
+ PATTERN_TO_CODEWORD.set(PDF417_PATTERN_TABLE[index][codeword], Object.freeze({
8906
+ codeword, cluster: PDF417_CLUSTER_NUMBERS[index],
8907
+ }));
8908
+ }
8909
+ }
8910
+
8911
+ /**
8912
+ * Return the 17-bit bar/space pattern for a codeword in a row cluster.
8913
+ * @param {number} codeword
8914
+ * @param {number} cluster Cluster number 0, 3 or 6.
8915
+ * @returns {number}
8916
+ */
8917
+ function pdf417PatternForCodeword(codeword, cluster) {
8918
+ if (!Number.isInteger(codeword) || codeword < 0 || codeword >= PDF417_CODEWORDS_PER_CLUSTER) throw new Error('PDF417: codeword must be in 0..928');
8919
+ const index = PDF417_CLUSTER_NUMBERS.indexOf(cluster);
8920
+ if (index < 0) throw new Error('PDF417: cluster must be 0, 3 or 6');
8921
+ return PDF417_PATTERN_TABLE[index][codeword];
8922
+ }
8923
+
8924
+ /**
8925
+ * Decode an exact 17-bit symbol-character pattern to its codeword and cluster.
8926
+ * @param {number} pattern
8927
+ * @returns {{codeword: number, cluster: number} | null}
8928
+ */
8929
+ function pdf417CodewordForPattern(pattern) {
8930
+ const result = PATTERN_TO_CODEWORD.get(pattern);
8931
+ return result ? { ...result } : null;
8932
+ }
8933
+
8934
+ __exports.PDF417_CLUSTER_NUMBERS = PDF417_CLUSTER_NUMBERS;
8935
+ __exports.PDF417_CODEWORDS_PER_CLUSTER = PDF417_CODEWORDS_PER_CLUSTER;
8936
+ __exports.pdf417ClusterForWidths = pdf417ClusterForWidths;
8937
+ __exports.PDF417_PATTERN_TABLE = PDF417_PATTERN_TABLE;
8938
+ __exports.pdf417PatternForCodeword = pdf417PatternForCodeword;
8939
+ __exports.pdf417CodewordForPattern = pdf417CodewordForPattern;
8940
+ };
8941
+
8942
+ __modules["pdf417/encoder.js"] = function (__require, __exports) {
8943
+ const { BitMatrix } = __require("core/bit-matrix.js");
8944
+ const { EncodeError } = __require("core/errors.js");
8945
+ const { compactPdf417 } = __require("pdf417/compaction.js");
8946
+ const { pdf417ErrorCorrection, pdf417EccLength } = __require("pdf417/error-correction.js");
8947
+ const { pdf417PatternForCodeword } = __require("pdf417/tables.js");
8948
+
8949
+ const START = '81111113';
8950
+ const STOP = '711311121';
8951
+
8952
+ function append(matrix, y, x, sequence, height) {
8953
+ let dark = true;
8954
+ for (const digit of sequence) {
8955
+ const width = digit.charCodeAt(0) - 48;
8956
+ if (dark) matrix.setRegion(x, y, width, height);
8957
+ x += width; dark = !dark;
8958
+ }
8959
+ return x;
8960
+ }
8961
+ function patternSequence(pattern) { return pattern.toString(2).padStart(17, '0').replace(/0+|1+/g, (run) => String(run.length)); }
8962
+ function indicators(row, rows, cols, level) {
8963
+ const group = Math.floor(row / 3), y = Math.floor((rows - 1) / 3), z = level * 3 + (rows - 1) % 3, v = cols - 1;
8964
+ if (row % 3 === 0) return [30 * group + y, 30 * group + v];
8965
+ if (row % 3 === 1) return [30 * group + z, 30 * group + y];
8966
+ return [30 * group + v, 30 * group + z];
8967
+ }
8968
+ function dimensions(needed, level, options) {
8969
+ for (const [name, value, min, max] of [['rows', options.rows, 3, 90], ['columns', options.columns, 1, 30]]) {
8970
+ if (value !== undefined && (!Number.isInteger(value) || value < min || value > max)) throw new EncodeError(`PDF417: ${name} must be an integer in ${min}..${max}`);
8971
+ }
8972
+ if (options.aspectRatio !== undefined && (!Number.isFinite(options.aspectRatio) || options.aspectRatio <= 0)) throw new EncodeError('PDF417: aspectRatio must be positive');
8973
+ const ecc = pdf417EccLength(level); let best = null;
8974
+ for (let rows = options.rows ?? 3; rows <= (options.rows ?? 90); rows++) for (let cols = options.columns ?? 1; cols <= (options.columns ?? 30); cols++) {
8975
+ if (rows < 3 || rows * cols > 928 || rows * cols - ecc < needed) continue;
8976
+ const ratio = (69 + cols * 17) / (rows * (options.rowHeight ?? 3));
8977
+ const score = (rows * cols - ecc - needed) * 10 + Math.abs(ratio - (options.aspectRatio ?? 3));
8978
+ if (!best || score < best.score) best = { rows, cols, score };
8979
+ }
8980
+ if (!best) throw new EncodeError('PDF417: payload does not fit the requested dimensions and error correction level');
8981
+ return best;
8982
+ }
8983
+ function encodePDF417(value, options = {}) {
8984
+ const level = options.eccLevel ?? 2, rowHeight = options.rowHeight ?? 3;
8985
+ if (!Number.isInteger(rowHeight) || rowHeight < 3) throw new EncodeError('PDF417: rowHeight must be an integer of at least 3');
8986
+ const payload = compactPdf417(value, { compaction: options.compaction });
8987
+ const { rows, cols } = dimensions(payload.length + 1, level, { ...options, rowHeight });
8988
+ const eccLength = pdf417EccLength(level), dataLength = rows * cols - eccLength;
8989
+ const data = [dataLength, ...payload]; while (data.length < dataLength) data.push(900);
8990
+ const codewords = data.concat(pdf417ErrorCorrection(data, level));
8991
+ const matrix = new BitMatrix(69 + cols * 17, rows * rowHeight);
8992
+ for (let row = 0; row < rows; row++) {
8993
+ const y = row * rowHeight, cluster = (row % 3) * 3, [left, right] = indicators(row, rows, cols, level);
8994
+ let x = append(matrix, y, 0, START, rowHeight);
8995
+ x = append(matrix, y, x, patternSequence(pdf417PatternForCodeword(left, cluster)), rowHeight);
8996
+ for (let col = 0; col < cols; col++) x = append(matrix, y, x, patternSequence(pdf417PatternForCodeword(codewords[row * cols + col], cluster)), rowHeight);
8997
+ x = append(matrix, y, x, patternSequence(pdf417PatternForCodeword(right, cluster)), rowHeight);
8998
+ append(matrix, y, x, STOP, rowHeight);
8999
+ }
9000
+ matrix.pdf417 = { rows, columns: cols, eccLevel: level, rowHeight, codewords };
9001
+ return matrix;
9002
+ }
9003
+
9004
+ __exports.encodePDF417 = encodePDF417;
9005
+ };
9006
+
9007
+ __modules["pdf417/decoder.js"] = function (__require, __exports) {
9008
+ const { FormatError } = __require("core/errors.js");
9009
+ const { decodePdf417CompactionDetailed } = __require("pdf417/compaction.js");
9010
+ const { pdf417CorrectErrors, pdf417EccLength } = __require("pdf417/error-correction.js");
9011
+ const { pdf417CodewordForPattern } = __require("pdf417/tables.js");
9012
+
9013
+ const START = '11111111010101000';
9014
+ const STOP = '111111101000101001';
9015
+ function bits(matrix, y, x, width) { let value = 0; for (let i = 0; i < width; i++) value = (value << 1) | (matrix.get(x + i, y) ? 1 : 0); return value; }
9016
+ function indicators(row, rows, cols, level) { const group = Math.floor(row / 3), y = Math.floor((rows - 1) / 3), z = level * 3 + (rows - 1) % 3, v = cols - 1; return row % 3 === 0 ? [30 * group + y, 30 * group + v] : row % 3 === 1 ? [30 * group + z, 30 * group + y] : [30 * group + v, 30 * group + z]; }
9017
+ function decodePDF417(matrix, options = {}) {
9018
+ if (!matrix?.width || !matrix?.height || (matrix.width - 69) % 17) throw new FormatError('PDF417: invalid matrix dimensions');
9019
+ const cols = (matrix.width - 69) / 17, rowHeight = options.rowHeight ?? matrix.pdf417?.rowHeight ?? 3;
9020
+ if (!Number.isInteger(rowHeight) || matrix.height % rowHeight) throw new FormatError('PDF417: invalid row height');
9021
+ const rows = matrix.height / rowHeight;
9022
+ if (rows < 3 || rows > 90 || cols < 1 || cols > 30) throw new FormatError('PDF417: dimensions outside the standard range');
9023
+ const all = [];
9024
+ const erasures = [];
9025
+ for (let row = 0; row < rows; row++) {
9026
+ const y = row * rowHeight, cluster = (row % 3) * 3;
9027
+ if (bits(matrix, y, 0, 17).toString(2).padStart(17, '0') !== START || bits(matrix, y, matrix.width - 18, 18).toString(2).padStart(18, '0') !== STOP) throw new FormatError('PDF417: missing start or stop pattern');
9028
+ const read = (x) => { const result = pdf417CodewordForPattern(bits(matrix, y, x, 17)); if (!result || result.cluster !== cluster) throw new FormatError('PDF417: invalid codeword pattern'); return result.codeword; };
9029
+ const left = read(17), right = read(34 + cols * 17);
9030
+ let matched = false; for (let level = 0; level <= 8; level++) { const expected = indicators(row, rows, cols, level); if (left === expected[0] && right === expected[1]) { matched = true; break; } }
9031
+ if (!matched) throw new FormatError('PDF417: row indicator mismatch');
9032
+ for (let col = 0; col < cols; col++) {
9033
+ try { all.push(read(34 + col * 17)); }
9034
+ catch {
9035
+ erasures.push(all.length);
9036
+ all.push(0);
9037
+ }
9038
+ }
9039
+ }
9040
+ let level = -1; for (let candidate = 0; candidate <= 8; candidate++) if (all.length > pdf417EccLength(candidate)) { level = candidate; break; }
9041
+ // The row indicators determine the level uniquely across the symbol.
9042
+ for (let candidate = 0; candidate <= 8; candidate++) {
9043
+ let ok = true; for (let row = 0; row < rows; row++) { const y = row * rowHeight, cluster = (row % 3) * 3, expected = indicators(row, rows, cols, candidate); const left = pdf417CodewordForPattern(bits(matrix, y, 17, 17)); const right = pdf417CodewordForPattern(bits(matrix, y, 34 + cols * 17, 17)); if (!left || !right || left.cluster !== cluster || right.cluster !== cluster || left.codeword !== expected[0] || right.codeword !== expected[1]) { ok = false; break; } } if (ok) { level = candidate; break; }
9044
+ }
9045
+ if (level < 0) throw new FormatError('PDF417: could not determine error correction level');
9046
+ const corrected = all.slice(); const corrections = pdf417CorrectErrors(corrected, level, erasures);
9047
+ const length = corrected[0]; if (length < 1 || length > corrected.length - pdf417EccLength(level)) throw new FormatError('PDF417: invalid symbol length descriptor');
9048
+ const payload = corrected.slice(1, length);
9049
+ const decoded = decodePdf417CompactionDetailed(payload);
9050
+ return { ...decoded, codewords: corrected, rows, columns: cols, eccLevel: level, corrections };
9051
+ }
9052
+
9053
+ __exports.decodePDF417 = decodePDF417;
9054
+ };
9055
+
9056
+ __modules["pdf417/detector.js"] = function (__require, __exports) {
9057
+ const { BitMatrix } = __require("core/bit-matrix.js");
9058
+ const { sampleGrid, sampleGridVoting } = __require("image/grid-sampler.js");
9059
+ const { PerspectiveTransform } = __require("image/perspective.js");
9060
+ const { decodePDF417 } = __require("pdf417/decoder.js");
9061
+
9062
+ const START_PATTERN = [8, 1, 1, 1, 1, 1, 1, 3];
9063
+ const STOP_PATTERN = [7, 1, 1, 3, 1, 1, 1, 2, 1];
9064
+ const SCAN_ANGLES = [0, -4, 4, -8, 8, -14, 14, -22, 22, -32, 32]
9065
+ .map((degrees) => degrees * Math.PI / 180);
9066
+
9067
+ function rotateClockwise(source) {
9068
+ const rotated = new BitMatrix(source.height, source.width);
9069
+ for (let y = 0; y < source.height; y++) for (let x = 0; x < source.width; x++) {
9070
+ if (source.get(x, y)) rotated.set(source.height - 1 - y, x);
9071
+ }
9072
+ return rotated;
9073
+ }
9074
+
9075
+ function scanGeometry(angle) {
9076
+ return {
9077
+ along: { x: Math.cos(angle), y: Math.sin(angle) },
9078
+ across: { x: -Math.sin(angle), y: Math.cos(angle) },
9079
+ };
9080
+ }
9081
+
9082
+ function projectionRange(image, vector) {
9083
+ const points = [
9084
+ { x: 0, y: 0 }, { x: image.width - 1, y: 0 },
9085
+ { x: image.width - 1, y: image.height - 1 }, { x: 0, y: image.height - 1 },
9086
+ ];
9087
+ const values = points.map((point) => point.x * vector.x + point.y * vector.y);
9088
+ return { min: Math.min(...values), max: Math.max(...values) };
9089
+ }
9090
+
9091
+ function lineRange(image, geometry, across) {
9092
+ const { along, across: normal } = geometry;
9093
+ let min = -Infinity, max = Infinity;
9094
+ const constrain = (low, high, step, offset) => {
9095
+ if (Math.abs(step) < 1e-9) return offset >= low && offset <= high;
9096
+ const first = (low - offset) / step, second = (high - offset) / step;
9097
+ min = Math.max(min, Math.min(first, second));
9098
+ max = Math.min(max, Math.max(first, second));
9099
+ return min <= max;
9100
+ };
9101
+ if (!constrain(0, image.width - 1, along.x, normal.x * across) ||
9102
+ !constrain(0, image.height - 1, along.y, normal.y * across)) return null;
9103
+ return { min: Math.ceil(min), max: Math.floor(max) };
9104
+ }
9105
+
9106
+ function runsInLine(image, geometry, across) {
9107
+ const range = lineRange(image, geometry, across);
9108
+ if (!range || range.max < range.min) return [];
9109
+ const { along, across: normal } = geometry;
9110
+ const runs = [];
9111
+ const valueAt = (position) => image.get(
9112
+ Math.round(along.x * position + normal.x * across),
9113
+ Math.round(along.y * position + normal.y * across),
9114
+ );
9115
+ let dark = valueAt(range.min), start = range.min;
9116
+ for (let position = range.min + 1; position <= range.max + 1; position++) {
9117
+ const value = position <= range.max ? valueAt(position) : !dark;
9118
+ if (value !== dark) {
9119
+ runs.push({ dark, start, end: position, length: position - start });
9120
+ start = position; dark = value;
9121
+ }
9122
+ }
9123
+ return runs;
9124
+ }
9125
+
9126
+ function removeSinglePixelSpecks(runs) {
9127
+ const clean = runs.map((run) => ({ ...run }));
9128
+ for (let index = 1; index < clean.length - 1;) {
9129
+ if (clean[index].length > 1) { index++; continue; }
9130
+ const merged = {
9131
+ dark: clean[index - 1].dark,
9132
+ start: clean[index - 1].start,
9133
+ end: clean[index + 1].end,
9134
+ length: clean[index - 1].length + clean[index].length + clean[index + 1].length,
9135
+ };
9136
+ clean.splice(index - 1, 3, merged);
9137
+ index = Math.max(1, index - 2);
9138
+ }
9139
+ return clean;
9140
+ }
9141
+
9142
+ function matchPattern(runs, at, expected) {
9143
+ if (at + expected.length > runs.length || !runs[at].dark) return null;
9144
+ let observed = 0, modules = 0;
9145
+ for (let i = 0; i < expected.length; i++) { observed += runs[at + i].length; modules += expected[i]; }
9146
+ const scale = observed / modules;
9147
+ if (scale < 0.65) return null;
9148
+ let error = 0;
9149
+ for (let i = 0; i < expected.length; i++) {
9150
+ const delta = Math.abs(runs[at + i].length - expected[i] * scale);
9151
+ if (delta > Math.max(1.15, scale * 0.62)) return null;
9152
+ error += delta / scale;
9153
+ }
9154
+ if (error / expected.length > 0.48) return null;
9155
+ return { start: runs[at].start, end: runs[at + expected.length - 1].end, scale, error, at };
9156
+ }
9157
+
9158
+ function quietPenalty(runs, start, stop) {
9159
+ const before = start.at > 0 ? runs[start.at - 1].length / start.scale : 0;
9160
+ const afterIndex = stop.at + STOP_PATTERN.length;
9161
+ const after = afterIndex < runs.length ? runs[afterIndex].length / stop.scale : 0;
9162
+ return Math.max(0, 2 - before) + Math.max(0, 2 - after);
9163
+ }
9164
+
9165
+ function patternPairs(runs) {
9166
+ const starts = [], stops = [];
9167
+ for (let at = 0; at < runs.length; at++) {
9168
+ const start = matchPattern(runs, at, START_PATTERN); if (start) starts.push(start);
9169
+ const stop = matchPattern(runs, at, STOP_PATTERN); if (stop) stops.push(stop);
9170
+ }
9171
+ const pairs = [];
9172
+ for (const start of starts) for (const stop of stops) {
9173
+ if (stop.start <= start.end) continue;
9174
+ const measured = stop.end - start.start;
9175
+ const localScale = Math.sqrt(start.scale * stop.scale);
9176
+ const roughColumns = Math.round((measured / localScale - 69) / 17);
9177
+ for (let columns = Math.max(1, roughColumns - 2); columns <= Math.min(30, roughColumns + 2); columns++) {
9178
+ const width = 69 + columns * 17;
9179
+ const globalScale = measured / width;
9180
+ const ratio = Math.max(start.scale, stop.scale, globalScale) /
9181
+ Math.min(start.scale, stop.scale, globalScale);
9182
+ if (ratio > 1.85) continue;
9183
+ const scaleError = Math.abs(Math.log(start.scale / globalScale)) +
9184
+ Math.abs(Math.log(stop.scale / globalScale));
9185
+ pairs.push({ start, stop, columns, width, scale: globalScale,
9186
+ startScale: start.scale, stopScale: stop.scale,
9187
+ error: start.error + stop.error + scaleError * 4 + quietPenalty(runs, start, stop) * 0.15 });
9188
+ }
9189
+ }
9190
+ pairs.sort((a, b) => a.error - b.error);
9191
+ const used = new Set();
9192
+ return pairs.filter((pair) => {
9193
+ if (used.has(pair.columns)) return false;
9194
+ used.add(pair.columns);
9195
+ return used.size <= 3;
9196
+ });
9197
+ }
9198
+
9199
+ function pointAt(geometry, along, across) {
9200
+ return {
9201
+ x: geometry.along.x * along + geometry.across.x * across,
9202
+ y: geometry.along.y * along + geometry.across.y * across,
9203
+ };
9204
+ }
9205
+
9206
+ function scanHits(image, angle) {
9207
+ const geometry = scanGeometry(angle);
9208
+ const range = projectionRange(image, geometry.across);
9209
+ const hits = [];
9210
+ for (let across = Math.ceil(range.min); across <= Math.floor(range.max); across++) {
9211
+ const raw = runsInLine(image, geometry, across);
9212
+ let pairs = patternPairs(raw);
9213
+ if (!pairs.length) pairs = patternPairs(removeSinglePixelSpecks(raw));
9214
+ for (const pair of pairs) {
9215
+ hits.push({ across, left: pair.start.start, right: pair.stop.end,
9216
+ leftPoint: pointAt(geometry, pair.start.start, across),
9217
+ rightPoint: pointAt(geometry, pair.stop.end, across),
9218
+ scale: pair.scale, startScale: pair.startScale, stopScale: pair.stopScale,
9219
+ columns: pair.columns, width: pair.width, error: pair.error,
9220
+ geometry });
9221
+ }
9222
+ }
9223
+ return hits;
9224
+ }
9225
+
9226
+ function fittedLine(hits, key) {
9227
+ const meanX = hits.reduce((sum, hit) => sum + hit.across, 0) / hits.length;
9228
+ const meanY = hits.reduce((sum, hit) => sum + hit[key], 0) / hits.length;
9229
+ let covariance = 0, variance = 0;
9230
+ for (const hit of hits) {
9231
+ const delta = hit.across - meanX;
9232
+ covariance += delta * (hit[key] - meanY);
9233
+ variance += delta * delta;
9234
+ }
9235
+ const slope = variance ? covariance / variance : 0;
9236
+ return { slope, intercept: meanY - slope * meanX };
9237
+ }
9238
+
9239
+ function lineValue(line, at) {
9240
+ return line.intercept + line.slope * at;
9241
+ }
9242
+
9243
+ function finderExtent(image, hits, edgeKey, scaleKey, centreModules, fallback) {
9244
+ const geometry = hits[0].geometry;
9245
+ const edge = fittedLine(hits, edgeKey), scale = fittedLine(hits, scaleKey);
9246
+ const span = fallback.bottom - fallback.top;
9247
+ const projection = projectionRange(image, geometry.across);
9248
+ const margin = Math.max(6, span * 0.35, hits[0].scale * 4);
9249
+ const start = Math.max(Math.ceil(projection.min), Math.floor(fallback.top - margin));
9250
+ const end = Math.min(Math.floor(projection.max), Math.ceil(fallback.bottom + margin));
9251
+ const values = [];
9252
+ for (let across = start; across <= end; across++) {
9253
+ const localScale = Math.max(0.5, lineValue(scale, across));
9254
+ const centre = lineValue(edge, across) + localScale * centreModules;
9255
+ let dark = 0;
9256
+ for (const offset of [-0.75, 0, 0.75]) {
9257
+ const point = pointAt(geometry, centre + localScale * offset, across);
9258
+ if (image.get(Math.round(point.x), Math.round(point.y))) dark++;
9259
+ }
9260
+ values.push({ across, dark: dark >= 2 });
9261
+ }
9262
+ const segments = [];
9263
+ let first = null, lastDark = null, gap = 0;
9264
+ for (const value of values) {
9265
+ if (value.dark) {
9266
+ if (first === null) first = value.across;
9267
+ lastDark = value.across; gap = 0;
9268
+ } else if (first !== null && ++gap > 2) {
9269
+ segments.push({ top: first, bottom: lastDark + 1 });
9270
+ first = null; lastDark = null; gap = 0;
9271
+ }
9272
+ }
9273
+ if (first !== null) segments.push({ top: first, bottom: lastDark + 1 });
9274
+ let best = null, bestScore = -Infinity;
9275
+ for (const segment of segments) {
9276
+ const overlap = Math.max(0, Math.min(segment.bottom, fallback.bottom) - Math.max(segment.top, fallback.top));
9277
+ const score = overlap * 4 + (segment.bottom - segment.top) -
9278
+ Math.abs((segment.top + segment.bottom) / 2 - (fallback.top + fallback.bottom) / 2);
9279
+ if (overlap >= span * 0.55 && score > bestScore) { best = segment; bestScore = score; }
9280
+ }
9281
+ return best ?? fallback;
9282
+ }
9283
+
9284
+ function intersectBoundary(leftAcross, rightAcross, leftCentre, rightCentre, leftEdge, rightEdge) {
9285
+ const delta = rightCentre - leftCentre;
9286
+ if (Math.abs(delta) < 1e-6) return { left: leftAcross, right: rightAcross };
9287
+ const slope = (rightAcross - leftAcross) / delta;
9288
+ const intercept = leftAcross - slope * leftCentre;
9289
+ const atEdge = (edge, fallback) => {
9290
+ const denominator = 1 - slope * edge.slope;
9291
+ return Math.abs(denominator) < 1e-6 ? fallback :
9292
+ (slope * edge.intercept + intercept) / denominator;
9293
+ };
9294
+ return { left: atEdge(leftEdge, leftAcross), right: atEdge(rightEdge, rightAcross) };
9295
+ }
9296
+
9297
+ function groupHits(hits, image) {
9298
+ const groups = [];
9299
+ for (const hit of hits.sort((a, b) => a.across - b.across || a.error - b.error)) {
9300
+ let best = null, bestDistance = Infinity;
9301
+ for (const group of groups) {
9302
+ const last = group.hits[group.hits.length - 1];
9303
+ const gap = hit.across - last.across;
9304
+ if (hit.columns !== last.columns || gap <= 0 || gap > Math.max(5, hit.scale * 3)) continue;
9305
+ const scaleRatio = Math.max(hit.scale, last.scale) / Math.min(hit.scale, last.scale);
9306
+ if (scaleRatio > 1.45) continue;
9307
+ const tolerance = Math.max(5, hit.scale * 4 + gap);
9308
+ const distance = Math.abs(hit.left - last.left) + Math.abs(hit.right - last.right);
9309
+ if (distance > tolerance * 2 || distance >= bestDistance) continue;
9310
+ best = group; bestDistance = distance;
9311
+ }
9312
+ if (best) best.hits.push(hit); else groups.push({ hits: [hit] });
9313
+ }
9314
+ const candidates = [];
9315
+ for (const group of groups) {
9316
+ const rows = group.hits;
9317
+ const scale = rows.reduce((sum, hit) => sum + hit.scale, 0) / rows.length;
9318
+ const top = rows[0].across, bottom = rows[rows.length - 1].across + 1;
9319
+ const span = bottom - top;
9320
+ if (rows.length < 4 || span < Math.max(6, scale * 4) || rows.length / span < 0.28) continue;
9321
+ const geometry = rows[0].geometry;
9322
+ const left = fittedLine(rows, 'left'), right = fittedLine(rows, 'right');
9323
+ const startScale = fittedLine(rows, 'startScale'), stopScale = fittedLine(rows, 'stopScale');
9324
+ const fallback = { top, bottom };
9325
+ const leftExtent = image ? finderExtent(image, rows, 'left', 'startScale', 4, fallback) : fallback;
9326
+ const rightExtent = image ? finderExtent(image, rows, 'right', 'stopScale', -14.5, fallback) : fallback;
9327
+ const boundary = (leftAcross, rightAcross) => intersectBoundary(
9328
+ leftAcross,
9329
+ rightAcross,
9330
+ lineValue(left, leftAcross) + lineValue(startScale, leftAcross) * 4,
9331
+ lineValue(right, rightAcross) - lineValue(stopScale, rightAcross) * 14.5,
9332
+ left,
9333
+ right,
9334
+ );
9335
+ const topBoundary = boundary(leftExtent.top, rightExtent.top);
9336
+ const bottomBoundary = boundary(leftExtent.bottom, rightExtent.bottom);
9337
+ candidates.push({
9338
+ width: rows[0].width, scale,
9339
+ corners: [
9340
+ pointAt(geometry, lineValue(left, topBoundary.left), topBoundary.left),
9341
+ pointAt(geometry, lineValue(right, topBoundary.right), topBoundary.right),
9342
+ pointAt(geometry, lineValue(right, bottomBoundary.right), bottomBoundary.right),
9343
+ pointAt(geometry, lineValue(left, bottomBoundary.left), bottomBoundary.left),
9344
+ ],
9345
+ score: rows.length / span * 8 + Math.log2(rows.length + 1) * 2 -
9346
+ rows.reduce((sum, hit) => sum + hit.error, 0) / rows.length,
9347
+ });
9348
+ }
9349
+ return candidates.sort((a, b) => b.score - a.score);
9350
+ }
9351
+
9352
+ function validQuadrilateral(value) {
9353
+ return Array.isArray(value) && value.length === 4 &&
9354
+ value.every((point) => Number.isFinite(point?.x) && Number.isFinite(point?.y));
9355
+ }
9356
+
9357
+ function manualCandidate(corners) {
9358
+ const horizontal = (Math.hypot(corners[1].x - corners[0].x, corners[1].y - corners[0].y) +
9359
+ Math.hypot(corners[2].x - corners[3].x, corners[2].y - corners[3].y)) / 2;
9360
+ const vertical = (Math.hypot(corners[3].x - corners[0].x, corners[3].y - corners[0].y) +
9361
+ Math.hypot(corners[2].x - corners[1].x, corners[2].y - corners[1].y)) / 2;
9362
+ const out = [];
9363
+ for (let columns = 1; columns <= 30; columns++) {
9364
+ const width = 69 + columns * 17, scale = horizontal / width;
9365
+ if (scale < 0.65) continue;
9366
+ const moduleHeight = vertical / scale;
9367
+ let plausibility = Infinity;
9368
+ for (let rowHeight = 3; rowHeight <= 12; rowHeight++) {
9369
+ const rows = Math.round(moduleHeight / rowHeight);
9370
+ if (rows >= 3 && rows <= 90) plausibility = Math.min(plausibility,
9371
+ Math.abs(moduleHeight - rows * rowHeight) / rowHeight);
9372
+ }
9373
+ out.push({ width, scale, corners, score: Number.isFinite(plausibility) ? 2 - plausibility : 0 });
9374
+ }
9375
+ return out.sort((a, b) => b.score - a.score);
9376
+ }
9377
+
9378
+ function edgeLength(first, second) {
9379
+ return Math.hypot(second.x - first.x, second.y - first.y);
9380
+ }
9381
+
9382
+ function rowCandidates(candidate, options) {
9383
+ const vertical = (edgeLength(candidate.corners[0], candidate.corners[3]) +
9384
+ edgeLength(candidate.corners[1], candidate.corners[2])) / 2;
9385
+ const allowedHeights = Number.isInteger(options.rowHeight) ? [options.rowHeight] :
9386
+ Array.from({ length: 10 }, (_, index) => index + 3);
9387
+ const rows = [];
9388
+ for (let value = 3; value <= 90; value++) {
9389
+ let score = Infinity;
9390
+ for (const rowHeight of allowedHeights) {
9391
+ score = Math.min(score, Math.abs(Math.log(vertical / (candidate.scale * value * rowHeight))));
9392
+ }
9393
+ rows.push({ value, score });
9394
+ }
9395
+ return rows.sort((a, b) => a.score - b.score).map((entry) => entry.value);
9396
+ }
9397
+
9398
+ function shiftedCandidate(candidate, amount) {
9399
+ if (!amount) return candidate;
9400
+ const topDx = candidate.corners[3].x - candidate.corners[0].x;
9401
+ const topDy = candidate.corners[3].y - candidate.corners[0].y;
9402
+ const bottomDx = candidate.corners[2].x - candidate.corners[1].x;
9403
+ const bottomDy = candidate.corners[2].y - candidate.corners[1].y;
9404
+ const topLength = Math.hypot(topDx, topDy) || 1;
9405
+ const bottomLength = Math.hypot(bottomDx, bottomDy) || 1;
9406
+ return { ...candidate, corners: [
9407
+ { x: candidate.corners[0].x - topDx / topLength * amount, y: candidate.corners[0].y - topDy / topLength * amount },
9408
+ { x: candidate.corners[1].x - bottomDx / bottomLength * amount, y: candidate.corners[1].y - bottomDy / bottomLength * amount },
9409
+ { x: candidate.corners[2].x + bottomDx / bottomLength * amount, y: candidate.corners[2].y + bottomDy / bottomLength * amount },
9410
+ { x: candidate.corners[3].x + topDx / topLength * amount, y: candidate.corners[3].y + topDy / topLength * amount },
9411
+ ] };
9412
+ }
9413
+
9414
+ function canonicalRows(matrix) {
9415
+ const rowHeight = 3;
9416
+ const out = new BitMatrix(matrix.width, matrix.height * rowHeight);
9417
+ for (let y = 0; y < matrix.height; y++) for (let x = 0; x < matrix.width; x++) {
9418
+ if (matrix.get(x, y)) out.setRegion(x, y * rowHeight, 1, rowHeight);
9419
+ }
9420
+ return out;
9421
+ }
9422
+
9423
+ function sampleCandidate(image, candidate, options) {
9424
+ for (const edgeShift of [0, candidate.scale * 0.35, -candidate.scale * 0.25]) {
9425
+ const geometry = shiftedCandidate(candidate, edgeShift);
9426
+ for (const rows of rowCandidates(geometry, options)) {
9427
+ const transform = PerspectiveTransform.quadToQuad(0, 0, geometry.width, 0, geometry.width, rows, 0, rows,
9428
+ geometry.corners[0].x, geometry.corners[0].y, geometry.corners[1].x, geometry.corners[1].y,
9429
+ geometry.corners[2].x, geometry.corners[2].y, geometry.corners[3].x, geometry.corners[3].y);
9430
+ for (const voting of [false, true]) {
9431
+ let matrix;
9432
+ try { matrix = voting ? sampleGridVoting(image, geometry.width, rows, transform) : sampleGrid(image, geometry.width, rows, transform); }
9433
+ catch { continue; }
9434
+ try {
9435
+ const result = decodePDF417(matrix, { ...options, rowHeight: 1 });
9436
+ return { matrix: canonicalRows(matrix), result, corners: geometry.corners };
9437
+ }
9438
+ catch { /* Try the next geometry. */ }
9439
+ }
9440
+ }
9441
+ }
9442
+ return null;
9443
+ }
9444
+
9445
+ function automaticCandidates(image) {
9446
+ const out = [];
9447
+ for (const angle of SCAN_ANGLES) {
9448
+ out.push(...groupHits(scanHits(image, angle), image));
9449
+ if (out.length) break;
9450
+ }
9451
+ return out;
9452
+ }
9453
+
9454
+ function detectInOrientation(image, options, supplied) {
9455
+ for (const candidate of [...supplied, ...automaticCandidates(image)]) {
9456
+ const decoded = sampleCandidate(image, candidate, options);
9457
+ if (decoded) return { candidate, decoded };
9458
+ }
9459
+ if (supplied.length) return null;
9460
+ for (const angle of SCAN_ANGLES.slice(1)) {
9461
+ const candidates = groupHits(scanHits(image, angle), image);
9462
+ for (const candidate of candidates) {
9463
+ const decoded = sampleCandidate(image, candidate, options);
9464
+ if (decoded) return { candidate, decoded };
9465
+ }
9466
+ }
9467
+ return null;
9468
+ }
9469
+
9470
+ /*
9471
+ * Locate a binarized raster symbol from its repeated start and stop patterns.
9472
+ * The detector estimates a projective quadrilateral; grayscale binarization
9473
+ * remains the caller's responsibility.
9474
+ */
9475
+ function detectPDF417(binaryImage, options = {}) {
9476
+ if (!binaryImage?.width || !binaryImage?.height || typeof binaryImage.get !== 'function') return null;
9477
+ let oriented = binaryImage;
9478
+ let toOriginal = (point) => ({ x: point.x, y: point.y });
9479
+ for (let turns = 0; turns < 4; turns++) {
9480
+ const supplied = turns === 0 && validQuadrilateral(options.quadrilateral)
9481
+ ? manualCandidate(options.quadrilateral.map(({ x, y }) => ({ x, y }))) : [];
9482
+ const found = detectInOrientation(oriented, options, supplied);
9483
+ if (found) {
9484
+ return { matrix: found.decoded.matrix, rotation: turns * 90,
9485
+ corners: found.decoded.corners.map(toOriginal), ...found.decoded.result };
9486
+ }
9487
+ const previous = oriented, previousToOriginal = toOriginal;
9488
+ oriented = rotateClockwise(previous);
9489
+ toOriginal = (point) => previousToOriginal({ x: point.y, y: previous.height - point.x });
9490
+ }
9491
+ return null;
9492
+ }
9493
+ function detectAndDecodePDF417(binaryImage, options = {}) { return detectPDF417(binaryImage, options); }
9494
+
9495
+ __exports.detectPDF417 = detectPDF417;
9496
+ __exports.detectAndDecodePDF417 = detectAndDecodePDF417;
9497
+ };
9498
+
9499
+ __modules["pdf417/index.js"] = function (__require, __exports) {
9500
+ const __reexport0 = __require("pdf417/compaction.js"); __exports.compactPdf417 = __reexport0.compactPdf417; __exports.compactPdf417Text = __reexport0.compactPdf417Text; __exports.compactPdf417Bytes = __reexport0.compactPdf417Bytes; __exports.compactPdf417Numeric = __reexport0.compactPdf417Numeric; __exports.decodePdf417Compaction = __reexport0.decodePdf417Compaction; __exports.decodePdf417CompactionDetailed = __reexport0.decodePdf417CompactionDetailed;
9501
+ const __reexport1 = __require("pdf417/encoder.js"); __exports.encodePDF417 = __reexport1.encodePDF417;
9502
+ const __reexport2 = __require("pdf417/decoder.js"); __exports.decodePDF417 = __reexport2.decodePDF417;
9503
+ const __reexport3 = __require("pdf417/detector.js"); __exports.detectPDF417 = __reexport3.detectPDF417; __exports.detectAndDecodePDF417 = __reexport3.detectAndDecodePDF417;
9504
+ const __reexport4 = __require("pdf417/error-correction.js"); __exports.pdf417EccLength = __reexport4.pdf417EccLength; __exports.pdf417ErrorCorrection = __reexport4.pdf417ErrorCorrection; __exports.pdf417CorrectErrors = __reexport4.pdf417CorrectErrors;
9505
+ const __reexport5 = __require("pdf417/tables.js"); __exports.PDF417_PATTERN_TABLE = __reexport5.PDF417_PATTERN_TABLE; __exports.PDF417_CLUSTER_NUMBERS = __reexport5.PDF417_CLUSTER_NUMBERS; __exports.pdf417PatternForCodeword = __reexport5.pdf417PatternForCodeword; __exports.pdf417CodewordForPattern = __reexport5.pdf417CodewordForPattern;
9506
+
9507
+
9508
+ };
9509
+
9510
+ __modules["micropdf417/tables.js"] = function (__require, __exports) {
9511
+ /**
9512
+ * MicroPDF417 format facts and Row Address Pattern (RAP) helpers.
9513
+ *
9514
+ * The tables are represented as compact, immutable data and are guarded by
9515
+ * {@link validateMicroPdf417Tables}. They are deliberately separate from the
9516
+ * PDF417 symbol-character table: MicroPDF417 has a fixed family of symbols and
9517
+ * its own row-address system.
9518
+ *
9519
+ * Values are derived from publicly available symbology documentation and
9520
+ * independently checked against black-box reference output. This module makes
9521
+ * no certification or conformance claim.
9522
+ *
9523
+ * @module micropdf417/tables
9524
+ */
9525
+
9526
+ const variant = (id, columns, rows, eccCodewords, rapStart, rapRotation) => Object.freeze({
9527
+ id,
9528
+ columns,
9529
+ rows,
9530
+ totalCodewords: columns * rows,
9531
+ dataCodewords: columns * rows - eccCodewords,
9532
+ eccCodewords,
9533
+ rapStart,
9534
+ rapRotation,
9535
+ });
9536
+
9537
+ /** All 34 predefined MicroPDF417 symbol variants, in format-table order. */
9538
+ const MICROPDF417_VARIANTS = Object.freeze([
9539
+ variant(1, 1, 11, 7, 1, 8), variant(2, 1, 14, 7, 8, 0),
9540
+ variant(3, 1, 17, 7, 36, 0), variant(4, 1, 20, 8, 19, 0),
9541
+ variant(5, 1, 24, 8, 9, 8), variant(6, 1, 28, 8, 25, 8),
9542
+ variant(7, 2, 8, 8, 1, 0), variant(8, 2, 11, 9, 1, 8),
9543
+ variant(9, 2, 14, 9, 8, 0), variant(10, 2, 17, 10, 36, 0),
9544
+ variant(11, 2, 20, 11, 19, 0), variant(12, 2, 23, 13, 9, 8),
9545
+ variant(13, 2, 26, 15, 27, 8),
9546
+ variant(14, 3, 6, 12, 1, 0), variant(15, 3, 8, 14, 7, 0),
9547
+ variant(16, 3, 10, 16, 15, 0), variant(17, 3, 12, 18, 25, 0),
9548
+ variant(18, 3, 15, 21, 37, 0), variant(19, 3, 20, 26, 1, 16),
9549
+ variant(20, 3, 26, 32, 1, 8), variant(21, 3, 32, 38, 21, 8),
9550
+ variant(22, 3, 38, 44, 15, 16), variant(23, 3, 44, 50, 1, 24),
9551
+ variant(24, 4, 4, 8, 47, 24), variant(25, 4, 6, 12, 1, 0),
9552
+ variant(26, 4, 8, 14, 7, 0), variant(27, 4, 10, 16, 15, 0),
9553
+ variant(28, 4, 12, 18, 25, 0), variant(29, 4, 15, 21, 37, 0),
9554
+ variant(30, 4, 20, 26, 1, 16), variant(31, 4, 26, 32, 1, 8),
9555
+ variant(32, 4, 32, 38, 21, 8), variant(33, 4, 38, 44, 15, 16),
9556
+ variant(34, 4, 44, 50, 1, 24),
9557
+ ]);
9558
+
9559
+ const byId = new Map(MICROPDF417_VARIANTS.map((entry) => [entry.id, entry]));
9560
+
9561
+ // Six run widths, ordered bar-space-bar-space-bar-space. A RAP is ten
9562
+ // modules wide; the right RAP has one additional one-module stop bar when
9563
+ // rendered. Keeping runs rather than bitmap literals makes each invariant
9564
+ // inspectable and avoids a rendering-specific representation here.
9565
+ const SIDE_RAP_RUNS = Object.freeze([
9566
+ '221311', '311311', '312211', '222211', '213211', '214111', '223111', '313111',
9567
+ '322111', '412111', '421111', '331111', '241111', '232111', '231211', '321211',
9568
+ '411211', '411121', '411112', '321112', '312112', '311212', '311221', '311131',
9569
+ '311122', '311113', '221113', '221122', '221131', '221221', '222121', '312121',
9570
+ '321121', '231121', '231112', '222112', '213112', '212212', '212221', '212131',
9571
+ '212122', '212113', '211213', '211123', '211132', '211141', '211231', '211222',
9572
+ '211312', '211321', '211411', '212311',
9573
+ ]);
9574
+
9575
+ const CENTER_RAP_RUNS = Object.freeze([
9576
+ '112231', '121231', '122131', '131131', '131221', '132121', '141121', '141211',
9577
+ '142111', '133111', '132211', '131311', '122311', '123211', '124111', '115111',
9578
+ '114211', '114121', '123121', '123112', '122212', '122221', '121321', '121411',
9579
+ '112411', '113311', '113221', '113212', '113122', '122122', '131122', '131113',
9580
+ '122113', '113113', '112213', '112222', '112312', '112321', '111421', '111331',
9581
+ '111322', '111232', '111223', '111133', '111124', '111214', '112114', '121114',
9582
+ '121123', '121132', '112132', '112141',
9583
+ ]);
9584
+
9585
+ /** @param {number} value @param {number} offset @returns {number} */
9586
+ function microPdf417NextRap(value, offset = 1) {
9587
+ if (!Number.isInteger(value) || value < 1 || value > 52) throw new RangeError('MicroPDF417: RAP number must be in 1..52');
9588
+ if (!Number.isInteger(offset)) throw new RangeError('MicroPDF417: RAP offset must be an integer');
9589
+ return ((value - 1 + offset) % 52 + 52) % 52 + 1;
9590
+ }
9591
+
9592
+ /** @param {number} id @returns {Readonly<typeof MICROPDF417_VARIANTS[number]>} */
9593
+ function microPdf417VariantByNumber(id) {
9594
+ const entry = byId.get(id);
9595
+ if (!entry) throw new RangeError('MicroPDF417: variant must be an integer in 1..34');
9596
+ return entry;
9597
+ }
9598
+
9599
+ /**
9600
+ * Return the smallest data-region candidate that fits `codewords`.
9601
+ * Ties are resolved by width, then height, so selection is deterministic.
9602
+ */
9603
+ function microPdf417VariantForCapacity(codewords) {
9604
+ if (!Number.isInteger(codewords) || codewords < 1) throw new RangeError('MicroPDF417: codeword capacity must be a positive integer');
9605
+ const candidates = MICROPDF417_VARIANTS.filter((entry) => entry.dataCodewords >= codewords);
9606
+ if (!candidates.length) throw new RangeError('MicroPDF417: payload exceeds the largest symbol data region');
9607
+ return candidates.slice().sort((a, b) => a.totalCodewords - b.totalCodewords || a.columns - b.columns || a.rows - b.rows)[0];
9608
+ }
9609
+
9610
+ /** Return the six bar/space run widths for a numbered side or center RAP. */
9611
+ function microPdf417RapSequence(number, kind = 'side') {
9612
+ if (!Number.isInteger(number) || number < 1 || number > 52) throw new RangeError('MicroPDF417: RAP number must be in 1..52');
9613
+ if (kind === 'side') return SIDE_RAP_RUNS[number - 1];
9614
+ if (kind === 'center') return CENTER_RAP_RUNS[number - 1];
9615
+ throw new RangeError('MicroPDF417: RAP kind must be side or center');
9616
+ }
9617
+
9618
+ /**
9619
+ * Resolve all row-address data for a zero-based row within a variant.
9620
+ * @returns {{left: number, center: number|null, right: number, cluster: 0|3|6}}
9621
+ */
9622
+ function microPdf417RowAddress(entry, row) {
9623
+ if (!entry || !Number.isInteger(entry.columns) || !Number.isInteger(entry.rows)) throw new TypeError('MicroPDF417: a variant entry is required');
9624
+ if (!Number.isInteger(row) || row < 0 || row >= entry.rows) throw new RangeError(`MicroPDF417: row must be in 0..${entry.rows - 1}`);
9625
+ const left = microPdf417NextRap(entry.rapStart, row);
9626
+ const cluster = /** @type {0|3|6} */ (((left - 1) % 3) * 3);
9627
+ if (entry.columns < 3) return { left, center: null, right: microPdf417NextRap(left, entry.rapRotation), cluster };
9628
+ const center = microPdf417NextRap(left, entry.rapRotation);
9629
+ return { left, center, right: microPdf417NextRap(center, entry.rapRotation), cluster };
9630
+ }
9631
+
9632
+ const validRuns = (runs) => runs.length === 6 && /^[1-9]{6}$/.test(runs) && [...runs].reduce((sum, digit) => sum + Number(digit), 0) === 10;
9633
+ const oneEdgeShift = (from, to) => [...from].reduce((sum, digit, index) => sum + Math.abs(Number(digit) - Number(to[index])), 0) === 2;
9634
+
9635
+ /** Return any table-invariant failures; an empty result means the table is coherent. */
9636
+ function validateMicroPdf417Tables() {
9637
+ const issues = [];
9638
+ if (MICROPDF417_VARIANTS.length !== 34) issues.push('expected 34 variants');
9639
+ const ids = new Set();
9640
+ const formats = new Set();
9641
+ for (const entry of MICROPDF417_VARIANTS) {
9642
+ if (ids.has(entry.id)) issues.push(`duplicate variant ${entry.id}`); ids.add(entry.id);
9643
+ const format = `${entry.columns}x${entry.rows}`;
9644
+ if (formats.has(format)) issues.push(`duplicate format ${format}`); formats.add(format);
9645
+ if (entry.totalCodewords !== entry.columns * entry.rows) issues.push(`${format}: total codeword geometry mismatch`);
9646
+ if (entry.dataCodewords + entry.eccCodewords !== entry.totalCodewords) issues.push(`${format}: data/ECC capacity mismatch`);
9647
+ if (entry.eccCodewords < 7 || entry.eccCodewords > 50) issues.push(`${format}: invalid ECC length`);
9648
+ if (entry.rapStart < 1 || entry.rapStart > 52 || entry.rapRotation < 0 || entry.rapRotation > 51) issues.push(`${format}: invalid RAP assignment`);
9649
+ for (let row = 0; row < entry.rows; row++) {
9650
+ const address = microPdf417RowAddress(entry, row);
9651
+ if (address.cluster !== ((address.left - 1) % 3) * 3) issues.push(`${format}: cluster mismatch at row ${row}`);
9652
+ if ((entry.columns < 3) !== (address.center === null)) issues.push(`${format}: center RAP layout mismatch`);
9653
+ }
9654
+ }
9655
+ for (const [kind, runs] of [['side', SIDE_RAP_RUNS], ['center', CENTER_RAP_RUNS]]) {
9656
+ if (runs.length !== 52) issues.push(`${kind}: expected 52 RAPs`);
9657
+ if (new Set(runs).size !== runs.length) issues.push(`${kind}: duplicate RAP`);
9658
+ for (let i = 0; i < runs.length; i++) {
9659
+ if (!validRuns(runs[i])) issues.push(`${kind}: invalid RAP ${i + 1}`);
9660
+ if (runs.length && !oneEdgeShift(runs[i], runs[(i + 1) % runs.length])) issues.push(`${kind}: RAP ${i + 1} is not adjacent to its successor`);
9661
+ }
9662
+ }
9663
+ return issues;
9664
+ }
9665
+
9666
+ __exports.MICROPDF417_VARIANTS = MICROPDF417_VARIANTS;
9667
+ __exports.microPdf417NextRap = microPdf417NextRap;
9668
+ __exports.microPdf417VariantByNumber = microPdf417VariantByNumber;
9669
+ __exports.microPdf417VariantForCapacity = microPdf417VariantForCapacity;
9670
+ __exports.microPdf417RapSequence = microPdf417RapSequence;
9671
+ __exports.microPdf417RowAddress = microPdf417RowAddress;
9672
+ __exports.validateMicroPdf417Tables = validateMicroPdf417Tables;
9673
+ };
9674
+
9675
+ __modules["micropdf417/error-correction.js"] = function (__require, __exports) {
9676
+ /** MicroPDF417 error correction over the existing GF(929) core. @module micropdf417/error-correction */
9677
+ const { EncodeError } = __require("core/errors.js");
9678
+ const { GF929 } = __require("core/galois-field.js");
9679
+ const { generatorPoly, rsDecode, rsEncode } = __require("core/reed-solomon.js");
9680
+
9681
+ function eccLength(entry) {
9682
+ if (!entry || !Number.isInteger(entry.eccCodewords)) throw new EncodeError('MicroPDF417: a variant with an ECC length is required');
9683
+ if (entry.eccCodewords < 1 || entry.eccCodewords >= GF929.size) throw new EncodeError('MicroPDF417: ECC length is outside GF(929) bounds');
9684
+ return entry.eccCodewords;
9685
+ }
9686
+
9687
+ /** Return the fixed number of parity codewords for a MicroPDF417 variant. */
9688
+ function microPdf417EccLength(entry) { return eccLength(entry); }
9689
+
9690
+ /** Build the MicroPDF417 generator polynomial for a variant's fixed ECC length. */
9691
+ function microPdf417Generator(entry) { return generatorPoly(eccLength(entry), GF929, 1); }
9692
+
9693
+ /** Compute systematic MicroPDF417 parity codewords. `data` must already include padding. */
9694
+ function microPdf417ErrorCorrection(data, entry) { return rsEncode(data, eccLength(entry), GF929, 1); }
9695
+
9696
+ /** Correct a complete MicroPDF417 codeword stream, optionally marking erasures. */
9697
+ function microPdf417CorrectErrors(codewords, entry, erasures = []) {
9698
+ return rsDecode(codewords, eccLength(entry), GF929, 1, erasures);
9699
+ }
9700
+
9701
+ __exports.microPdf417EccLength = microPdf417EccLength;
9702
+ __exports.microPdf417Generator = microPdf417Generator;
9703
+ __exports.microPdf417ErrorCorrection = microPdf417ErrorCorrection;
9704
+ __exports.microPdf417CorrectErrors = microPdf417CorrectErrors;
9705
+ };
9706
+
9707
+ __modules["micropdf417/compaction.js"] = function (__require, __exports) {
9708
+ /** MicroPDF417 high-level compaction adapter. @module micropdf417/compaction */
9709
+ const { EncodeError } = __require("core/errors.js");
9710
+ const { compactPdf417Bytes, compactPdf417Numeric, compactPdf417Text } = __require("pdf417/compaction.js");
9711
+
9712
+ function byteLength(value) {
9713
+ if (value instanceof Uint8Array) return value.byteLength;
9714
+ if (ArrayBuffer.isView(value)) return value.byteLength;
9715
+ return -1;
9716
+ }
9717
+
9718
+ function assertNotEmpty(value) {
9719
+ if ((typeof value === 'string' && value.length === 0) || byteLength(value) === 0) {
9720
+ throw new EncodeError('MicroPDF417: value must not be empty');
9721
+ }
9722
+ }
9723
+
9724
+ function latin1Bytes(value) {
9725
+ if (typeof value !== 'string') return value;
9726
+ const bytes = [];
9727
+ for (const character of value) {
9728
+ const codePoint = character.codePointAt(0);
9729
+ if (codePoint > 255) {
9730
+ throw new EncodeError('MicroPDF417 ECI 3: string contains a character outside ISO-8859-1');
9731
+ }
9732
+ bytes.push(codePoint);
9733
+ }
9734
+ return Uint8Array.from(bytes);
9735
+ }
9736
+
9737
+ function compactByte(value, eci) {
9738
+ if (eci === undefined) return compactPdf417Bytes(value);
9739
+ if (eci === 3) return compactPdf417Bytes(latin1Bytes(value));
9740
+ if (eci === 26) {
9741
+ if (typeof value !== 'string') {
9742
+ throw new EncodeError('MicroPDF417 ECI 26: value must be a string so UTF-8 validity is known');
9743
+ }
9744
+ const encoded = compactPdf417Bytes(value);
9745
+ return encoded[0] === 927 && encoded[1] === 26 ? encoded : [927, 26, ...encoded];
9746
+ }
9747
+ throw new EncodeError('MicroPDF417: supported ECI assignment numbers are 3 and 26');
9748
+ }
9749
+
9750
+ /**
9751
+ * Compact one MicroPDF417 value.
9752
+ *
9753
+ * Unlike PDF417, MicroPDF417 starts in Byte Compaction. Text therefore needs
9754
+ * an explicit 900 latch. Byte compaction always emits 901 or 924 so its start
9755
+ * state is unambiguous, including when an ECI designator precedes it.
9756
+ */
9757
+ function compactMicroPDF417(value, options = {}) {
9758
+ assertNotEmpty(value);
9759
+ const mode = options.compaction ?? 'auto';
9760
+ const eci = options.eci;
9761
+ if (eci !== undefined && eci !== 3 && eci !== 26) {
9762
+ throw new EncodeError('MicroPDF417: supported ECI assignment numbers are 3 and 26');
9763
+ }
9764
+
9765
+ if (mode === 'text') {
9766
+ if (eci !== undefined) throw new EncodeError('MicroPDF417: explicit ECI is supported only with byte compaction');
9767
+ return [900, ...compactPdf417Text(value)];
9768
+ }
9769
+ if (mode === 'numeric') {
9770
+ if (eci !== undefined) throw new EncodeError('MicroPDF417: explicit ECI is supported only with byte compaction');
9771
+ return compactPdf417Numeric(value);
9772
+ }
9773
+ if (mode === 'byte') return compactByte(value, eci);
9774
+ if (mode !== 'auto') {
9775
+ throw new EncodeError(`MicroPDF417: unsupported compaction mode ${JSON.stringify(mode)}`);
9776
+ }
9777
+
9778
+ if (eci !== undefined) return compactByte(value, eci);
9779
+ if (typeof value === 'string' && /^\d{13,}$/.test(value)) return compactPdf417Numeric(value);
9780
+ if (typeof value === 'string') {
9781
+ try {
9782
+ return [900, ...compactPdf417Text(value)];
9783
+ } catch (error) {
9784
+ if (!(error instanceof EncodeError)) throw error;
9785
+ }
9786
+ }
9787
+ return compactPdf417Bytes(value);
9788
+ }
9789
+
9790
+ __exports.compactMicroPDF417 = compactMicroPDF417;
9791
+ };
9792
+
9793
+ __modules["micropdf417/encoder.js"] = function (__require, __exports) {
9794
+ /** MicroPDF417 encoder. @module micropdf417/encoder */
9795
+ const { BitMatrix } = __require("core/bit-matrix.js");
9796
+ const { EncodeError } = __require("core/errors.js");
9797
+ const { pdf417PatternForCodeword } = __require("pdf417/tables.js");
9798
+ const { compactMicroPDF417 } = __require("micropdf417/compaction.js");
9799
+ const { microPdf417ErrorCorrection } = __require("micropdf417/error-correction.js");
9800
+ const { MICROPDF417_VARIANTS, microPdf417RapSequence, microPdf417RowAddress, microPdf417VariantByNumber, microPdf417VariantForCapacity } = __require("micropdf417/tables.js");
9801
+
9802
+ function appendWidths(matrix, y, x, sequence, height) {
9803
+ let dark = true;
9804
+ for (const digit of sequence) {
9805
+ const width = digit.charCodeAt(0) - 48;
9806
+ if (!Number.isInteger(width) || width < 1 || width > 6) {
9807
+ throw new EncodeError('MicroPDF417: invalid module-width sequence');
9808
+ }
9809
+ if (dark) matrix.setRegion(x, y, width, height);
9810
+ x += width;
9811
+ dark = !dark;
9812
+ }
9813
+ return x;
9814
+ }
9815
+
9816
+ function codewordSequence(codeword, cluster) {
9817
+ return pdf417PatternForCodeword(codeword, cluster)
9818
+ .toString(2)
9819
+ .padStart(17, '0')
9820
+ .replace(/0+|1+/g, (run) => String(run.length));
9821
+ }
9822
+
9823
+ function symbolWidth(columns) {
9824
+ return 21 + columns * 17 + (columns > 2 ? 10 : 0);
9825
+ }
9826
+
9827
+ function validateOptions(options) {
9828
+ const rowHeight = options.rowHeight ?? 2;
9829
+ if (!Number.isInteger(rowHeight) || rowHeight < 2) {
9830
+ throw new EncodeError('MicroPDF417: rowHeight must be an integer of at least 2');
9831
+ }
9832
+ if (options.columns !== undefined &&
9833
+ (!Number.isInteger(options.columns) || options.columns < 1 || options.columns > 4)) {
9834
+ throw new EncodeError('MicroPDF417: columns must be an integer in 1..4');
9835
+ }
9836
+ if (options.variant !== undefined &&
9837
+ (!Number.isInteger(options.variant) || options.variant < 1 || options.variant > 34)) {
9838
+ throw new EncodeError('MicroPDF417: variant must be an integer in 1..34');
9839
+ }
9840
+ if (options.aspectRatio !== undefined &&
9841
+ (!Number.isFinite(options.aspectRatio) || options.aspectRatio <= 0)) {
9842
+ throw new EncodeError('MicroPDF417: aspectRatio must be positive');
9843
+ }
9844
+ if (options.rows !== undefined) {
9845
+ throw new EncodeError('MicroPDF417: rows are fixed by the selected variant');
9846
+ }
9847
+ if (options.eccLevel !== undefined) {
9848
+ throw new EncodeError('MicroPDF417: error correction is fixed by the selected variant');
9849
+ }
9850
+ for (const feature of [
9851
+ 'structuredAppend', 'macro', 'macroPdf417', 'macroControlBlock',
9852
+ 'readerInit', 'gs1', 'hibc', 'linkage',
9853
+ ]) {
9854
+ if (options[feature] !== undefined) {
9855
+ throw new EncodeError(`MicroPDF417: ${feature} is not implemented`);
9856
+ }
9857
+ }
9858
+ return rowHeight;
9859
+ }
9860
+
9861
+ function chooseVariant(codewordCount, rowHeight, options) {
9862
+ if (options.variant !== undefined) {
9863
+ const variant = microPdf417VariantByNumber(options.variant);
9864
+ if (!variant) throw new EncodeError(`MicroPDF417: unknown variant ${options.variant}`);
9865
+ if (options.columns !== undefined && variant.columns !== options.columns) {
9866
+ throw new EncodeError(`MicroPDF417: variant ${variant.id} has ${variant.columns} columns`);
9867
+ }
9868
+ if (codewordCount > variant.dataCodewords) {
9869
+ throw new EncodeError(
9870
+ `MicroPDF417: payload requires ${codewordCount} data codewords, variant ${variant.id} holds ${variant.dataCodewords}`
9871
+ );
9872
+ }
9873
+ return variant;
9874
+ }
9875
+
9876
+ if (options.columns === undefined && options.aspectRatio === undefined) {
9877
+ try {
9878
+ return microPdf417VariantForCapacity(codewordCount);
9879
+ } catch (error) {
9880
+ if (!(error instanceof RangeError)) throw error;
9881
+ throw new EncodeError(`MicroPDF417: payload requires ${codewordCount} data codewords and exceeds every variant`);
9882
+ }
9883
+ }
9884
+
9885
+ const candidates = MICROPDF417_VARIANTS.filter((variant) =>
9886
+ variant.dataCodewords >= codewordCount &&
9887
+ (options.columns === undefined || variant.columns === options.columns)
9888
+ );
9889
+ if (!candidates.length) {
9890
+ const columnText = options.columns === undefined ? '' : ` with ${options.columns} columns`;
9891
+ throw new EncodeError(`MicroPDF417: payload does not fit any supported variant${columnText}`);
9892
+ }
9893
+ if (options.aspectRatio === undefined) {
9894
+ return candidates.reduce((best, variant) =>
9895
+ variant.dataCodewords < best.dataCodewords ||
9896
+ (variant.dataCodewords === best.dataCodewords && variant.totalCodewords < best.totalCodewords)
9897
+ ? variant : best
9898
+ );
9899
+ }
9900
+
9901
+ const target = options.aspectRatio;
9902
+ return candidates.reduce((best, variant) => {
9903
+ const ratio = symbolWidth(variant.columns) / (variant.rows * rowHeight);
9904
+ const score = Math.abs(Math.log(ratio / target)) +
9905
+ (variant.dataCodewords - codewordCount) / 10000;
9906
+ return !best || score < best.score ? { variant, score } : best;
9907
+ }, null).variant;
9908
+ }
9909
+
9910
+ /** Encode a value as one of the 34 fixed MicroPDF417 variants. */
9911
+ function encodeMicroPDF417(value, options = {}) {
9912
+ const rowHeight = validateOptions(options);
9913
+ const payload = compactMicroPDF417(value, options);
9914
+ const variant = chooseVariant(payload.length, rowHeight, options);
9915
+ const data = payload.slice();
9916
+ while (data.length < variant.dataCodewords) data.push(900);
9917
+ const ecc = microPdf417ErrorCorrection(data, variant);
9918
+ if (ecc.length !== variant.eccCodewords) {
9919
+ throw new EncodeError('MicroPDF417: error-correction length does not match the selected variant');
9920
+ }
9921
+ const codewords = data.concat(ecc);
9922
+ if (codewords.length !== variant.totalCodewords || codewords.length !== variant.rows * variant.columns) {
9923
+ throw new EncodeError('MicroPDF417: selected variant has inconsistent codeword dimensions');
9924
+ }
9925
+
9926
+ const matrix = new BitMatrix(symbolWidth(variant.columns), variant.rows * rowHeight);
9927
+ for (let row = 0; row < variant.rows; row++) {
9928
+ const y = row * rowHeight;
9929
+ const address = microPdf417RowAddress(variant, row);
9930
+ let x = appendWidths(matrix, y, 0, microPdf417RapSequence(address.left, 'side'), rowHeight);
9931
+ for (let column = 0; column < variant.columns; column++) {
9932
+ x = appendWidths(
9933
+ matrix,
9934
+ y,
9935
+ x,
9936
+ codewordSequence(codewords[row * variant.columns + column], address.cluster),
9937
+ rowHeight
9938
+ );
9939
+ const hasCentralRap = (variant.columns === 3 && column === 0) ||
9940
+ (variant.columns === 4 && column === 1);
9941
+ if (hasCentralRap) {
9942
+ if (address.center === null) {
9943
+ throw new EncodeError('MicroPDF417: selected variant is missing its centre row address');
9944
+ }
9945
+ x = appendWidths(matrix, y, x, microPdf417RapSequence(address.center, 'center'), rowHeight);
9946
+ }
9947
+ }
9948
+ x = appendWidths(matrix, y, x, microPdf417RapSequence(address.right, 'side'), rowHeight);
9949
+ matrix.setRegion(x, y, 1, rowHeight);
9950
+ x++;
9951
+ if (x !== matrix.width) throw new EncodeError('MicroPDF417: row width does not match the selected variant');
9952
+ }
9953
+
9954
+ matrix.micropdf417 = {
9955
+ variant: variant.id,
9956
+ rows: variant.rows,
9957
+ columns: variant.columns,
9958
+ eccCodewords: variant.eccCodewords,
9959
+ rowHeight,
9960
+ payloadCodewords: payload.length,
9961
+ dataCodewords: data,
9962
+ codewords,
9963
+ };
9964
+ return matrix;
9965
+ }
9966
+
9967
+ __exports.encodeMicroPDF417 = encodeMicroPDF417;
9968
+ };
9969
+
9970
+ __modules["micropdf417/decoder.js"] = function (__require, __exports) {
9971
+ /**
9972
+ * Direct-module MicroPDF417 decoder.
9973
+ *
9974
+ * This module reads an already sampled, axis-aligned `BitMatrix`. Image finding,
9975
+ * perspective correction, and recognition from photographic pixels are deliberately
9976
+ * outside this first decoder boundary. The RAP sequence is authoritative for format
9977
+ * detection; matrix metadata is used only as an optional row-height hint.
9978
+ *
9979
+ * @module micropdf417/decoder
9980
+ */
9981
+ const { FormatError } = __require("core/errors.js");
9982
+ const { decodePdf417CompactionDetailed } = __require("pdf417/compaction.js");
9983
+ const { pdf417CodewordForPattern } = __require("pdf417/tables.js");
9984
+ const { microPdf417CorrectErrors } = __require("micropdf417/error-correction.js");
9985
+ const { MICROPDF417_VARIANTS, microPdf417RapSequence, microPdf417RowAddress, microPdf417VariantByNumber } = __require("micropdf417/tables.js");
9986
+
9987
+ function symbolWidth(columns) {
9988
+ return 21 + columns * 17 + (columns > 2 ? 10 : 0);
9989
+ }
9990
+
9991
+ function bits(matrix, y, x, width) {
9992
+ let value = 0;
9993
+ for (let i = 0; i < width; i++) value = (value << 1) | (matrix.get(x + i, y) ? 1 : 0);
9994
+ return value;
9995
+ }
9996
+
9997
+ function widthsToBits(widths) {
9998
+ let dark = true;
9999
+ let out = '';
10000
+ for (const digit of widths) {
10001
+ out += (dark ? '1' : '0').repeat(digit.charCodeAt(0) - 48);
10002
+ dark = !dark;
10003
+ }
10004
+ return out;
10005
+ }
10006
+
10007
+ function hasExpectedBits(matrix, y, x, sequence) {
10008
+ const expected = widthsToBits(sequence);
10009
+ for (let i = 0; i < expected.length; i++) {
10010
+ if ((matrix.get(x + i, y) ? '1' : '0') !== expected[i]) return false;
10011
+ }
10012
+ return true;
10013
+ }
10014
+
10015
+ function centralRapAfter(entry, column) {
10016
+ return (entry.columns === 3 && column === 0) ||
10017
+ (entry.columns === 4 && column === 1);
10018
+ }
10019
+
10020
+ /** Return true when all address patterns for this format candidate agree. */
10021
+ function hasValidRowAddresses(matrix, entry, rowHeight) {
10022
+ for (let row = 0; row < entry.rows; row++) {
10023
+ const y = row * rowHeight;
10024
+ const address = microPdf417RowAddress(entry, row);
10025
+ let x = 0;
10026
+ if (!hasExpectedBits(matrix, y, x, microPdf417RapSequence(address.left, 'side'))) return false;
10027
+ x += 10;
10028
+ for (let column = 0; column < entry.columns; column++) {
10029
+ x += 17;
10030
+ if (centralRapAfter(entry, column)) {
10031
+ if (address.center === null ||
10032
+ !hasExpectedBits(matrix, y, x, microPdf417RapSequence(address.center, 'center'))) return false;
10033
+ x += 10;
10034
+ }
10035
+ }
10036
+ if (!hasExpectedBits(matrix, y, x, microPdf417RapSequence(address.right, 'side'))) return false;
10037
+ x += 10;
10038
+ if (!matrix.get(x, y) || x + 1 !== matrix.width) return false;
10039
+ }
10040
+ return true;
10041
+ }
10042
+
10043
+ function candidateFormats(matrix, options) {
10044
+ const metadataHeight = matrix.micropdf417?.rowHeight;
10045
+ const requestedHeight = options.rowHeight ?? metadataHeight;
10046
+ if (requestedHeight !== undefined && (!Number.isInteger(requestedHeight) || requestedHeight < 1)) {
10047
+ throw new FormatError('MicroPDF417: rowHeight must be a positive integer');
10048
+ }
10049
+ const requestedVariant = options.variant === undefined ? null : microPdf417VariantByNumber(options.variant);
10050
+ const pool = requestedVariant ? [requestedVariant] : MICROPDF417_VARIANTS;
10051
+ const candidates = [];
10052
+ for (const entry of pool) {
10053
+ if (matrix.width !== symbolWidth(entry.columns)) continue;
10054
+ if (matrix.height % entry.rows) continue;
10055
+ const rowHeight = matrix.height / entry.rows;
10056
+ if (requestedHeight !== undefined && rowHeight !== requestedHeight) continue;
10057
+ if (hasValidRowAddresses(matrix, entry, rowHeight)) candidates.push({ entry, rowHeight });
10058
+ }
10059
+ return candidates;
10060
+ }
10061
+
10062
+ function resolveFormat(matrix, options) {
10063
+ if (!matrix?.width || !matrix?.height || typeof matrix.get !== 'function') {
10064
+ throw new FormatError('MicroPDF417: matrix with width, height and get() is required');
10065
+ }
10066
+ const candidates = candidateFormats(matrix, options);
10067
+ if (!candidates.length) throw new FormatError('MicroPDF417: no variant matches matrix geometry and row-address patterns');
10068
+ if (candidates.length > 1) throw new FormatError('MicroPDF417: row-address patterns do not identify a unique variant');
10069
+ return candidates[0];
10070
+ }
10071
+
10072
+ function readCodewords(matrix, entry, rowHeight) {
10073
+ const codewords = [];
10074
+ const erasures = [];
10075
+ for (let row = 0; row < entry.rows; row++) {
10076
+ const y = row * rowHeight;
10077
+ const address = microPdf417RowAddress(entry, row);
10078
+ let x = 10;
10079
+ for (let column = 0; column < entry.columns; column++) {
10080
+ const decoded = pdf417CodewordForPattern(bits(matrix, y, x, 17));
10081
+ if (!decoded || decoded.cluster !== address.cluster) {
10082
+ erasures.push(codewords.length);
10083
+ codewords.push(0);
10084
+ } else {
10085
+ codewords.push(decoded.codeword);
10086
+ }
10087
+ x += 17;
10088
+ if (centralRapAfter(entry, column)) x += 10;
10089
+ }
10090
+ }
10091
+ return { codewords, erasures };
10092
+ }
10093
+
10094
+ /**
10095
+ * Decode a sampled MicroPDF417 matrix.
10096
+ *
10097
+ * The complete fixed data region is compacted after correction. Encoder padding
10098
+ * is PDF417 Text latch 900, which contributes no characters at the end of the
10099
+ * payload. This avoids relying on non-symbol metadata for payload length.
10100
+ */
10101
+ function decodeMicroPDF417(matrix, options = {}) {
10102
+ const { entry, rowHeight } = resolveFormat(matrix, options);
10103
+ const { codewords, erasures } = readCodewords(matrix, entry, rowHeight);
10104
+ const corrections = microPdf417CorrectErrors(codewords, entry, erasures);
10105
+ const data = codewords.slice(0, entry.dataCodewords);
10106
+ const decoded = decodePdf417CompactionDetailed(data);
10107
+ return {
10108
+ ...decoded,
10109
+ codewords,
10110
+ rows: entry.rows,
10111
+ columns: entry.columns,
10112
+ variant: entry.id,
10113
+ eccCodewords: entry.eccCodewords,
10114
+ rowHeight,
10115
+ corrections,
10116
+ };
10117
+ }
10118
+
10119
+ __exports.decodeMicroPDF417 = decodeMicroPDF417;
10120
+ };
10121
+
10122
+ __modules["micropdf417/detector.js"] = function (__require, __exports) {
10123
+ /**
10124
+ * Axis-aligned MicroPDF417 raster detection.
10125
+ *
10126
+ * A MicroPDF417 symbol has a fixed module width for each column count and a
10127
+ * dark leading and trailing module in every row. Consequently the bounding
10128
+ * rectangle of dark pixels identifies the complete symbol even when a light
10129
+ * quiet zone surrounds it. Its width determines the integer raster scale;
10130
+ * the existing direct-module decoder then verifies every row-address pattern
10131
+ * and selects the exact variant. This is intentionally narrower than the
10132
+ * PDF417 photo detector: it handles clean binarized rasters only, not skew or
10133
+ * projective camera images.
10134
+ *
10135
+ * @module micropdf417/detector
10136
+ */
10137
+ const { BitMatrix } = __require("core/bit-matrix.js");
10138
+ const { decodeMicroPDF417 } = __require("micropdf417/decoder.js");
10139
+
10140
+ /** @typedef {{x:number, y:number}} Point */
10141
+
10142
+ // Each row has two 10-module side RAPs, a final separator, and 17 modules for
10143
+ // each data column. Three and four columns also contain one central RAP.
10144
+ function symbolWidth(columns) { return 21 + columns * 17 + (columns > 2 ? 10 : 0); }
10145
+ const WIDTHS = [1, 2, 3, 4].map(symbolWidth);
10146
+
10147
+ function rotateClockwise(source) {
10148
+ const rotated = new BitMatrix(source.height, source.width);
10149
+ for (let y = 0; y < source.height; y++) for (let x = 0; x < source.width; x++) {
10150
+ if (source.get(x, y)) rotated.set(source.height - 1 - y, x);
10151
+ }
10152
+ return rotated;
10153
+ }
10154
+
10155
+ function integerScale(width, modules) {
10156
+ if (width % modules) return 0;
10157
+ const scale = width / modules;
10158
+ return Number.isInteger(scale) && scale > 0 ? scale : 0;
10159
+ }
10160
+
10161
+ /** Collapse exact integer scale blocks using a majority vote. */
10162
+ function sampleRaster(image, bounds, modulesWide, scale) {
10163
+ const modulesHigh = bounds.height / scale;
10164
+ if (!Number.isInteger(modulesHigh) || modulesHigh < 1) return null;
10165
+ const matrix = new BitMatrix(modulesWide, modulesHigh);
10166
+ for (let y = 0; y < modulesHigh; y++) for (let x = 0; x < modulesWide; x++) {
10167
+ let dark = 0;
10168
+ for (let py = 0; py < scale; py++) for (let px = 0; px < scale; px++) {
10169
+ if (image.get(bounds.x + x * scale + px, bounds.y + y * scale + py)) dark++;
10170
+ }
10171
+ if (dark * 2 >= scale * scale) matrix.set(x, y);
10172
+ }
10173
+ return matrix;
10174
+ }
10175
+
10176
+ function rectangle(bounds) {
10177
+ return [
10178
+ { x: bounds.x, y: bounds.y },
10179
+ { x: bounds.x + bounds.width, y: bounds.y },
10180
+ { x: bounds.x + bounds.width, y: bounds.y + bounds.height },
10181
+ { x: bounds.x, y: bounds.y + bounds.height },
10182
+ ];
10183
+ }
10184
+
10185
+ function detectAxisAligned(image, options) {
10186
+ const bounds = image.getBounds();
10187
+ if (!bounds) return null;
10188
+ for (const width of WIDTHS) {
10189
+ const scale = integerScale(bounds.width, width);
10190
+ if (!scale || bounds.height % scale) continue;
10191
+ const matrix = sampleRaster(image, bounds, width, scale);
10192
+ if (!matrix) continue;
10193
+ try {
10194
+ const decoded = decodeMicroPDF417(matrix, options);
10195
+ return { matrix, corners: rectangle(bounds), moduleSize: scale, ...decoded };
10196
+ } catch { /* The RAP sequence is not a MicroPDF417 symbol of this width. */ }
10197
+ }
10198
+ return null;
10199
+ }
10200
+
10201
+ /**
10202
+ * Detect and decode one clean, binarized MicroPDF417 raster.
10203
+ *
10204
+ * Integer upscaling and quiet zones are accepted. The image is retried at all
10205
+ * quarter-turns, but arbitrary angles and perspective require caller-side
10206
+ * rectification before this function is used. `rotation` reports the clockwise
10207
+ * orientation of the supplied input relative to a normally oriented symbol;
10208
+ * it is not the inverse correction applied internally while searching.
10209
+ *
10210
+ * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage Set bit = dark.
10211
+ * @param {object} [options] Passed to {@link decodeMicroPDF417}.
10212
+ * @returns {(ReturnType<typeof decodeMicroPDF417> & {matrix: BitMatrix, corners: Point[], moduleSize: number, rotation: number}) | null}
10213
+ */
10214
+ function detectMicroPDF417(binaryImage, options = {}) {
10215
+ if (!binaryImage?.width || !binaryImage?.height || typeof binaryImage.get !== 'function') return null;
10216
+ let oriented = binaryImage;
10217
+ let toOriginal = (point) => ({ x: point.x, y: point.y });
10218
+ for (let turns = 0; turns < 4; turns++) {
10219
+ const found = detectAxisAligned(oriented, options);
10220
+ // Search rotates clockwise to normalize the input. Public rotation has the
10221
+ // opposite meaning: it describes how the input itself was rotated.
10222
+ if (found) return {
10223
+ ...found,
10224
+ rotation: (360 - turns * 90) % 360,
10225
+ corners: found.corners.map(toOriginal),
10226
+ };
10227
+ const previous = oriented;
10228
+ const previousToOriginal = toOriginal;
10229
+ oriented = rotateClockwise(previous);
10230
+ // Boundary coordinates (rather than just pixel centres) are transformed
10231
+ // here, so callers can draw the returned rectangle directly on the input.
10232
+ toOriginal = (point) => previousToOriginal({ x: point.y, y: previous.height - point.x });
10233
+ }
10234
+ return null;
10235
+ }
10236
+
10237
+ /** Alias kept symmetric with the other 2D readers. */
10238
+ function detectAndDecodeMicroPDF417(binaryImage, options = {}) {
10239
+ return detectMicroPDF417(binaryImage, options);
10240
+ }
10241
+
10242
+ __exports.detectMicroPDF417 = detectMicroPDF417;
10243
+ __exports.detectAndDecodeMicroPDF417 = detectAndDecodeMicroPDF417;
10244
+ };
10245
+
10246
+ __modules["micropdf417/index.js"] = function (__require, __exports) {
10247
+ const __reexport0 = __require("micropdf417/tables.js"); __exports.MICROPDF417_VARIANTS = __reexport0.MICROPDF417_VARIANTS; __exports.microPdf417NextRap = __reexport0.microPdf417NextRap; __exports.microPdf417VariantByNumber = __reexport0.microPdf417VariantByNumber; __exports.microPdf417VariantForCapacity = __reexport0.microPdf417VariantForCapacity; __exports.microPdf417RapSequence = __reexport0.microPdf417RapSequence; __exports.microPdf417RowAddress = __reexport0.microPdf417RowAddress; __exports.validateMicroPdf417Tables = __reexport0.validateMicroPdf417Tables;
10248
+ const __reexport1 = __require("micropdf417/error-correction.js"); __exports.microPdf417EccLength = __reexport1.microPdf417EccLength; __exports.microPdf417Generator = __reexport1.microPdf417Generator; __exports.microPdf417ErrorCorrection = __reexport1.microPdf417ErrorCorrection; __exports.microPdf417CorrectErrors = __reexport1.microPdf417CorrectErrors;
10249
+ const __reexport2 = __require("micropdf417/compaction.js"); __exports.compactMicroPDF417 = __reexport2.compactMicroPDF417;
10250
+ const __reexport3 = __require("micropdf417/encoder.js"); __exports.encodeMicroPDF417 = __reexport3.encodeMicroPDF417;
10251
+ const __reexport4 = __require("micropdf417/decoder.js"); __exports.decodeMicroPDF417 = __reexport4.decodeMicroPDF417;
10252
+ const __reexport5 = __require("micropdf417/detector.js"); __exports.detectMicroPDF417 = __reexport5.detectMicroPDF417; __exports.detectAndDecodeMicroPDF417 = __reexport5.detectAndDecodeMicroPDF417;
10253
+
10254
+
10255
+ };
10256
+
10257
+ __modules["render/options.js"] = function (__require, __exports) {
10258
+ /**
10259
+ * Shared render options, normalised once so every backend agrees.
10260
+ *
10261
+ * @module render/options
10262
+ */
10263
+ const { BitMatrix } = __require("core/bit-matrix.js");
10264
+
10265
+ /**
10266
+ * @typedef {object} RenderOptions
10267
+ * @property {number} [scale] Pixels per module. Default 8.
10268
+ * @property {number} [margin] Quiet-zone modules on every side. Default 4.
10269
+ * @property {string} [dark] Colour of set modules. Default '#000000'.
10270
+ * @property {string} [light] Colour of clear modules, or 'none' for transparent.
10271
+ * @property {number} [barHeight] For 1D symbols: total bar height in pixels.
10272
+ */
10273
+
10274
+ /**
10275
+ * Expand and pad the matrix, and resolve every dimension.
10276
+ *
10277
+ * Linear symbols arrive one module tall. They are stretched to `barHeight`
10278
+ * *before* the quiet zone is applied, so the margin ends up uniform on all
10279
+ * four sides — padding first would leave a quiet zone one module tall against
10280
+ * bars a hundred pixels tall, which no scanner would accept.
10281
+ *
10282
+ * @param {BitMatrix} matrix
10283
+ * @param {RenderOptions} options
10284
+ */
10285
+ function normalizeOptions(matrix, options = {}) {
10286
+ const scale = Math.max(1, Math.floor(options.scale ?? 8));
10287
+ const margin = Math.max(0, Math.floor(options.margin ?? 4));
10288
+ const dark = options.dark ?? '#000000';
10289
+ const light = options.light ?? '#ffffff';
10290
+ const barHeight = options.barHeight ?? null;
10291
+
10292
+ let base = matrix;
10293
+ const is1D = matrix.height === 1;
10294
+
10295
+ if (is1D) {
10296
+ // Default to a bar height that stays scannable: tall enough that a laser
10297
+ // crossing at a slight angle still passes through the whole symbol.
10298
+ const targetPixels = barHeight ?? Math.max(40, Math.round(matrix.width * scale * 0.15));
10299
+ const rows = Math.max(1, Math.round(targetPixels / scale));
10300
+ base = new BitMatrix(matrix.width, rows);
10301
+ for (let x = 0; x < matrix.width; x++) {
10302
+ if (!matrix.get(x, 0)) continue;
10303
+ for (let y = 0; y < rows; y++) base.set(x, y);
10304
+ }
10305
+ }
10306
+
10307
+ const source = margin > 0 ? base.withMargin(margin) : base;
10308
+
10309
+ return {
10310
+ scale,
10311
+ margin,
10312
+ dark,
10313
+ light,
10314
+ is1D,
10315
+ source,
10316
+ rowHeight: scale,
10317
+ pixelWidth: source.width * scale,
10318
+ pixelHeight: source.height * scale,
10319
+ };
10320
+ }
10321
+
10322
+ /**
10323
+ * Parse a CSS colour into RGBA bytes.
10324
+ *
10325
+ * Supports the forms a barcode actually needs: #rgb, #rgba, #rrggbb,
10326
+ * #rrggbbaa, rgb(), rgba(), plus 'none' and 'transparent'.
10327
+ *
10328
+ * @param {string} colour
10329
+ * @returns {[number, number, number, number]}
10330
+ */
10331
+ function parseColor(colour) {
10332
+ const value = String(colour).trim().toLowerCase();
10333
+
10334
+ if (value === 'none' || value === 'transparent') return [0, 0, 0, 0];
10335
+ if (value === 'white') return [255, 255, 255, 255];
10336
+ if (value === 'black') return [0, 0, 0, 255];
10337
+
10338
+ if (value[0] === '#') {
10339
+ const hex = value.slice(1);
10340
+ const expand = (c) => parseInt(c + c, 16);
10341
+ if (hex.length === 3) {
10342
+ return [expand(hex[0]), expand(hex[1]), expand(hex[2]), 255];
10343
+ }
10344
+ if (hex.length === 4) {
10345
+ return [expand(hex[0]), expand(hex[1]), expand(hex[2]), expand(hex[3])];
10346
+ }
10347
+ if (hex.length === 6) {
10348
+ return [
10349
+ parseInt(hex.slice(0, 2), 16),
10350
+ parseInt(hex.slice(2, 4), 16),
10351
+ parseInt(hex.slice(4, 6), 16),
10352
+ 255,
10353
+ ];
10354
+ }
10355
+ if (hex.length === 8) {
10356
+ return [
10357
+ parseInt(hex.slice(0, 2), 16),
10358
+ parseInt(hex.slice(2, 4), 16),
10359
+ parseInt(hex.slice(4, 6), 16),
10360
+ parseInt(hex.slice(6, 8), 16),
10361
+ ];
10362
+ }
10363
+ }
10364
+
10365
+ const fn = value.match(/^rgba?\(([^)]+)\)$/);
10366
+ if (fn) {
10367
+ const parts = fn[1].split(/[,/\s]+/).filter(Boolean);
10368
+ const channel = (s) => (s.endsWith('%')
10369
+ ? Math.round((parseFloat(s) / 100) * 255)
10370
+ : Math.round(parseFloat(s)));
10371
+ const r = channel(parts[0]);
10372
+ const g = channel(parts[1]);
10373
+ const b = channel(parts[2]);
10374
+ let a = 255;
10375
+ if (parts.length > 3) {
10376
+ a = parts[3].endsWith('%')
10377
+ ? Math.round((parseFloat(parts[3]) / 100) * 255)
10378
+ : Math.round(parseFloat(parts[3]) * 255);
10379
+ }
10380
+ return [r, g, b, a];
10381
+ }
10382
+
10383
+ // Unrecognised: fall back to opaque black rather than throwing, so an
10384
+ // unusual colour never costs someone a barcode.
10385
+ return [0, 0, 0, 255];
10386
+ }
10387
+
10388
+ __exports.normalizeOptions = normalizeOptions;
10389
+ __exports.parseColor = parseColor;
10390
+ };
10391
+
10392
+ __modules["render/svg.js"] = function (__require, __exports) {
10393
+ /**
10394
+ * SVG output.
10395
+ *
10396
+ * Dark modules are emitted as a single `<path>` with horizontal runs merged,
10397
+ * not as one `<rect>` per module. A version 40 QR symbol has 31329 modules; the
10398
+ * naive rendering is a megabyte of XML that browsers choke on, while the merged
10399
+ * path is a few kilobytes and draws identically.
10400
+ *
10401
+ * @module render/svg
10402
+ */
10403
+ const { normalizeOptions } = __require("render/options.js");
10404
+
10405
+ /**
10406
+ * @param {string} value
10407
+ * @returns {string}
10408
+ */
10409
+ function escapeAttr(value) {
10410
+ return String(value)
10411
+ .replace(/&/g, '&amp;')
10412
+ .replace(/</g, '&lt;')
10413
+ .replace(/>/g, '&gt;')
10414
+ .replace(/"/g, '&quot;');
10415
+ }
10416
+
10417
+ /**
10418
+ * Render to an SVG document.
10419
+ *
10420
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix
10421
+ * @param {import('./options.js').RenderOptions} [options]
10422
+ * @returns {string}
10423
+ */
10424
+ function toSVG(matrix, options = {}) {
10425
+ const opts = normalizeOptions(matrix, options);
10426
+ const { scale, source, pixelWidth, pixelHeight, rowHeight } = opts;
10427
+
10428
+ let path = '';
10429
+ for (let y = 0; y < source.height; y++) {
10430
+ let x = 0;
10431
+ while (x < source.width) {
10432
+ if (!source.get(x, y)) { x++; continue; }
10433
+ let run = 1;
10434
+ while (x + run < source.width && source.get(x + run, y)) run++;
10435
+ // Relative horizontal-vertical path commands: shorter than rects and
10436
+ // free of the seams that appear between adjacent rects at some zooms.
10437
+ path += `M${x * scale} ${y * rowHeight}h${run * scale}v${rowHeight}h${-run * scale}z`;
10438
+ x += run;
10439
+ }
10440
+ }
10441
+
10442
+ const bg = opts.light === 'none'
10443
+ ? ''
10444
+ : `<rect width="${pixelWidth}" height="${pixelHeight}" fill="${escapeAttr(opts.light)}"/>`;
10445
+
10446
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${pixelWidth}" height="${pixelHeight}" ` +
10447
+ `viewBox="0 0 ${pixelWidth} ${pixelHeight}" shape-rendering="crispEdges">` +
10448
+ bg +
10449
+ `<path d="${path}" fill="${escapeAttr(opts.dark)}"/>` +
10450
+ '</svg>';
10451
+ }
10452
+
10453
+ /**
10454
+ * Base64 that works identically in Node and the browser.
10455
+ *
10456
+ * `btoa` is byte-oriented, so the UTF-8 encoding has to happen first — passing
10457
+ * it a string with any character above U+00FF throws.
10458
+ *
10459
+ * @param {string} text
10460
+ * @returns {string}
10461
+ */
10462
+ function toBase64(text) {
10463
+ const bytes = new TextEncoder().encode(text);
10464
+ let binary = '';
10465
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
10466
+ if (typeof btoa === 'function') return btoa(binary);
10467
+ // Node before btoa was global, and non-browser embedders.
10468
+ /* eslint-disable-next-line no-undef */
7425
10469
  return Buffer.from(bytes).toString('base64');
7426
10470
  }
7427
10471
 
@@ -8465,6 +11509,9 @@ const { ONED_FORMATS } = __require("oned/index.js");
8465
11509
  const { decodeOneD } = __require("oned/reader.js");
8466
11510
  const datamatrix = __require("datamatrix/index.js");
8467
11511
  const qr = __require("qr/index.js");
11512
+ const aztec = __require("aztec/index.js");
11513
+ const pdf417 = __require("pdf417/index.js");
11514
+ const micropdf417 = __require("micropdf417/index.js");
8468
11515
  __exports.BitMatrix = BitMatrix;
8469
11516
  const __reexport0 = __require("core/errors.js"); __exports.BarcodeError = __reexport0.BarcodeError; __exports.EncodeError = __reexport0.EncodeError; __exports.NotFoundError = __reexport0.NotFoundError; __exports.FormatError = __reexport0.FormatError; __exports.ChecksumError = __reexport0.ChecksumError;
8470
11517
  const __reexport1 = __require("image/luminance.js"); __exports.LuminanceSource = __reexport1.LuminanceSource;
@@ -8477,6 +11524,9 @@ const __reexport6 = __require("render/index.js"); __exports.renderToCanvasAuto =
8477
11524
  const __reexport7 = __require("render/index.js"); __exports.renderToCanvasAutoAsync = __reexport7.renderToCanvasAutoAsync; __exports.isWebGPUAvailable = __reexport7.isWebGPUAvailable;
8478
11525
  const __reexport8 = __require("qr/index.js"); __exports.encodeQR = __reexport8.encodeQR; __exports.decodeQR = __reexport8.decodeQR; __exports.detectQR = __reexport8.detectQR; __exports.detectAndDecodeQR = __reexport8.detectAndDecodeQR;
8479
11526
  const __reexport9 = __require("datamatrix/index.js"); __exports.encodeDataMatrix = __reexport9.encodeDataMatrix; __exports.decodeDataMatrix = __reexport9.decodeDataMatrix; __exports.detectDataMatrix = __reexport9.detectDataMatrix; __exports.detectAndDecodeDataMatrix = __reexport9.detectAndDecodeDataMatrix;
11527
+ const __reexport10 = __require("aztec/index.js"); __exports.encodeAztec = __reexport10.encodeAztec; __exports.decodeAztec = __reexport10.decodeAztec; __exports.detectAztec = __reexport10.detectAztec; __exports.detectAndDecodeAztec = __reexport10.detectAndDecodeAztec;
11528
+ const __reexport11 = __require("pdf417/index.js"); __exports.encodePDF417 = __reexport11.encodePDF417; __exports.decodePDF417 = __reexport11.decodePDF417; __exports.detectPDF417 = __reexport11.detectPDF417; __exports.detectAndDecodePDF417 = __reexport11.detectAndDecodePDF417;
11529
+ const __reexport12 = __require("micropdf417/index.js"); __exports.encodeMicroPDF417 = __reexport12.encodeMicroPDF417; __exports.decodeMicroPDF417 = __reexport12.decodeMicroPDF417; __exports.detectMicroPDF417 = __reexport12.detectMicroPDF417; __exports.detectAndDecodeMicroPDF417 = __reexport12.detectAndDecodeMicroPDF417;
8480
11530
 
8481
11531
  /**
8482
11532
  * @typedef {object} FormatInfo
@@ -8502,6 +11552,16 @@ const qrCanDecode = qrPresent &&
8502
11552
  typeof qr.detectAndDecodeQR === 'function' && qr.QR_CAN_DECODE !== false;
8503
11553
  const dataMatrixCanEncode = typeof datamatrix.encodeDataMatrix === 'function';
8504
11554
  const dataMatrixCanDecode = typeof datamatrix.detectAndDecodeDataMatrix === 'function';
11555
+ const aztecCanEncode = typeof aztec.encodeAztec === 'function';
11556
+ const aztecCanDecode = typeof aztec.detectAndDecodeAztec === 'function';
11557
+ const pdf417CanEncode = typeof pdf417.encodePDF417 === 'function';
11558
+ // The matrix decoder is complete, but automatic image localization is still
11559
+ // limited to clean module-aligned symbols or an application-supplied
11560
+ // quadrilateral. Keep the generic scanner capability opt-in until a
11561
+ // perspective/noise corpus is passed.
11562
+ const pdf417CanDecode = typeof pdf417.detectAndDecodePDF417 === 'function';
11563
+ const microPdf417CanEncode = typeof micropdf417.encodeMicroPDF417 === 'function';
11564
+ const microPdf417CanDecode = typeof micropdf417.detectAndDecodeMicroPDF417 === 'function';
8505
11565
 
8506
11566
  /**
8507
11567
  * Every format this build supports.
@@ -8536,6 +11596,27 @@ function listFormats() {
8536
11596
  canRead: dataMatrixCanDecode,
8537
11597
  kind: /** @type {'2D'} */ ('2D'),
8538
11598
  });
11599
+ formats.push({
11600
+ id: 'aztec',
11601
+ label: 'Aztec Code',
11602
+ canWrite: aztecCanEncode,
11603
+ canRead: aztecCanDecode,
11604
+ kind: /** @type {'2D'} */ ('2D'),
11605
+ });
11606
+ formats.push({
11607
+ id: 'pdf417',
11608
+ label: 'PDF417',
11609
+ canWrite: pdf417CanEncode,
11610
+ canRead: pdf417CanDecode,
11611
+ kind: /** @type {'2D'} */ ('2D'),
11612
+ });
11613
+ formats.push({
11614
+ id: 'micropdf417',
11615
+ label: 'MicroPDF417',
11616
+ canWrite: microPdf417CanEncode,
11617
+ canRead: microPdf417CanDecode,
11618
+ kind: /** @type {'2D'} */ ('2D'),
11619
+ });
8539
11620
 
8540
11621
  return formats;
8541
11622
  }
@@ -8556,6 +11637,16 @@ function listFormats() {
8556
11637
  * @param {boolean} [options.checkDigit] Append a check digit, where optional.
8557
11638
  * @param {boolean} [options.fullAscii] Code 39 extended encoding.
8558
11639
  * @param {boolean} [options.gs1] Emit a leading FNC1.
11640
+ * @param {number} [options.layers] Aztec layer count; automatic if omitted.
11641
+ * @param {boolean} [options.compact] Force an Aztec Compact or Full symbol.
11642
+ * @param {number} [options.eccPercent] Requested Aztec error-correction percentage.
11643
+ * @param {number} [options.eccLevel] PDF417 error-correction level, 0-8.
11644
+ * @param {number} [options.columns] PDF417 columns, 1-30.
11645
+ * @param {number} [options.rows] PDF417 rows, 3-90.
11646
+ * @param {number} [options.rowHeight] PDF417 row height in modules.
11647
+ * @param {'auto'|'text'|'byte'|'numeric'} [options.compaction] PDF417 compaction mode.
11648
+ * @param {number} [options.eci] MicroPDF417 byte-compaction ECI assignment (3 or 26).
11649
+ * @param {number} [options.aspectRatio] Preferred MicroPDF417 symbol aspect ratio.
8559
11650
  * @returns {BitMatrix}
8560
11651
  */
8561
11652
  function encode(text, options = {}) {
@@ -8568,10 +11659,19 @@ function encode(text, options = {}) {
8568
11659
  if (format === 'datamatrix' || format === 'data-matrix') {
8569
11660
  return datamatrix.encodeDataMatrix(value, options);
8570
11661
  }
11662
+ if (format === 'aztec' || format === 'aztec-code') {
11663
+ return aztec.encodeAztec(value, options);
11664
+ }
11665
+ if (format === 'pdf417' || format === 'pdf-417') {
11666
+ return pdf417.encodePDF417(value, options);
11667
+ }
11668
+ if (format === 'micropdf417' || format === 'micro-pdf417' || format === 'micro-pdf-417') {
11669
+ return micropdf417.encodeMicroPDF417(value, options);
11670
+ }
8571
11671
 
8572
11672
  const entry = ONED_FORMATS[format];
8573
11673
  if (!entry) {
8574
- const known = [...Object.keys(ONED_FORMATS), 'qr', 'datamatrix'].join(', ');
11674
+ const known = [...Object.keys(ONED_FORMATS), 'qr', 'datamatrix', 'aztec', 'pdf417', 'micropdf417'].join(', ');
8575
11675
  throw new EncodeError(`Unknown format "${format}". Known formats: ${known}`);
8576
11676
  }
8577
11677
  return entry.encode(value, options);
@@ -8581,9 +11681,19 @@ function encode(text, options = {}) {
8581
11681
  * @typedef {object} DecodeResult
8582
11682
  * @property {string} text
8583
11683
  * @property {string} format
8584
- * @property {Uint8Array} [bytes] Raw payload, before text decoding.
11684
+ * @property {Uint8Array} [bytes] Raw octets exposed by byte-oriented payload modes, before text decoding.
11685
+ * @property {{mode: 'text'|'byte'|'numeric', text: string, bytes: Uint8Array, eci: number, latch: number|null, codewordStart: number, codewordEnd: number}[]} [segments] PDF417 compaction segments in source order.
8585
11686
  * @property {number} [version] QR version.
8586
11687
  * @property {string} [ecc] QR error-correction level.
11688
+ * @property {number} [layers] Aztec layer count.
11689
+ * @property {boolean} [compact] Whether an Aztec symbol is Compact.
11690
+ * @property {number} [corrections] Reed–Solomon corrections applied by an Aztec decode.
11691
+ * @property {number} [rows] PDF417 row count.
11692
+ * @property {number} [columns] PDF417 column count.
11693
+ * @property {number} [eccLevel] PDF417 error-correction level.
11694
+ * @property {number} [rowHeight] PDF417 row height in modules.
11695
+ * @property {number} [variant] MicroPDF417 predefined variant number.
11696
+ * @property {number} [eccCodewords] MicroPDF417 fixed error-correction codewords.
8587
11697
  */
8588
11698
 
8589
11699
  /**
@@ -8605,6 +11715,9 @@ function decode(image, options = {}) {
8605
11715
  const want = formats ? new Set(formats.map((f) => f.toLowerCase())) : null;
8606
11716
  const wantQR = !want || want.has('qr') || want.has('qrcode');
8607
11717
  const wantDataMatrix = !want || want.has('datamatrix') || want.has('data-matrix');
11718
+ const wantAztec = !want || want.has('aztec') || want.has('aztec-code');
11719
+ const wantPDF417 = !want || want.has('pdf417') || want.has('pdf-417');
11720
+ const wantMicroPDF417 = !want || want.has('micropdf417') || want.has('micro-pdf417') || want.has('micro-pdf-417');
8608
11721
  const wantOneD = !want || [...want].some((f) => f in ONED_FORMATS);
8609
11722
 
8610
11723
  const source = LuminanceSource.fromImageData(image);
@@ -8642,6 +11755,45 @@ function decode(image, options = {}) {
8642
11755
  }
8643
11756
  }
8644
11757
 
11758
+ if (wantAztec && aztecCanDecode) {
11759
+ // The central bull's-eye is a small, high-contrast target. Hybrid
11760
+ // thresholding can flatten it on clean rendered symbols, so mirror the
11761
+ // Data Matrix global fallback in auto mode.
11762
+ const aztecBits = binarizer === 'auto' ? [bits, binarize(pass, 'global')] : [bits];
11763
+ for (const candidateBits of aztecBits) {
11764
+ try {
11765
+ const found = aztec.detectAndDecodeAztec(candidateBits);
11766
+ if (found) { results.push({ ...found, format: 'aztec' }); break; }
11767
+ } catch {
11768
+ /* no Aztec code with this threshold */
11769
+ }
11770
+ }
11771
+ }
11772
+
11773
+ if (wantPDF417 && pdf417CanDecode) {
11774
+ try {
11775
+ const found = pdf417.detectAndDecodePDF417(bits);
11776
+ if (found) results.push({ ...found, format: 'pdf417' });
11777
+ } catch {
11778
+ /* no PDF417 in this pass */
11779
+ }
11780
+ }
11781
+
11782
+ if (wantMicroPDF417 && microPdf417CanDecode) {
11783
+ // MicroPDF417 detection measures runs across the whole raster. Hybrid
11784
+ // thresholding can alter uniform modules near local-window boundaries,
11785
+ // so retry the global threshold in auto mode as for the other 2D codes.
11786
+ const microPdf417Bits = binarizer === 'auto' ? [bits, binarize(pass, 'global')] : [bits];
11787
+ for (const candidateBits of microPdf417Bits) {
11788
+ try {
11789
+ const found = micropdf417.detectAndDecodeMicroPDF417(candidateBits);
11790
+ if (found) { results.push({ ...found, format: 'micropdf417' }); break; }
11791
+ } catch {
11792
+ /* no MicroPDF417 with this threshold */
11793
+ }
11794
+ }
11795
+ }
11796
+
8645
11797
  if (wantOneD) {
8646
11798
  const oneDFormats = want ? [...want].filter((f) => f in ONED_FORMATS) : null;
8647
11799
  for (const found of decodeOneD(bits, { formats: oneDFormats, tryHarder })) {
@@ -8676,7 +11828,7 @@ function decodeStrict(image, options) {
8676
11828
  }
8677
11829
 
8678
11830
  /** Library version, matching package.json. */
8679
- const VERSION = '1.0.0';
11831
+ const VERSION = '1.2.5';
8680
11832
 
8681
11833
  __exports.listFormats = listFormats;
8682
11834
  __exports.encode = encode;
@@ -8701,17 +11853,27 @@ export const {
8701
11853
  binarizeGlobal,
8702
11854
  binarizeHybrid,
8703
11855
  decode,
11856
+ decodeAztec,
8704
11857
  decodeDataMatrix,
11858
+ decodeMicroPDF417,
8705
11859
  decodeOneD,
8706
11860
  decodeOneDStrict,
11861
+ decodePDF417,
8707
11862
  decodeQR,
8708
11863
  decodeStrict,
11864
+ detectAndDecodeAztec,
8709
11865
  detectAndDecodeDataMatrix,
11866
+ detectAndDecodeMicroPDF417,
11867
+ detectAndDecodePDF417,
8710
11868
  detectAndDecodeQR,
11869
+ detectAztec,
8711
11870
  detectDataMatrix,
11871
+ detectMicroPDF417,
11872
+ detectPDF417,
8712
11873
  detectQR,
8713
11874
  ean13CheckDigit,
8714
11875
  encode,
11876
+ encodeAztec,
8715
11877
  encodeCodabar,
8716
11878
  encodeCode11,
8717
11879
  encodeCode128,
@@ -8724,6 +11886,8 @@ export const {
8724
11886
  encodeITF,
8725
11887
  encodeITF14,
8726
11888
  encodeMSI,
11889
+ encodeMicroPDF417,
11890
+ encodePDF417,
8727
11891
  encodePharmacode,
8728
11892
  encodeQR,
8729
11893
  encodeUPCA,