@sythos/js_barcode_universal 1.0.0 → 1.1.0

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.
@@ -1,5 +1,5 @@
1
1
  /*!
2
- * Sythos Barcode Suite v1.0.0
2
+ * Sythos Barcode Suite v1.1.0
3
3
  *
4
4
  * MIT License
5
5
  *
@@ -2918,6 +2918,9 @@ const GF256_QR = new GaloisField({ size: 256, primitive: 0x011d, name: 'GF(256)/
2918
2918
  /** Data Matrix ECC200. x^8 + x^5 + x^3 + x^2 + 1 */
2919
2919
  const GF256_DM = new GaloisField({ size: 256, primitive: 0x012d, name: 'GF(256)/DataMatrix' });
2920
2920
 
2921
+ /** Aztec's eight-bit data field is algebraically identical to Data Matrix's. */
2922
+ const GF256_AZTEC = GF256_DM;
2923
+
2921
2924
  /** PDF417. Prime field; 3 is a primitive root modulo 929. */
2922
2925
  const GF929 = new GaloisField({ size: 929, prime: true, generator: 3, name: 'GF(929)' });
2923
2926
 
@@ -2930,6 +2933,7 @@ const GF4096 = new GaloisField({ size: 4096, primitive: 0x1069, name: 'GF(4096)'
2930
2933
  __exports.GaloisField = GaloisField;
2931
2934
  __exports.GF256_QR = GF256_QR;
2932
2935
  __exports.GF256_DM = GF256_DM;
2936
+ __exports.GF256_AZTEC = GF256_AZTEC;
2933
2937
  __exports.GF929 = GF929;
2934
2938
  __exports.GF16 = GF16;
2935
2939
  __exports.GF64 = GF64;
@@ -2965,7 +2969,7 @@ const { ChecksumError } = __require("core/errors.js");
2965
2969
  *
2966
2970
  * g(x) = product over i of (x - a^(base + i)), i = 0 .. eccLen-1
2967
2971
  *
2968
- * `base` is 0 for QR and Aztec; 1 for Data Matrix and PDF417.
2972
+ * `base` is 0 for QR; 1 for Aztec, Data Matrix and PDF417.
2969
2973
  *
2970
2974
  * @param {number} eccLen
2971
2975
  * @param {import('./galois-field.js').GaloisField} field
@@ -7209,6 +7213,1122 @@ const __reexport2 = __require("qr/detector.js"); __exports.detectQR = __reexport
7209
7213
  const __reexport3 = __require("qr/tables.js"); __exports.validateTables = __reexport3.validateTables;
7210
7214
 
7211
7215
 
7216
+ };
7217
+
7218
+ __modules["aztec/high-level.js"] = function (__require, __exports) {
7219
+ /**
7220
+ * Aztec high-level stream writer.
7221
+ *
7222
+ * The output is deliberately a `BitWriter`, rather than a byte array: Aztec's
7223
+ * text controls and binary-shift lengths are not byte aligned. This module is
7224
+ * also the boundary where JavaScript strings become UTF-8. Passing a byte
7225
+ * view bypasses that conversion and preserves every octet unchanged.
7226
+ *
7227
+ * The initial state mandated by the symbology is UPPER. The greedy text pass
7228
+ * uses UPPER, LOWER, DIGIT and PUNCT tables, selecting the shortest available
7229
+ * latch at each byte. Bytes without a text-table representation are emitted
7230
+ * through the standard B/S (binary shift) escape. B/S is available from
7231
+ * UPPER and makes this a complete, lossless representation of UTF-8 payloads.
7232
+ *
7233
+ * @module aztec/high-level
7234
+ */
7235
+ const { BitWriter } = __require("core/bit-buffer.js");
7236
+ const { EncodeError } = __require("core/errors.js");
7237
+
7238
+ /** Aztec high-level table identifiers, exposed for decoder/API symmetry. */
7239
+ const HIGH_LEVEL_MODE = Object.freeze({
7240
+ UPPER: 0,
7241
+ LOWER: 1,
7242
+ DIGIT: 2,
7243
+ MIXED: 3,
7244
+ PUNCT: 4,
7245
+ });
7246
+
7247
+ /** Maximum number of bytes represented by one B/S escape. */
7248
+ const MAX_BINARY_SHIFT = 2078;
7249
+
7250
+ /**
7251
+ * Convert accepted public input to its encoded octets.
7252
+ *
7253
+ * @param {string|ArrayBuffer|ArrayBufferView} value
7254
+ * @param {'utf-8'} [charset]
7255
+ * @returns {Uint8Array}
7256
+ */
7257
+ function aztecBytes(value, charset = 'utf-8') {
7258
+ if (charset !== 'utf-8') throw new EncodeError(`Aztec: unsupported charset "${charset}"`);
7259
+ if (typeof value === 'string') return new TextEncoder().encode(value);
7260
+ if (value instanceof ArrayBuffer) return new Uint8Array(value);
7261
+ if (ArrayBuffer.isView(value)) {
7262
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
7263
+ }
7264
+ throw new EncodeError('Aztec: value must be a string, ArrayBuffer, or byte view');
7265
+ }
7266
+
7267
+ /** @param {number} byte @returns {number} UPPER-table value, or -1. */
7268
+ function upperValue(byte) {
7269
+ if (byte === 0x20) return 1;
7270
+ if (byte >= 0x41 && byte <= 0x5a) return byte - 0x41 + 2;
7271
+ return -1;
7272
+ }
7273
+
7274
+ /** Aztec's latch table, packed as `(bitCount << 16) | bits`. */
7275
+ const LATCH = Object.freeze([
7276
+ [0, 327708, 327710, 327709, 656318],
7277
+ [590318, 0, 327710, 327709, 656318],
7278
+ [262158, 590300, 0, 590301, 932798],
7279
+ [327709, 327708, 656322, 0, 327710],
7280
+ [327711, 656380, 656382, 656381, 0],
7281
+ ]);
7282
+
7283
+ /** @param {number} byte @returns {number} */
7284
+ function lowerValue(byte) {
7285
+ if (byte === 0x20) return 1;
7286
+ if (byte >= 0x61 && byte <= 0x7a) return byte - 0x61 + 2;
7287
+ return -1;
7288
+ }
7289
+
7290
+ /** @param {number} byte @returns {number} */
7291
+ function digitValue(byte) {
7292
+ if (byte === 0x20) return 1;
7293
+ if (byte >= 0x30 && byte <= 0x39) return byte - 0x30 + 2;
7294
+ if (byte === 0x2c) return 12;
7295
+ if (byte === 0x2e) return 13;
7296
+ return -1;
7297
+ }
7298
+
7299
+ const PUNCT = new Map([
7300
+ [0x0d, 1], [0x21, 6], [0x22, 7], [0x23, 8], [0x24, 9], [0x25, 10],
7301
+ [0x26, 11], [0x27, 12], [0x28, 13], [0x29, 14], [0x2a, 15], [0x2b, 16],
7302
+ [0x2c, 17], [0x2d, 18], [0x2e, 19], [0x2f, 20], [0x3a, 21], [0x3b, 22],
7303
+ [0x3c, 23], [0x3d, 24], [0x3e, 25], [0x3f, 26], [0x5b, 27], [0x5d, 28],
7304
+ [0x7b, 29], [0x7d, 30],
7305
+ ]);
7306
+
7307
+ /** @param {number} byte @param {number} mode @returns {number} */
7308
+ function textValue(byte, mode) {
7309
+ switch (mode) {
7310
+ case HIGH_LEVEL_MODE.UPPER: return upperValue(byte);
7311
+ case HIGH_LEVEL_MODE.LOWER: return lowerValue(byte);
7312
+ case HIGH_LEVEL_MODE.DIGIT: return digitValue(byte);
7313
+ case HIGH_LEVEL_MODE.PUNCT: return PUNCT.get(byte) ?? -1;
7314
+ default: return -1;
7315
+ }
7316
+ }
7317
+
7318
+ /** @param {BitWriter} writer @param {number} from @param {number} to */
7319
+ function latch(writer, from, to) {
7320
+ if (from === to) return;
7321
+ const packed = LATCH[from][to];
7322
+ writer.put(packed & 0xffff, packed >>> 16);
7323
+ }
7324
+
7325
+ /** @param {number} mode @returns {number} */
7326
+ function characterWidth(mode) {
7327
+ return mode === HIGH_LEVEL_MODE.DIGIT ? 4 : 5;
7328
+ }
7329
+
7330
+ /**
7331
+ * Write an Aztec binary-shift segment while in UPPER mode.
7332
+ *
7333
+ * B/S is `11111`; its five-bit length directly covers 1..31 bytes. A zero
7334
+ * length selects the extended eleven-bit form, whose stored value is n - 31.
7335
+ * Splitting at 2078 keeps each control representable and makes arbitrarily
7336
+ * long byte input well-defined.
7337
+ *
7338
+ * @param {BitWriter} writer
7339
+ * @param {Uint8Array} bytes
7340
+ * @param {number} start
7341
+ * @param {number} length
7342
+ */
7343
+ function writeBinaryShift(writer, bytes, start, length) {
7344
+ let at = start;
7345
+ let left = length;
7346
+ while (left > 0) {
7347
+ const count = Math.min(left, MAX_BINARY_SHIFT);
7348
+ writer.put(31, 5); // UPPER B/S
7349
+ if (count <= 31) writer.put(count, 5);
7350
+ else {
7351
+ writer.put(0, 5);
7352
+ writer.put(count - 31, 11);
7353
+ }
7354
+ for (let i = 0; i < count; i++) writer.put(bytes[at + i], 8);
7355
+ at += count;
7356
+ left -= count;
7357
+ }
7358
+ }
7359
+
7360
+ /**
7361
+ * Build a valid Aztec high-level bitstream.
7362
+ *
7363
+ * @param {string|ArrayBuffer|ArrayBufferView} value
7364
+ * @param {{charset?: 'utf-8'}} [options]
7365
+ * @returns {BitWriter}
7366
+ */
7367
+ function encodeHighLevel(value, options = {}) {
7368
+ const bytes = aztecBytes(value, options.charset ?? 'utf-8');
7369
+ const writer = new BitWriter();
7370
+ let mode = HIGH_LEVEL_MODE.UPPER;
7371
+
7372
+ for (let at = 0; at < bytes.length;) {
7373
+ let bestMode = -1;
7374
+ let bestValue = -1;
7375
+ let bestCost = Number.POSITIVE_INFINITY;
7376
+ for (const candidate of [HIGH_LEVEL_MODE.UPPER, HIGH_LEVEL_MODE.LOWER, HIGH_LEVEL_MODE.DIGIT, HIGH_LEVEL_MODE.PUNCT]) {
7377
+ const value = textValue(bytes[at], candidate);
7378
+ if (value < 0) continue;
7379
+ const latchCost = candidate === mode ? 0 : LATCH[mode][candidate] >>> 16;
7380
+ const cost = latchCost + characterWidth(candidate);
7381
+ if (cost < bestCost) { bestCost = cost; bestMode = candidate; bestValue = value; }
7382
+ }
7383
+ if (bestMode >= 0) {
7384
+ latch(writer, mode, bestMode);
7385
+ writer.put(bestValue, characterWidth(bestMode));
7386
+ mode = bestMode;
7387
+ at++;
7388
+ } else {
7389
+ // B/S is defined from UPPER; the latch is retained after the shift.
7390
+ latch(writer, mode, HIGH_LEVEL_MODE.UPPER);
7391
+ mode = HIGH_LEVEL_MODE.UPPER;
7392
+ const start = at;
7393
+ 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++;
7394
+ writeBinaryShift(writer, bytes, start, at - start);
7395
+ }
7396
+ }
7397
+ return writer;
7398
+ }
7399
+
7400
+ __exports.HIGH_LEVEL_MODE = HIGH_LEVEL_MODE;
7401
+ __exports.MAX_BINARY_SHIFT = MAX_BINARY_SHIFT;
7402
+ __exports.aztecBytes = aztecBytes;
7403
+ __exports.writeBinaryShift = writeBinaryShift;
7404
+ __exports.encodeHighLevel = encodeHighLevel;
7405
+ };
7406
+
7407
+ __modules["aztec/tables.js"] = function (__require, __exports) {
7408
+ /**
7409
+ * Aztec Code layer geometry and Reed-Solomon parameters.
7410
+ *
7411
+ * `totalBits` counts the payload ring before its leading pad bits are added;
7412
+ * consequently only `usableBits` can be partitioned into codewords. Compact
7413
+ * symbols have no reference grid. Full symbols insert alternating reference
7414
+ * rows and columns every 16 modules around the centre.
7415
+ *
7416
+ * The five data fields use generator base 1. GF(256)/DataMatrix is also the
7417
+ * Aztec 8-bit field: both use primitive polynomial 0x12d.
7418
+ *
7419
+ * @module aztec/tables
7420
+ */
7421
+ const { GF16, GF64, GF256_AZTEC, GF1024, GF4096 } = __require("core/galois-field.js");
7422
+
7423
+ /** Reed-Solomon generator base defined for Aztec parameter and data fields. */
7424
+ const AZTEC_RS_GENERATOR_BASE = 1;
7425
+
7426
+ /** Minimum recommended error correction: 23 percent plus three codewords. */
7427
+ const AZTEC_DEFAULT_ECC_PERCENT = 23;
7428
+ const AZTEC_MIN_ECC_WORDS = 3;
7429
+
7430
+ /** Word size selected solely by the number of layers. */
7431
+ function wordSizeForLayers(layers) {
7432
+ if (!Number.isInteger(layers) || layers < 1 || layers > 32) {
7433
+ throw new RangeError(`Aztec: layers must be an integer from 1 to 32 (got ${layers})`);
7434
+ }
7435
+ if (layers <= 2) return 6;
7436
+ if (layers <= 8) return 8;
7437
+ if (layers <= 22) return 10;
7438
+ return 12;
7439
+ }
7440
+
7441
+ /** Return the field used by Aztec codewords of `wordSize` bits. */
7442
+ function fieldForWordSize(wordSize) {
7443
+ switch (wordSize) {
7444
+ case 4: return GF16; // Mode message only.
7445
+ case 6: return GF64;
7446
+ case 8: return GF256_AZTEC;
7447
+ case 10: return GF1024;
7448
+ case 12: return GF4096;
7449
+ default: throw new RangeError(`Aztec: unsupported codeword size ${wordSize}`);
7450
+ }
7451
+ }
7452
+
7453
+ /** Return the data field selected for a symbol with `layers` layers. */
7454
+ function fieldForLayers(layers) {
7455
+ return fieldForWordSize(wordSizeForLayers(layers));
7456
+ }
7457
+
7458
+ /** Matrix side length, including Full-mode reference grid lines. */
7459
+ function aztecSymbolSize(layers, compact = false) {
7460
+ if (!Number.isInteger(layers) || layers < 1 || layers > (compact ? 4 : 32)) {
7461
+ throw new RangeError(`Aztec: ${compact ? 'Compact' : 'Full'} layers out of range: ${layers}`);
7462
+ }
7463
+ if (compact) return 11 + 4 * layers;
7464
+ const baseMatrixSize = 14 + 4 * layers;
7465
+ return baseMatrixSize + 1 + 2 * Math.floor((baseMatrixSize / 2 - 1) / 15);
7466
+ }
7467
+
7468
+ function layer(layers, compact) {
7469
+ const wordSize = wordSizeForLayers(layers);
7470
+ const totalBits = ((compact ? 88 : 112) + 16 * layers) * layers;
7471
+ const usableBits = totalBits - totalBits % wordSize;
7472
+ const totalCodewords = usableBits / wordSize;
7473
+ const baseMatrixSize = (compact ? 11 : 14) + 4 * layers;
7474
+ return Object.freeze({
7475
+ compact,
7476
+ layers,
7477
+ wordSize,
7478
+ totalBits,
7479
+ usableBits,
7480
+ totalCodewords,
7481
+ // Compact mode encodes the count in six bits and can therefore hold no
7482
+ // more than 64 data codewords even where the ring itself is larger.
7483
+ maxDataCodewords: compact ? Math.min(totalCodewords, 64) : totalCodewords,
7484
+ baseMatrixSize,
7485
+ symbolSize: aztecSymbolSize(layers, compact),
7486
+ modeMessageDataWords: compact ? 2 : 4,
7487
+ modeMessageWords: compact ? 7 : 10,
7488
+ modeMessageBits: compact ? 28 : 40,
7489
+ rsGeneratorBase: AZTEC_RS_GENERATOR_BASE,
7490
+ });
7491
+ }
7492
+
7493
+ /** Compact Aztec layers 1 through 4, in encoding preference order. */
7494
+ const AZTEC_COMPACT_LAYERS = Object.freeze(
7495
+ Array.from({ length: 4 }, (_, i) => layer(i + 1, true)),
7496
+ );
7497
+
7498
+ /** Full Aztec layers 1 through 32, in ascending layer order. */
7499
+ const AZTEC_FULL_LAYERS = Object.freeze(
7500
+ Array.from({ length: 32 }, (_, i) => layer(i + 1, false)),
7501
+ );
7502
+
7503
+ /** All allowed symbols. Compact entries precede Full entries for automatic selection. */
7504
+ const AZTEC_LAYERS = Object.freeze([
7505
+ ...AZTEC_COMPACT_LAYERS,
7506
+ ...AZTEC_FULL_LAYERS,
7507
+ ]);
7508
+
7509
+ /** Return one immutable layer record. */
7510
+ function aztecLayer(layers, compact = false) {
7511
+ if (!Number.isInteger(layers) || layers < 1 || layers > (compact ? 4 : 32)) {
7512
+ throw new RangeError(`Aztec: ${compact ? 'Compact' : 'Full'} layers out of range: ${layers}`);
7513
+ }
7514
+ return (compact ? AZTEC_COMPACT_LAYERS : AZTEC_FULL_LAYERS)[layers - 1];
7515
+ }
7516
+
7517
+ /**
7518
+ * Calculate the minimum parity count for a data word count.
7519
+ *
7520
+ * The percentage is rounded up because a fractional codeword cannot be
7521
+ * emitted. The mandatory three words protect short payloads, where a bare
7522
+ * percentage would otherwise round to zero.
7523
+ */
7524
+ function eccCodewordsFor(dataCodewords, eccPercent = AZTEC_DEFAULT_ECC_PERCENT) {
7525
+ if (!Number.isInteger(dataCodewords) || dataCodewords < 0) {
7526
+ throw new RangeError(`Aztec: data codewords must be a non-negative integer (got ${dataCodewords})`);
7527
+ }
7528
+ if (!Number.isFinite(eccPercent) || eccPercent < 0 || eccPercent > 100) {
7529
+ throw new RangeError(`Aztec: ECC percent must be between 0 and 100 (got ${eccPercent})`);
7530
+ }
7531
+ return Math.ceil(dataCodewords * eccPercent / 100) + AZTEC_MIN_ECC_WORDS;
7532
+ }
7533
+
7534
+ /**
7535
+ * Choose the first symbol which holds an already stuffed payload.
7536
+ *
7537
+ * `dataBits` must be a multiple of the candidate word size; callers which
7538
+ * start from high-level bits must stuff separately per candidate word size.
7539
+ */
7540
+ function selectAztecLayer(dataBits, {
7541
+ eccPercent = AZTEC_DEFAULT_ECC_PERCENT,
7542
+ layers = null,
7543
+ compact = null,
7544
+ } = {}) {
7545
+ if (!Number.isInteger(dataBits) || dataBits < 0) {
7546
+ throw new RangeError(`Aztec: data bits must be a non-negative integer (got ${dataBits})`);
7547
+ }
7548
+ if (compact !== null && typeof compact !== 'boolean') {
7549
+ throw new TypeError('Aztec: compact must be true, false or null');
7550
+ }
7551
+
7552
+ let candidates;
7553
+ if (layers !== null) {
7554
+ if (compact === null) throw new TypeError('Aztec: compact must be specified when layers is specified');
7555
+ candidates = [aztecLayer(layers, compact)];
7556
+ } else if (compact === null) {
7557
+ candidates = AZTEC_LAYERS;
7558
+ } else {
7559
+ candidates = compact ? AZTEC_COMPACT_LAYERS : AZTEC_FULL_LAYERS;
7560
+ }
7561
+
7562
+ for (const candidate of candidates) {
7563
+ if (dataBits % candidate.wordSize !== 0) continue;
7564
+ const dataCodewords = dataBits / candidate.wordSize;
7565
+ const eccCodewords = eccCodewordsFor(dataCodewords, eccPercent);
7566
+ if (dataCodewords <= candidate.maxDataCodewords &&
7567
+ dataCodewords + eccCodewords <= candidate.totalCodewords) {
7568
+ return Object.freeze({ ...candidate, dataCodewords, eccCodewords });
7569
+ }
7570
+ }
7571
+
7572
+ throw new RangeError('Aztec: payload and requested error correction do not fit an available symbol');
7573
+ }
7574
+
7575
+ /** Check static identities so table corruption fails explicitly in tests. */
7576
+ function validateAztecTables() {
7577
+ const issues = [];
7578
+ for (const entry of AZTEC_LAYERS) {
7579
+ if (entry.usableBits % entry.wordSize !== 0) issues.push(`${entry.compact ? 'C' : 'F'}${entry.layers}: unaligned usable bits`);
7580
+ if (entry.totalCodewords !== entry.usableBits / entry.wordSize) issues.push(`${entry.compact ? 'C' : 'F'}${entry.layers}: codeword mismatch`);
7581
+ if (entry.symbolSize !== aztecSymbolSize(entry.layers, entry.compact)) issues.push(`${entry.compact ? 'C' : 'F'}${entry.layers}: matrix size mismatch`);
7582
+ if (entry.rsGeneratorBase !== AZTEC_RS_GENERATOR_BASE) issues.push(`${entry.compact ? 'C' : 'F'}${entry.layers}: generator base mismatch`);
7583
+ if (entry.compact && entry.maxDataCodewords > 64) issues.push(`C${entry.layers}: Compact data-word limit exceeded`);
7584
+ }
7585
+ return issues;
7586
+ }
7587
+
7588
+ __exports.AZTEC_RS_GENERATOR_BASE = AZTEC_RS_GENERATOR_BASE;
7589
+ __exports.AZTEC_DEFAULT_ECC_PERCENT = AZTEC_DEFAULT_ECC_PERCENT;
7590
+ __exports.AZTEC_MIN_ECC_WORDS = AZTEC_MIN_ECC_WORDS;
7591
+ __exports.wordSizeForLayers = wordSizeForLayers;
7592
+ __exports.fieldForWordSize = fieldForWordSize;
7593
+ __exports.fieldForLayers = fieldForLayers;
7594
+ __exports.aztecSymbolSize = aztecSymbolSize;
7595
+ __exports.AZTEC_COMPACT_LAYERS = AZTEC_COMPACT_LAYERS;
7596
+ __exports.AZTEC_FULL_LAYERS = AZTEC_FULL_LAYERS;
7597
+ __exports.AZTEC_LAYERS = AZTEC_LAYERS;
7598
+ __exports.aztecLayer = aztecLayer;
7599
+ __exports.eccCodewordsFor = eccCodewordsFor;
7600
+ __exports.selectAztecLayer = selectAztecLayer;
7601
+ __exports.validateAztecTables = validateAztecTables;
7602
+ };
7603
+
7604
+ __modules["aztec/encoder.js"] = function (__require, __exports) {
7605
+ /**
7606
+ * Aztec encoder: high-level bits, bit stuffing, Reed-Solomon and matrix layout.
7607
+ *
7608
+ * `tables.js` is intentionally the source of geometry and field selection.
7609
+ * Its `aztecLayer(layers, compact)` entries must expose `totalBits`,
7610
+ * `totalCodewords`, `baseMatrixSize` and `symbolSize`; `fieldForLayers()` must
7611
+ * return the matching binary field. All Aztec Reed-Solomon generators start
7612
+ * at alpha^1, hence the explicit base `1` in both data and mode messages.
7613
+ *
7614
+ * @module aztec/encoder
7615
+ */
7616
+ const { BitWriter } = __require("core/bit-buffer.js");
7617
+ const { BitMatrix } = __require("core/bit-matrix.js");
7618
+ const { EncodeError } = __require("core/errors.js");
7619
+ const { rsEncode } = __require("core/reed-solomon.js");
7620
+ const { encodeHighLevel } = __require("aztec/high-level.js");
7621
+ const { AZTEC_COMPACT_LAYERS, AZTEC_FULL_LAYERS, aztecLayer, eccCodewordsFor, fieldForLayers, fieldForWordSize, wordSizeForLayers } = __require("aztec/tables.js");
7622
+
7623
+ /** @param {BitWriter} bits @param {number} at @returns {boolean} */
7624
+ function bitAt(bits, at) {
7625
+ return at >= 0 && at < bits.length && ((bits.bytes[at >>> 3] >>> (7 - (at & 7))) & 1) !== 0;
7626
+ }
7627
+
7628
+ /** @param {BitWriter} bits @param {number} from @param {number} count @returns {number} */
7629
+ function readBits(bits, from, count) {
7630
+ let value = 0;
7631
+ for (let i = 0; i < count; i++) value = (value << 1) | (bitAt(bits, from + i) ? 1 : 0);
7632
+ return value;
7633
+ }
7634
+
7635
+ /**
7636
+ * Prevent all-zero and all-one codewords except their final bit. The final
7637
+ * bit is intentionally re-consumed after a stuffed word; it is the mechanism
7638
+ * that makes the transform injective and reversible.
7639
+ *
7640
+ * @param {BitWriter} bits @param {number} wordSize @returns {BitWriter}
7641
+ */
7642
+ function stuffBits(bits, wordSize) {
7643
+ const out = new BitWriter();
7644
+ const reserved = (1 << wordSize) - 2;
7645
+ for (let at = 0; at < bits.length; at += wordSize) {
7646
+ const word = readBits(bits, at, wordSize);
7647
+ if ((word & reserved) === reserved) {
7648
+ out.put(word & reserved, wordSize);
7649
+ at--;
7650
+ } else if ((word & reserved) === 0) {
7651
+ out.put(word | 1, wordSize);
7652
+ at--;
7653
+ } else {
7654
+ out.put(word, wordSize);
7655
+ }
7656
+ }
7657
+ return out;
7658
+ }
7659
+
7660
+ /**
7661
+ * Add systematic Aztec Reed-Solomon parity and the leading alignment bits.
7662
+ * @param {BitWriter} data @param {number} totalBits @param {number} wordSize
7663
+ * @param {import('../core/galois-field.js').GaloisField} field
7664
+ * @returns {{bits: BitWriter, dataWords: number, eccWords: number}}
7665
+ */
7666
+ function addCheckWords(data, totalBits, wordSize, field) {
7667
+ const totalWords = Math.floor(totalBits / wordSize);
7668
+ const dataWords = Math.ceil(data.length / wordSize);
7669
+ if (dataWords > totalWords) throw new EncodeError('Aztec: data codewords exceed layer capacity');
7670
+ const eccWords = totalWords - dataWords;
7671
+ const words = new Array(dataWords);
7672
+ for (let i = 0; i < dataWords; i++) words[i] = readBits(data, i * wordSize, wordSize);
7673
+ const ecc = rsEncode(words, eccWords, field, 1);
7674
+ const out = new BitWriter();
7675
+ out.put(0, totalBits % wordSize);
7676
+ for (const word of words) out.put(word, wordSize);
7677
+ for (const word of ecc) out.put(word, wordSize);
7678
+ return { bits: out, dataWords, eccWords };
7679
+ }
7680
+
7681
+ /** @param {number} layers @param {number} dataWords @param {boolean} compact @returns {BitWriter} */
7682
+ function modeMessage(layers, dataWords, compact) {
7683
+ const raw = new BitWriter();
7684
+ if (compact) {
7685
+ raw.put(layers - 1, 2);
7686
+ raw.put(dataWords - 1, 6);
7687
+ return addCheckWords(raw, 28, 4, fieldForWordSize(4)).bits;
7688
+ }
7689
+ raw.put(layers - 1, 5);
7690
+ raw.put(dataWords - 1, 11);
7691
+ return addCheckWords(raw, 40, 4, fieldForWordSize(4)).bits;
7692
+ }
7693
+
7694
+ /** @param {BitMatrix} matrix @param {number} center @param {number} size */
7695
+ function drawBullsEye(matrix, center, size) {
7696
+ for (let ring = 0; ring < size; ring += 2) {
7697
+ for (let p = center - ring; p <= center + ring; p++) {
7698
+ matrix.set(p, center - ring); matrix.set(p, center + ring);
7699
+ matrix.set(center - ring, p); matrix.set(center + ring, p);
7700
+ }
7701
+ }
7702
+ matrix.set(center - size, center - size);
7703
+ matrix.set(center - size + 1, center - size);
7704
+ matrix.set(center - size, center - size + 1);
7705
+ matrix.set(center + size, center - size);
7706
+ matrix.set(center + size, center - size + 1);
7707
+ matrix.set(center + size, center + size - 1);
7708
+ }
7709
+
7710
+ /** @param {BitMatrix} matrix @param {BitWriter} message @param {boolean} compact @param {number} center */
7711
+ function drawModeMessage(matrix, message, compact, center) {
7712
+ if (compact) {
7713
+ for (let i = 0; i < 7; i++) {
7714
+ const offset = center - 3 + i;
7715
+ if (bitAt(message, i)) matrix.set(offset, center - 5);
7716
+ if (bitAt(message, i + 7)) matrix.set(center + 5, offset);
7717
+ if (bitAt(message, 20 - i)) matrix.set(offset, center + 5);
7718
+ if (bitAt(message, 27 - i)) matrix.set(center - 5, offset);
7719
+ }
7720
+ } else {
7721
+ for (let i = 0; i < 10; i++) {
7722
+ const offset = center - 5 + i + Math.floor(i / 5);
7723
+ if (bitAt(message, i)) matrix.set(offset, center - 7);
7724
+ if (bitAt(message, i + 10)) matrix.set(center + 7, offset);
7725
+ if (bitAt(message, 29 - i)) matrix.set(offset, center + 7);
7726
+ if (bitAt(message, 39 - i)) matrix.set(center - 7, offset);
7727
+ }
7728
+ }
7729
+ }
7730
+
7731
+ /**
7732
+ * Lay low-level bits in the four-sided, inward Aztec spiral.
7733
+ * @param {BitWriter} bits @param {{layers:number,compact:boolean,baseMatrixSize:number,symbolSize:number}} symbol
7734
+ * @returns {BitMatrix}
7735
+ */
7736
+ function buildAztecMatrix(bits, symbol) {
7737
+ const { layers, compact, baseMatrixSize, symbolSize } = symbol;
7738
+ const matrix = new BitMatrix(symbolSize);
7739
+ const alignment = new Int32Array(baseMatrixSize);
7740
+ const center = Math.floor(symbolSize / 2);
7741
+
7742
+ if (compact) {
7743
+ for (let i = 0; i < baseMatrixSize; i++) alignment[i] = i;
7744
+ } else {
7745
+ const originalCenter = Math.floor(baseMatrixSize / 2);
7746
+ for (let i = 0; i < originalCenter; i++) {
7747
+ const offset = i + Math.floor(i / 15);
7748
+ alignment[originalCenter - i - 1] = center - offset - 1;
7749
+ alignment[originalCenter + i] = center + offset + 1;
7750
+ }
7751
+ }
7752
+
7753
+ let bit = 0;
7754
+ for (let layer = 0; layer < layers; layer++) {
7755
+ const rowSize = (layers - layer) * 4 + (compact ? 9 : 12);
7756
+ const low = layer * 2;
7757
+ const high = baseMatrixSize - 1 - low;
7758
+ for (let j = 0; j < rowSize; j++) {
7759
+ const offset = j * 2;
7760
+ for (let k = 0; k < 2; k++) {
7761
+ if (bitAt(bits, bit + offset + k)) matrix.set(alignment[low + k], alignment[low + j]);
7762
+ if (bitAt(bits, bit + rowSize * 2 + offset + k)) matrix.set(alignment[low + j], alignment[high - k]);
7763
+ if (bitAt(bits, bit + rowSize * 4 + offset + k)) matrix.set(alignment[high - k], alignment[high - j]);
7764
+ if (bitAt(bits, bit + rowSize * 6 + offset + k)) matrix.set(alignment[high - j], alignment[low + k]);
7765
+ }
7766
+ }
7767
+ bit += rowSize * 8;
7768
+ }
7769
+ if (bit !== bits.length) throw new EncodeError(`Aztec: layout consumed ${bit} of ${bits.length} bits`);
7770
+
7771
+ const mode = modeMessage(layers, symbol.dataWords, compact);
7772
+ drawModeMessage(matrix, mode, compact, center);
7773
+ drawBullsEye(matrix, center, compact ? 5 : 7);
7774
+
7775
+ if (!compact) {
7776
+ for (let i = 0, offset = 0; i < Math.floor(baseMatrixSize / 2) - 1; i += 15, offset += 16) {
7777
+ for (let p = center & 1; p < symbolSize; p += 2) {
7778
+ matrix.set(center - offset, p); matrix.set(center + offset, p);
7779
+ matrix.set(p, center - offset); matrix.set(p, center + offset);
7780
+ }
7781
+ }
7782
+ }
7783
+ return matrix;
7784
+ }
7785
+
7786
+ /** @param {number | undefined} layers @param {boolean | undefined} compact */
7787
+ function candidates(layers, compact) {
7788
+ if (layers !== undefined) {
7789
+ if (!Number.isInteger(layers) || layers < 1 || layers > 32) throw new EncodeError('Aztec: layers must be an integer 1..32');
7790
+ if (compact === true && layers > 4) throw new EncodeError('Aztec: compact symbols support layers 1..4');
7791
+ return [aztecLayer(layers, compact === true)];
7792
+ }
7793
+ if (compact === true) return AZTEC_COMPACT_LAYERS;
7794
+ if (compact === false) return AZTEC_FULL_LAYERS;
7795
+ return [...AZTEC_COMPACT_LAYERS, ...AZTEC_FULL_LAYERS];
7796
+ }
7797
+
7798
+ /**
7799
+ * Encode a UTF-8 string or bytes into an Aztec Code matrix.
7800
+ *
7801
+ * @param {string|ArrayBuffer|ArrayBufferView} value
7802
+ * @param {{layers?:number,compact?:boolean,eccPercent?:number,charset?:'utf-8'}} [options]
7803
+ * @returns {BitMatrix & {format?:string,layers?:number,compact?:boolean,eccPercent?:number,dataCodewords?:number}}
7804
+ */
7805
+ function encodeAztec(value, options = {}) {
7806
+ const eccPercent = options.eccPercent ?? 23;
7807
+ if (!Number.isFinite(eccPercent) || eccPercent < 5 || eccPercent > 95) {
7808
+ throw new EncodeError('Aztec: eccPercent must be between 5 and 95');
7809
+ }
7810
+ const high = encodeHighLevel(value, { charset: options.charset ?? 'utf-8' });
7811
+ for (const candidate of candidates(options.layers, options.compact)) {
7812
+ if (!candidate) continue;
7813
+ const wordSize = wordSizeForLayers(candidate.layers);
7814
+ const stuffed = stuffBits(high, wordSize);
7815
+ const dataWords = Math.ceil(stuffed.length / wordSize);
7816
+ const eccWords = eccCodewordsFor(dataWords, eccPercent);
7817
+ if (dataWords > candidate.maxDataCodewords || dataWords + eccWords > candidate.totalCodewords) continue;
7818
+ const checked = addCheckWords(stuffed, candidate.totalBits, wordSize, fieldForLayers(candidate.layers));
7819
+ // `addCheckWords` uses every remaining word as parity. This is stronger
7820
+ // than the requested percentage, never weaker, and canonical for a chosen
7821
+ // layer/data-word combination.
7822
+ const symbol = { ...candidate, dataWords: checked.dataWords };
7823
+ const matrix = buildAztecMatrix(checked.bits, symbol);
7824
+ matrix.format = 'aztec'; matrix.layers = candidate.layers; matrix.compact = candidate.compact;
7825
+ matrix.eccPercent = Math.round(checked.eccWords * wordSize * 100 / Math.max(1, stuffed.length));
7826
+ matrix.dataCodewords = checked.dataWords;
7827
+ return matrix;
7828
+ }
7829
+ throw new EncodeError('Aztec: payload does not fit the requested layers and error correction');
7830
+ }
7831
+
7832
+ __exports.stuffBits = stuffBits;
7833
+ __exports.addCheckWords = addCheckWords;
7834
+ __exports.modeMessage = modeMessage;
7835
+ __exports.buildAztecMatrix = buildAztecMatrix;
7836
+ __exports.encodeAztec = encodeAztec;
7837
+ };
7838
+
7839
+ __modules["aztec/decoder.js"] = function (__require, __exports) {
7840
+ /**
7841
+ * Decoder for a sampled Aztec symbol.
7842
+ *
7843
+ * This module deliberately accepts only a square, module-aligned BitMatrix.
7844
+ * Locating a bull's-eye in a photograph and perspective sampling are detector
7845
+ * concerns. Keeping the two stages apart makes all bit order and ECC rules
7846
+ * testable without image-processing noise.
7847
+ *
7848
+ * Contract with tables.js:
7849
+ * - aztecSymbolForLayers(compact, layers) returns the nominal symbol data;
7850
+ * - aztecWordSizeForLayers(layers) returns 6, 8, 10 or 12;
7851
+ * - aztecFieldForLayers(layers) returns the matching binary Galois field;
7852
+ * - aztecMatrixSize(compact, layers) returns the rendered square size.
7853
+ *
7854
+ * @module aztec/decoder
7855
+ */
7856
+ const { FormatError } = __require("core/errors.js");
7857
+ const { rsDecode } = __require("core/reed-solomon.js");
7858
+ const { aztecLayer: aztecSymbolForLayers, wordSizeForLayers: aztecWordSizeForLayers, fieldForLayers: aztecFieldForLayers, fieldForWordSize, aztecSymbolSize: aztecMatrixSize } = __require("aztec/tables.js");
7859
+
7860
+ const UPPER = ['CTRL_PS', ' ', ...'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'CTRL_LL', 'CTRL_ML', 'CTRL_DL', 'CTRL_BS'];
7861
+ const LOWER = ['CTRL_PS', ' ', ...'abcdefghijklmnopqrstuvwxyz', 'CTRL_US', 'CTRL_ML', 'CTRL_DL', 'CTRL_BS'];
7862
+ const MIXED = [
7863
+ 'CTRL_PS', ' ', '\x01', '\x02', '\x03', '\x04', '\x05', '\x06', '\x07', '\b', '\t', '\n', '\x0b', '\f', '\r', '\x1b',
7864
+ '\x1c', '\x1d', '\x1e', '\x1f', '@', '\\', '^', '_', '`', '|', '~', '\x7f', 'CTRL_LL', 'CTRL_UL', 'CTRL_PL', 'CTRL_BS',
7865
+ ];
7866
+ const PUNCT = ['FLG(n)', '\r', '\r\n', '. ', ', ', ': ', '!', '"', '#', '$', '%', '&', "'", '(', ')', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '[', ']', '{', '}', 'CTRL_UL'];
7867
+ const DIGIT = ['CTRL_PS', ' ', ...'0123456789', ',', '.', 'CTRL_UL'];
7868
+ const TABLES = { UPPER, LOWER, MIXED, PUNCT, DIGIT };
7869
+
7870
+ /** @param {boolean[]} bits @param {number} offset @param {number} count */
7871
+ function readBits(bits, offset, count) {
7872
+ if (offset + count > bits.length) throw new FormatError('Aztec: truncated high-level stream');
7873
+ let value = 0;
7874
+ for (let i = 0; i < count; i++) value = (value << 1) | (bits[offset + i] ? 1 : 0);
7875
+ return value;
7876
+ }
7877
+
7878
+ /** @param {number} value @param {number} count @param {boolean[]} out */
7879
+ function appendBits(value, count, out) {
7880
+ for (let i = count - 1; i >= 0; i--) out.push(((value >>> i) & 1) !== 0);
7881
+ }
7882
+
7883
+ /**
7884
+ * Decode an Aztec high-level bit stream to its exact byte payload.
7885
+ *
7886
+ * Text tables contribute their ISO-8859-1 byte values; Binary Shift appends
7887
+ * raw bytes. ECI markers are consumed but intentionally not emitted: callers
7888
+ * receive the transported byte payload and may select their own charset.
7889
+ *
7890
+ * @param {boolean[]} bits
7891
+ * @returns {Uint8Array}
7892
+ */
7893
+ function decodeHighLevelBits(bits) {
7894
+ const output = [];
7895
+ let latch = 'UPPER';
7896
+ let shift = 'UPPER';
7897
+ let offset = 0;
7898
+
7899
+ while (offset < bits.length) {
7900
+ if (shift === 'BINARY') {
7901
+ if (offset + 5 > bits.length) break; // legal trailing pad
7902
+ let length = readBits(bits, offset, 5);
7903
+ offset += 5;
7904
+ if (length === 0) {
7905
+ if (offset + 11 > bits.length) throw new FormatError('Aztec: truncated Binary Shift length');
7906
+ length = readBits(bits, offset, 11) + 31;
7907
+ offset += 11;
7908
+ }
7909
+ if (offset + length * 8 > bits.length) throw new FormatError('Aztec: truncated Binary Shift data');
7910
+ for (let i = 0; i < length; i++) {
7911
+ output.push(readBits(bits, offset, 8));
7912
+ offset += 8;
7913
+ }
7914
+ shift = latch;
7915
+ continue;
7916
+ }
7917
+
7918
+ const size = shift === 'DIGIT' ? 4 : 5;
7919
+ if (offset + size > bits.length) break; // trailing pad after unstuffing
7920
+ const code = readBits(bits, offset, size);
7921
+ offset += size;
7922
+ const table = TABLES[shift];
7923
+ const token = table[code];
7924
+ if (token === undefined) throw new FormatError(`Aztec: invalid ${shift} code ${code}`);
7925
+
7926
+ if (token === 'FLG(n)') {
7927
+ if (offset + 3 > bits.length) throw new FormatError('Aztec: truncated FLG(n)');
7928
+ const count = readBits(bits, offset, 3);
7929
+ offset += 3;
7930
+ if (count === 0) output.push(0x1d); // FNC1 / GS
7931
+ else if (count <= 6) {
7932
+ // ECI assignment number, encoded as count decimal digits. It changes
7933
+ // interpretation, not the wire bytes, so consume it without output.
7934
+ for (let i = 0; i < count; i++) {
7935
+ if (offset + 4 > bits.length) throw new FormatError('Aztec: truncated ECI');
7936
+ const digit = readBits(bits, offset, 4);
7937
+ offset += 4;
7938
+ if (digit < 2 || digit > 11) throw new FormatError('Aztec: invalid ECI digit');
7939
+ }
7940
+ } else {
7941
+ throw new FormatError(`Aztec: unsupported FLG(${count})`);
7942
+ }
7943
+ shift = latch;
7944
+ continue;
7945
+ }
7946
+
7947
+ if (token.startsWith('CTRL_')) {
7948
+ const targetCode = token.slice(5, -1);
7949
+ const latchMode = token.endsWith('L');
7950
+ const target = ({ P: 'PUNCT', L: 'LOWER', M: 'MIXED', D: 'DIGIT', U: 'UPPER', B: 'BINARY' })[targetCode];
7951
+ if (!target) throw new FormatError(`Aztec: invalid control ${token}`);
7952
+ shift = target;
7953
+ if (latchMode) latch = shift;
7954
+ continue;
7955
+ }
7956
+
7957
+ for (let i = 0; i < token.length; i++) output.push(token.charCodeAt(i));
7958
+ shift = latch;
7959
+ }
7960
+ return Uint8Array.from(output);
7961
+ }
7962
+
7963
+ /** @param {boolean} compact @param {number} layers */
7964
+ function alignmentMap(compact, layers) {
7965
+ const baseSize = (compact ? 11 : 14) + layers * 4;
7966
+ if (compact) return Array.from({ length: baseSize }, (_, i) => i);
7967
+ const size = aztecMatrixSize(layers, false);
7968
+ const map = new Array(baseSize);
7969
+ const baseCenter = baseSize >> 1;
7970
+ const center = size >> 1;
7971
+ for (let i = 0; i < baseCenter; i++) {
7972
+ const offset = i + Math.floor(i / 15);
7973
+ map[baseCenter - i - 1] = center - offset - 1;
7974
+ map[baseCenter + i] = center + offset + 1;
7975
+ }
7976
+ return map;
7977
+ }
7978
+
7979
+ /**
7980
+ * Read the four sides of the parameter message. The order mirrors the
7981
+ * clockwise write order and is independent of the data spiral.
7982
+ *
7983
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix
7984
+ * @param {boolean} compact
7985
+ * @returns {boolean[]}
7986
+ */
7987
+ function readModeBits(matrix, compact) {
7988
+ const center = matrix.width >> 1;
7989
+ const side = compact ? 7 : 10;
7990
+ const offset = compact ? 5 : 7;
7991
+ // Full symbols skip the reference grid line through the bull's-eye. This
7992
+ // exact sequence is also used by drawModeMessage() in encoder.js.
7993
+ const positions = Array.from(
7994
+ { length: side },
7995
+ (_, i) => compact ? center - 3 + i : center - 5 + i + Math.floor(i / 5),
7996
+ );
7997
+ const bits = [];
7998
+ for (let i = 0; i < side; i++) bits.push(matrix.get(positions[i], center - offset));
7999
+ for (let i = 0; i < side; i++) bits.push(matrix.get(center + offset, positions[i]));
8000
+ for (let i = 0; i < side; i++) bits.push(matrix.get(positions[side - 1 - i], center + offset));
8001
+ for (let i = 0; i < side; i++) bits.push(matrix.get(center - offset, positions[side - 1 - i]));
8002
+ return bits;
8003
+ }
8004
+
8005
+ /** @param {boolean[]} bits @param {boolean} compact */
8006
+ function decodeModeMessage(bits, compact) {
8007
+ const total = compact ? 7 : 10;
8008
+ const dataWords = compact ? 2 : 4;
8009
+ const words = new Array(total);
8010
+ for (let i = 0; i < total; i++) words[i] = readBits(bits, i * 4, 4);
8011
+ const corrections = rsDecode(words, total - dataWords, fieldForWordSize(4), 1);
8012
+ let data = 0;
8013
+ for (let i = 0; i < dataWords; i++) data = (data << 4) | words[i];
8014
+ const layers = compact ? (data >>> 6) + 1 : (data >>> 11) + 1;
8015
+ const dataCodewords = compact ? (data & 0x3f) + 1 : (data & 0x7ff) + 1;
8016
+ return { layers, dataCodewords, corrections };
8017
+ }
8018
+
8019
+ /** @param {boolean} compact @param {number} layers */
8020
+ function totalBitsInLayers(compact, layers) {
8021
+ return ((compact ? 88 : 112) + 16 * layers) * layers;
8022
+ }
8023
+
8024
+ /**
8025
+ * Extract raw, stuffed codeword bits in logical ring order.
8026
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix
8027
+ * @param {boolean} compact @param {number} layers
8028
+ * @returns {boolean[]}
8029
+ */
8030
+ function extractBits(matrix, compact, layers) {
8031
+ const baseSize = (compact ? 11 : 14) + layers * 4;
8032
+ const map = alignmentMap(compact, layers);
8033
+ const raw = new Array(totalBitsInLayers(compact, layers));
8034
+ let offset = 0;
8035
+ for (let layer = 0; layer < layers; layer++) {
8036
+ const rowSize = (layers - layer) * 4 + (compact ? 9 : 12);
8037
+ for (let j = 0; j < rowSize; j++) {
8038
+ const col = j * 2;
8039
+ for (let k = 0; k < 2; k++) {
8040
+ raw[offset + col + k] = matrix.get(map[layer * 2 + k], map[layer * 2 + j]);
8041
+ raw[offset + rowSize * 2 + col + k] = matrix.get(map[layer * 2 + j], map[baseSize - 1 - layer * 2 - k]);
8042
+ raw[offset + rowSize * 4 + col + k] = matrix.get(map[baseSize - 1 - layer * 2 - k], map[baseSize - 1 - layer * 2 - j]);
8043
+ raw[offset + rowSize * 6 + col + k] = matrix.get(map[baseSize - 1 - layer * 2 - j], map[layer * 2 + k]);
8044
+ }
8045
+ }
8046
+ offset += rowSize * 8;
8047
+ }
8048
+ return raw;
8049
+ }
8050
+
8051
+ /** @param {boolean[]} raw @param {number} layers @param {number} dataCodewords */
8052
+ function correctAndUnstuff(raw, layers, dataCodewords) {
8053
+ const wordSize = aztecWordSizeForLayers(layers);
8054
+ const totalWords = Math.floor(raw.length / wordSize);
8055
+ if (dataCodewords <= 0 || dataCodewords > totalWords) throw new FormatError('Aztec: invalid data word count');
8056
+ const start = raw.length % wordSize;
8057
+ const words = new Array(totalWords);
8058
+ for (let i = 0; i < totalWords; i++) words[i] = readBits(raw, start + i * wordSize, wordSize);
8059
+ const corrections = rsDecode(words, totalWords - dataCodewords, aztecFieldForLayers(layers), 1);
8060
+ const mask = (1 << wordSize) - 1;
8061
+ const corrected = [];
8062
+ for (let i = 0; i < dataCodewords; i++) {
8063
+ const word = words[i];
8064
+ if (word === 0 || word === mask) throw new FormatError('Aztec: invalid stuffed codeword');
8065
+ if (word === 1 || word === mask - 1) {
8066
+ for (let j = 0; j < wordSize - 1; j++) corrected.push(word === mask - 1);
8067
+ } else {
8068
+ appendBits(word, wordSize, corrected);
8069
+ }
8070
+ }
8071
+ return { bits: corrected, corrections };
8072
+ }
8073
+
8074
+ /** @param {Uint8Array} bytes */
8075
+ function bytesToText(bytes) {
8076
+ try { return new TextDecoder('utf-8', { fatal: true }).decode(bytes); }
8077
+ catch { return new TextDecoder('latin1').decode(bytes); }
8078
+ }
8079
+
8080
+ /**
8081
+ * Decode a square Aztec symbol with one bit per module and no quiet zone.
8082
+ * The matrix must already be oriented with the mode message at the top.
8083
+ *
8084
+ * @param {import('../core/bit-matrix.js').BitMatrix} matrix
8085
+ * @returns {{text: string, bytes: Uint8Array, compact: boolean, layers: number, corrections: number, eccPercent: number}}
8086
+ */
8087
+ function decodeAztec(matrix) {
8088
+ if (!matrix || matrix.width !== matrix.height) throw new FormatError('Aztec: expected a square BitMatrix');
8089
+ let compact;
8090
+ let mode;
8091
+ // Compact and full dimensions are disjoint; trying both also makes malformed
8092
+ // candidate handling deterministic for the future image detector.
8093
+ for (const candidate of [true, false]) {
8094
+ try {
8095
+ const value = decodeModeMessage(readModeBits(matrix, candidate), candidate);
8096
+ if (value.layers < 1 || value.layers > (candidate ? 4 : 32)) continue;
8097
+ if (aztecMatrixSize(value.layers, candidate) !== matrix.width) continue;
8098
+ compact = candidate;
8099
+ mode = value;
8100
+ break;
8101
+ } catch { /* Try the other family. */ }
8102
+ }
8103
+ if (compact === undefined || !mode) throw new FormatError('Aztec: invalid mode message or dimensions');
8104
+ // Ensure the declared layer data agrees with the table module, so a future
8105
+ // tables refactor cannot silently make decoder capacity calculations stale.
8106
+ aztecSymbolForLayers(mode.layers, compact);
8107
+ const raw = extractBits(matrix, compact, mode.layers);
8108
+ const payload = correctAndUnstuff(raw, mode.layers, mode.dataCodewords);
8109
+ const bytes = decodeHighLevelBits(payload.bits);
8110
+ const totalWords = Math.floor(raw.length / aztecWordSizeForLayers(mode.layers));
8111
+ return {
8112
+ text: bytesToText(bytes),
8113
+ bytes,
8114
+ compact,
8115
+ layers: mode.layers,
8116
+ corrections: mode.corrections + payload.corrections,
8117
+ eccPercent: Math.round(((totalWords - mode.dataCodewords) * 100) / totalWords),
8118
+ };
8119
+ }
8120
+
8121
+ __exports.decodeHighLevelBits = decodeHighLevelBits;
8122
+ __exports.decodeAztec = decodeAztec;
8123
+ };
8124
+
8125
+ __modules["aztec/detector.js"] = function (__require, __exports) {
8126
+ /**
8127
+ * Aztec image detection.
8128
+ *
8129
+ * Aztec has no finder pattern at its outer border. Its reliable geometric
8130
+ * anchor is instead the alternating square bull's-eye in the centre: five
8131
+ * rings in Compact symbols, seven rings in Full symbols. The detector finds
8132
+ * isolated central modules, verifies those rings at module centres, then
8133
+ * samples each legal symbol dimension. The decoder is deliberately the final
8134
+ * arbiter: its mode-message Reed--Solomon check rejects accidental concentric
8135
+ * artwork and tells us which of the compact/full dimensions is real.
8136
+ *
8137
+ * Sampling uses a quadrilateral, not a cropped bitmap, so the detected
8138
+ * rotation is corrected before decoding. The ring search covers arbitrary
8139
+ * in-plane rotations (four-degree coarse search; at normal camera scales its
8140
+ * positional error remains well inside a module). The optional inverse pass
8141
+ * supports light modules on a dark field.
8142
+ *
8143
+ * @module aztec/detector
8144
+ */
8145
+ const { NotFoundError } = __require("core/errors.js");
8146
+ const { sampleQuad } = __require("image/grid-sampler.js");
8147
+ const { decodeAztec } = __require("aztec/decoder.js");
8148
+
8149
+ /** @typedef {{x:number, y:number}} Point */
8150
+ /** @typedef {{corners: Point[], dimension: number, compact: boolean, moduleSize: number, matrix: import('../core/bit-matrix.js').BitMatrix}} Detection */
8151
+
8152
+ // Compact: 11 + 4 layers. Full symbols add reference-grid rows/columns every
8153
+ // 15 modules measured from their central 14-module base, not every 15 layers.
8154
+ const DIMENSIONS = [
8155
+ ...[1, 2, 3, 4].map((layers) => ({ compact: true, dimension: 11 + 4 * layers })),
8156
+ ...Array.from({ length: 32 }, (_, index) => {
8157
+ const layers = index + 1;
8158
+ return { compact: false, dimension: 15 + 4 * layers + 2 * Math.floor((2 * layers + 6) / 15) };
8159
+ }),
8160
+ ];
8161
+
8162
+ function pixel(image, x, y) {
8163
+ const ix = Math.round(x);
8164
+ const iy = Math.round(y);
8165
+ return ix >= 0 && iy >= 0 && ix < image.width && iy < image.height && image.get(ix, iy);
8166
+ }
8167
+
8168
+ /** Connected components of either polarity, retaining only plausible modules. */
8169
+ function components(image, value) {
8170
+ const seen = new Uint8Array(image.width * image.height);
8171
+ const out = [];
8172
+ const maximumArea = Math.max(4, Math.floor(image.width * image.height * 0.08));
8173
+ for (let y = 0; y < image.height; y++) for (let x = 0; x < image.width; x++) {
8174
+ const start = y * image.width + x;
8175
+ if (seen[start] || image.get(x, y) !== value) continue;
8176
+ const xs = [x];
8177
+ const ys = [y];
8178
+ seen[start] = 1;
8179
+ let head = 0;
8180
+ let minX = x; let maxX = x; let minY = y; let maxY = y;
8181
+ while (head < xs.length) {
8182
+ const px = xs[head]; const py = ys[head++];
8183
+ if (px < minX) minX = px; if (px > maxX) maxX = px;
8184
+ if (py < minY) minY = py; if (py > maxY) maxY = py;
8185
+ for (const [nx, ny] of [[px - 1, py], [px + 1, py], [px, py - 1], [px, py + 1]]) {
8186
+ if (nx < 0 || ny < 0 || nx >= image.width || ny >= image.height) continue;
8187
+ const at = ny * image.width + nx;
8188
+ if (!seen[at] && image.get(nx, ny) === value) {
8189
+ seen[at] = 1; xs.push(nx); ys.push(ny);
8190
+ }
8191
+ }
8192
+ }
8193
+ const width = maxX - minX + 1;
8194
+ const height = maxY - minY + 1;
8195
+ const area = width * height;
8196
+ // The central module is solid and approximately square. This filter is
8197
+ // intentionally permissive because a rotated raster module is diamond-ish.
8198
+ if (xs.length <= maximumArea && Math.abs(width - height) <= Math.max(1, Math.ceil(Math.max(width, height) * 0.35)) &&
8199
+ xs.length >= area * 0.45) {
8200
+ out.push({ x: (minX + maxX) / 2, y: (minY + maxY) / 2, width, height, pixels: xs.length });
8201
+ }
8202
+ }
8203
+ return out.sort((a, b) => b.pixels - a.pixels).slice(0, 2000);
8204
+ }
8205
+
8206
+ function expectedDark(ring, inverted) {
8207
+ return inverted ? (ring & 1) === 1 : (ring & 1) === 0;
8208
+ }
8209
+
8210
+ /** Score one square bull's-eye at an angle and a candidate module pitch. */
8211
+ function ringScore(image, centre, pitch, angle, inverted, rings) {
8212
+ const cos = Math.cos(angle);
8213
+ const sin = Math.sin(angle);
8214
+ let correct = 0;
8215
+ let total = 0;
8216
+ for (let ring = 0; ring < rings; ring++) {
8217
+ const wanted = expectedDark(ring, inverted);
8218
+ for (let j = -ring; j <= ring; j++) for (let i = -ring; i <= ring; i++) {
8219
+ if (ring && Math.abs(i) !== ring && Math.abs(j) !== ring) continue;
8220
+ const x = centre.x + (i * cos - j * sin) * pitch;
8221
+ const y = centre.y + (i * sin + j * cos) * pitch;
8222
+ if (pixel(image, x, y) === wanted) correct++;
8223
+ total++;
8224
+ }
8225
+ }
8226
+ return correct / total;
8227
+ }
8228
+
8229
+ function rotateCorners(corners, turn) {
8230
+ return corners.slice(turn).concat(corners.slice(0, turn));
8231
+ }
8232
+
8233
+ function invert(matrix) {
8234
+ const out = matrix.clone();
8235
+ for (let y = 0; y < out.height; y++) for (let x = 0; x < out.width; x++) out.flip(x, y);
8236
+ return out;
8237
+ }
8238
+
8239
+ function cornersFor(centre, pitch, angle, dimension) {
8240
+ const half = dimension * pitch / 2;
8241
+ const cos = Math.cos(angle);
8242
+ const sin = Math.sin(angle);
8243
+ const point = (x, y) => ({ x: centre.x + x * cos - y * sin, y: centre.y + x * sin + y * cos });
8244
+ return [point(-half, -half), point(half, -half), point(half, half), point(-half, half)];
8245
+ }
8246
+
8247
+ /**
8248
+ * Find an Aztec symbol in a binarized image.
8249
+ *
8250
+ * The returned matrix is in the orientation accepted by the Aztec decoder.
8251
+ * A valid mode message is required before a geometric candidate is returned,
8252
+ * making false positives from decorative concentric squares very unlikely.
8253
+ *
8254
+ * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage Set bit = dark.
8255
+ * @returns {Detection | null}
8256
+ */
8257
+ function detectAztec(binaryImage) {
8258
+ if (!binaryImage || !binaryImage.width || !binaryImage.height) {
8259
+ throw new NotFoundError('detectAztec: no image supplied');
8260
+ }
8261
+ const candidates = [];
8262
+ for (const inverted of [false, true]) {
8263
+ for (const core of components(binaryImage, !inverted)) {
8264
+ // A non-rotated one-module component directly gives its pitch. For
8265
+ // rotated modules its bounding box grows by |sin| + |cos|, compensated
8266
+ // below for every tested angle.
8267
+ for (let degrees = 0; degrees < 180; degrees += 4) {
8268
+ const angle = degrees * Math.PI / 180;
8269
+ const scale = Math.abs(Math.cos(angle)) + Math.abs(Math.sin(angle));
8270
+ const pitch = ((core.width + core.height) / 2) / scale;
8271
+ if (pitch < 0.8) continue;
8272
+ // Test Full first: its seven rings also exclude Compact candidates.
8273
+ const fullScore = ringScore(binaryImage, core, pitch, angle, inverted, 7);
8274
+ const rings = fullScore >= 0.88 ? 7 : 5;
8275
+ const score = rings === 7 ? fullScore : ringScore(binaryImage, core, pitch, angle, inverted, 5);
8276
+ if (score < 0.91) continue;
8277
+ const symbolKinds = rings === 7 ? DIMENSIONS.filter((item) => !item.compact) : DIMENSIONS.filter((item) => item.compact);
8278
+ for (const kind of symbolKinds) {
8279
+ const baseCorners = cornersFor(core, pitch, angle, kind.dimension);
8280
+ for (let turn = 0; turn < 4; turn++) {
8281
+ const corners = rotateCorners(baseCorners, turn);
8282
+ let matrix;
8283
+ try { matrix = sampleQuad(binaryImage, kind.dimension, corners); } catch (e) { continue; }
8284
+ if (inverted) matrix = invert(matrix);
8285
+ try {
8286
+ // The decoder verifies the mode-message ECC and exact geometry.
8287
+ // We do not expose its result here so callers can use pure
8288
+ // detection without treating payload decoding as an API contract.
8289
+ decodeAztec(matrix);
8290
+ candidates.push({ corners, dimension: kind.dimension, compact: kind.compact,
8291
+ moduleSize: pitch, matrix, score });
8292
+ } catch (e) { /* Not an Aztec mode message at this dimension. */ }
8293
+ }
8294
+ }
8295
+ }
8296
+ }
8297
+ }
8298
+ candidates.sort((a, b) => b.score - a.score || b.moduleSize - a.moduleSize);
8299
+ const best = candidates[0];
8300
+ if (!best) return null;
8301
+ delete best.score;
8302
+ return best;
8303
+ }
8304
+
8305
+ /**
8306
+ * Detect then decode an Aztec symbol. Detection failure is a normal result for
8307
+ * images without an Aztec code, therefore invalid candidates return null.
8308
+ *
8309
+ * @param {import('../core/bit-matrix.js').BitMatrix} binaryImage
8310
+ * @returns {(import('./decoder.js').DecodeResult & {corners: Point[]}) | null}
8311
+ */
8312
+ function detectAndDecodeAztec(binaryImage) {
8313
+ let detection;
8314
+ try { detection = detectAztec(binaryImage); } catch (e) { return null; }
8315
+ if (!detection) return null;
8316
+ try { return Object.assign({ corners: detection.corners }, decodeAztec(detection.matrix)); }
8317
+ catch (e) { return null; }
8318
+ }
8319
+
8320
+ __exports.detectAztec = detectAztec;
8321
+ __exports.detectAndDecodeAztec = detectAndDecodeAztec;
8322
+ };
8323
+
8324
+ __modules["aztec/index.js"] = function (__require, __exports) {
8325
+ /** Aztec Code entry points. @module aztec */
8326
+ const __reexport0 = __require("aztec/encoder.js"); __exports.encodeAztec = __reexport0.encodeAztec;
8327
+ const __reexport1 = __require("aztec/decoder.js"); __exports.decodeAztec = __reexport1.decodeAztec;
8328
+ const __reexport2 = __require("aztec/detector.js"); __exports.detectAztec = __reexport2.detectAztec; __exports.detectAndDecodeAztec = __reexport2.detectAndDecodeAztec;
8329
+ 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;
8330
+
8331
+
7212
8332
  };
7213
8333
 
7214
8334
  __modules["render/options.js"] = function (__require, __exports) {
@@ -8466,6 +9586,7 @@ const { ONED_FORMATS } = __require("oned/index.js");
8466
9586
  const { decodeOneD } = __require("oned/reader.js");
8467
9587
  const datamatrix = __require("datamatrix/index.js");
8468
9588
  const qr = __require("qr/index.js");
9589
+ const aztec = __require("aztec/index.js");
8469
9590
  __exports.BitMatrix = BitMatrix;
8470
9591
  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;
8471
9592
  const __reexport1 = __require("image/luminance.js"); __exports.LuminanceSource = __reexport1.LuminanceSource;
@@ -8478,6 +9599,7 @@ const __reexport6 = __require("render/index.js"); __exports.renderToCanvasAuto =
8478
9599
  const __reexport7 = __require("render/index.js"); __exports.renderToCanvasAutoAsync = __reexport7.renderToCanvasAutoAsync; __exports.isWebGPUAvailable = __reexport7.isWebGPUAvailable;
8479
9600
  const __reexport8 = __require("qr/index.js"); __exports.encodeQR = __reexport8.encodeQR; __exports.decodeQR = __reexport8.decodeQR; __exports.detectQR = __reexport8.detectQR; __exports.detectAndDecodeQR = __reexport8.detectAndDecodeQR;
8480
9601
  const __reexport9 = __require("datamatrix/index.js"); __exports.encodeDataMatrix = __reexport9.encodeDataMatrix; __exports.decodeDataMatrix = __reexport9.decodeDataMatrix; __exports.detectDataMatrix = __reexport9.detectDataMatrix; __exports.detectAndDecodeDataMatrix = __reexport9.detectAndDecodeDataMatrix;
9602
+ const __reexport10 = __require("aztec/index.js"); __exports.encodeAztec = __reexport10.encodeAztec; __exports.decodeAztec = __reexport10.decodeAztec; __exports.detectAztec = __reexport10.detectAztec; __exports.detectAndDecodeAztec = __reexport10.detectAndDecodeAztec;
8481
9603
 
8482
9604
  /**
8483
9605
  * @typedef {object} FormatInfo
@@ -8503,6 +9625,8 @@ const qrCanDecode = qrPresent &&
8503
9625
  typeof qr.detectAndDecodeQR === 'function' && qr.QR_CAN_DECODE !== false;
8504
9626
  const dataMatrixCanEncode = typeof datamatrix.encodeDataMatrix === 'function';
8505
9627
  const dataMatrixCanDecode = typeof datamatrix.detectAndDecodeDataMatrix === 'function';
9628
+ const aztecCanEncode = typeof aztec.encodeAztec === 'function';
9629
+ const aztecCanDecode = typeof aztec.detectAndDecodeAztec === 'function';
8506
9630
 
8507
9631
  /**
8508
9632
  * Every format this build supports.
@@ -8537,6 +9661,13 @@ function listFormats() {
8537
9661
  canRead: dataMatrixCanDecode,
8538
9662
  kind: /** @type {'2D'} */ ('2D'),
8539
9663
  });
9664
+ formats.push({
9665
+ id: 'aztec',
9666
+ label: 'Aztec Code',
9667
+ canWrite: aztecCanEncode,
9668
+ canRead: aztecCanDecode,
9669
+ kind: /** @type {'2D'} */ ('2D'),
9670
+ });
8540
9671
 
8541
9672
  return formats;
8542
9673
  }
@@ -8557,6 +9688,9 @@ function listFormats() {
8557
9688
  * @param {boolean} [options.checkDigit] Append a check digit, where optional.
8558
9689
  * @param {boolean} [options.fullAscii] Code 39 extended encoding.
8559
9690
  * @param {boolean} [options.gs1] Emit a leading FNC1.
9691
+ * @param {number} [options.layers] Aztec layer count; automatic if omitted.
9692
+ * @param {boolean} [options.compact] Force an Aztec Compact or Full symbol.
9693
+ * @param {number} [options.eccPercent] Requested Aztec error-correction percentage.
8560
9694
  * @returns {BitMatrix}
8561
9695
  */
8562
9696
  function encode(text, options = {}) {
@@ -8569,10 +9703,13 @@ function encode(text, options = {}) {
8569
9703
  if (format === 'datamatrix' || format === 'data-matrix') {
8570
9704
  return datamatrix.encodeDataMatrix(value, options);
8571
9705
  }
9706
+ if (format === 'aztec' || format === 'aztec-code') {
9707
+ return aztec.encodeAztec(value, options);
9708
+ }
8572
9709
 
8573
9710
  const entry = ONED_FORMATS[format];
8574
9711
  if (!entry) {
8575
- const known = [...Object.keys(ONED_FORMATS), 'qr', 'datamatrix'].join(', ');
9712
+ const known = [...Object.keys(ONED_FORMATS), 'qr', 'datamatrix', 'aztec'].join(', ');
8576
9713
  throw new EncodeError(`Unknown format "${format}". Known formats: ${known}`);
8577
9714
  }
8578
9715
  return entry.encode(value, options);
@@ -8585,6 +9722,9 @@ function encode(text, options = {}) {
8585
9722
  * @property {Uint8Array} [bytes] Raw payload, before text decoding.
8586
9723
  * @property {number} [version] QR version.
8587
9724
  * @property {string} [ecc] QR error-correction level.
9725
+ * @property {number} [layers] Aztec layer count.
9726
+ * @property {boolean} [compact] Whether an Aztec symbol is Compact.
9727
+ * @property {number} [corrections] Reed–Solomon corrections applied by an Aztec decode.
8588
9728
  */
8589
9729
 
8590
9730
  /**
@@ -8606,6 +9746,7 @@ function decode(image, options = {}) {
8606
9746
  const want = formats ? new Set(formats.map((f) => f.toLowerCase())) : null;
8607
9747
  const wantQR = !want || want.has('qr') || want.has('qrcode');
8608
9748
  const wantDataMatrix = !want || want.has('datamatrix') || want.has('data-matrix');
9749
+ const wantAztec = !want || want.has('aztec') || want.has('aztec-code');
8609
9750
  const wantOneD = !want || [...want].some((f) => f in ONED_FORMATS);
8610
9751
 
8611
9752
  const source = LuminanceSource.fromImageData(image);
@@ -8643,6 +9784,21 @@ function decode(image, options = {}) {
8643
9784
  }
8644
9785
  }
8645
9786
 
9787
+ if (wantAztec && aztecCanDecode) {
9788
+ // The central bull's-eye is a small, high-contrast target. Hybrid
9789
+ // thresholding can flatten it on clean rendered symbols, so mirror the
9790
+ // Data Matrix global fallback in auto mode.
9791
+ const aztecBits = binarizer === 'auto' ? [bits, binarize(pass, 'global')] : [bits];
9792
+ for (const candidateBits of aztecBits) {
9793
+ try {
9794
+ const found = aztec.detectAndDecodeAztec(candidateBits);
9795
+ if (found) { results.push({ ...found, format: 'aztec' }); break; }
9796
+ } catch {
9797
+ /* no Aztec code with this threshold */
9798
+ }
9799
+ }
9800
+ }
9801
+
8646
9802
  if (wantOneD) {
8647
9803
  const oneDFormats = want ? [...want].filter((f) => f in ONED_FORMATS) : null;
8648
9804
  for (const found of decodeOneD(bits, { formats: oneDFormats, tryHarder })) {
@@ -8677,7 +9833,7 @@ function decodeStrict(image, options) {
8677
9833
  }
8678
9834
 
8679
9835
  /** Library version, matching package.json. */
8680
- const VERSION = '1.0.0';
9836
+ const VERSION = '1.1.0';
8681
9837
 
8682
9838
  __exports.listFormats = listFormats;
8683
9839
  __exports.encode = encode;