@bcts/components 1.0.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,507 @@
1
+ const require_index = require('./index.cjs');
2
+ let _bcts_crypto = require("@bcts/crypto");
3
+ let _bcts_dcbor = require("@bcts/dcbor");
4
+ let _bcts_tags = require("@bcts/tags");
5
+ let _bcts_uniform_resources = require("@bcts/uniform-resources");
6
+
7
+ //#region src/error.ts
8
+ /**
9
+ * Error types re-exported from @bcts/crypto
10
+ * with additional factory methods for components
11
+ *
12
+ * Ported from bc-components-rust/src/error.rs
13
+ */
14
+ var CryptoError = class CryptoError extends _bcts_crypto.CryptoError {
15
+ static invalidSize(expected, actual) {
16
+ return new CryptoError(`Invalid size: expected ${expected}, got ${actual}`);
17
+ }
18
+ static invalidFormat(message) {
19
+ return new CryptoError(`Invalid format: ${message}`);
20
+ }
21
+ static cryptoOperation(message) {
22
+ return new CryptoError(`Crypto operation failed: ${message}`);
23
+ }
24
+ static invalidInput(message) {
25
+ return new CryptoError(`Invalid input: ${message}`);
26
+ }
27
+ static dataTooShort(name, minSize, actual) {
28
+ return new CryptoError(`${name} too short: minimum ${minSize}, got ${actual}`);
29
+ }
30
+ static invalidData(message) {
31
+ return new CryptoError(`Invalid data: ${message}`);
32
+ }
33
+ };
34
+ function isError(result) {
35
+ return result instanceof Error;
36
+ }
37
+
38
+ //#endregion
39
+ //#region src/utils.ts
40
+ /**
41
+ * Utility functions for byte array conversions and comparisons.
42
+ *
43
+ * These functions provide cross-platform support for common byte manipulation
44
+ * operations needed in cryptographic and encoding contexts.
45
+ *
46
+ * @packageDocumentation
47
+ */
48
+ /**
49
+ * Convert a Uint8Array to a lowercase hexadecimal string.
50
+ *
51
+ * @param data - The byte array to convert
52
+ * @returns A lowercase hex string representation (2 characters per byte)
53
+ *
54
+ * @example
55
+ * ```typescript
56
+ * const bytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);
57
+ * bytesToHex(bytes); // "deadbeef"
58
+ * ```
59
+ */
60
+ function bytesToHex(data) {
61
+ return Array.from(data).map((b) => b.toString(16).padStart(2, "0")).join("");
62
+ }
63
+ /**
64
+ * Convert a hexadecimal string to a Uint8Array.
65
+ *
66
+ * @param hex - A hex string (must have even length, case-insensitive)
67
+ * @returns The decoded byte array
68
+ * @throws {Error} If the hex string has odd length or contains invalid characters
69
+ *
70
+ * @example
71
+ * ```typescript
72
+ * hexToBytes("deadbeef"); // Uint8Array([0xde, 0xad, 0xbe, 0xef])
73
+ * hexToBytes("DEADBEEF"); // Uint8Array([0xde, 0xad, 0xbe, 0xef])
74
+ * hexToBytes("xyz"); // throws Error: Invalid hex string
75
+ * ```
76
+ */
77
+ function hexToBytes(hex) {
78
+ if (hex.length % 2 !== 0) throw new Error(`Hex string must have even length, got ${hex.length}`);
79
+ if (!/^[0-9A-Fa-f]*$/.test(hex)) throw new Error("Invalid hex string: contains non-hexadecimal characters");
80
+ const data = new Uint8Array(hex.length / 2);
81
+ for (let i = 0; i < hex.length; i += 2) data[i / 2] = parseInt(hex.substring(i, i + 2), 16);
82
+ return data;
83
+ }
84
+ /**
85
+ * Convert a Uint8Array to a base64-encoded string.
86
+ *
87
+ * This function works in both browser and Node.js environments.
88
+ * Uses btoa which is available in browsers and Node.js 16+.
89
+ *
90
+ * @param data - The byte array to encode
91
+ * @returns A base64-encoded string
92
+ *
93
+ * @example
94
+ * ```typescript
95
+ * const bytes = new Uint8Array([72, 101, 108, 108, 111]); // "Hello"
96
+ * toBase64(bytes); // "SGVsbG8="
97
+ * ```
98
+ */
99
+ function toBase64(data) {
100
+ let binary = "";
101
+ for (const byte of data) binary += String.fromCharCode(byte);
102
+ return btoa(binary);
103
+ }
104
+ /**
105
+ * Convert a base64-encoded string to a Uint8Array.
106
+ *
107
+ * This function works in both browser and Node.js environments.
108
+ * Uses atob which is available in browsers and Node.js 16+.
109
+ *
110
+ * @param base64 - A base64-encoded string
111
+ * @returns The decoded byte array
112
+ *
113
+ * @example
114
+ * ```typescript
115
+ * fromBase64("SGVsbG8="); // Uint8Array([72, 101, 108, 108, 111])
116
+ * ```
117
+ */
118
+ function fromBase64(base64) {
119
+ const binary = atob(base64);
120
+ const bytes = new Uint8Array(binary.length);
121
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
122
+ return bytes;
123
+ }
124
+ /**
125
+ * Compare two Uint8Arrays for equality using constant-time comparison.
126
+ *
127
+ * This function is designed to be resistant to timing attacks by always
128
+ * comparing all bytes regardless of where a difference is found. The
129
+ * comparison time depends only on the length of the arrays, not on where
130
+ * they differ.
131
+ *
132
+ * **Security Note**: If the arrays have different lengths, this function
133
+ * returns `false` immediately, which does leak length information. For
134
+ * cryptographic uses where length should also be secret, ensure both
135
+ * arrays are the same length before comparison.
136
+ *
137
+ * @param a - First byte array
138
+ * @param b - Second byte array
139
+ * @returns `true` if both arrays have the same length and identical contents
140
+ *
141
+ * @example
142
+ * ```typescript
143
+ * const key1 = new Uint8Array([1, 2, 3, 4]);
144
+ * const key2 = new Uint8Array([1, 2, 3, 4]);
145
+ * const key3 = new Uint8Array([1, 2, 3, 5]);
146
+ *
147
+ * bytesEqual(key1, key2); // true
148
+ * bytesEqual(key1, key3); // false
149
+ * ```
150
+ */
151
+ function bytesEqual(a, b) {
152
+ if (a.length !== b.length) return false;
153
+ let result = 0;
154
+ for (let i = 0; i < a.length; i++) result |= a[i] ^ b[i];
155
+ return result === 0;
156
+ }
157
+
158
+ //#endregion
159
+ //#region src/digest.ts
160
+ /**
161
+ * SHA-256 cryptographic digest (32 bytes)
162
+ *
163
+ * Ported from bc-components-rust/src/digest.rs
164
+ *
165
+ * A `Digest` represents the cryptographic hash of some data. In this
166
+ * implementation, SHA-256 is used, which produces a 32-byte hash value.
167
+ * Digests are used throughout the crate for data verification and as unique
168
+ * identifiers derived from data.
169
+ *
170
+ * # CBOR Serialization
171
+ *
172
+ * `Digest` implements the CBOR tagged encoding interfaces, which means it can be
173
+ * serialized to and deserialized from CBOR with a specific tag (TAG_DIGEST = 40001).
174
+ *
175
+ * # UR Serialization
176
+ *
177
+ * When serialized as a Uniform Resource (UR), a `Digest` is represented as a
178
+ * binary blob with the type "digest".
179
+ *
180
+ * @example
181
+ * ```typescript
182
+ * import { Digest } from '@bcts/components';
183
+ *
184
+ * // Create a digest from a string
185
+ * const data = new TextEncoder().encode("hello world");
186
+ * const digest = Digest.fromImage(data);
187
+ *
188
+ * // Validate that the digest matches the original data
189
+ * console.log(digest.validate(data)); // true
190
+ *
191
+ * // Create a digest from a hex string
192
+ * const hexString = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";
193
+ * const digest2 = Digest.fromHex(hexString);
194
+ *
195
+ * // Retrieve the digest as hex
196
+ * console.log(digest2.hex()); // b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9
197
+ * ```
198
+ */
199
+ var Digest = class Digest {
200
+ static DIGEST_SIZE = _bcts_crypto.SHA256_SIZE;
201
+ _data;
202
+ constructor(data) {
203
+ if (data.length !== Digest.DIGEST_SIZE) throw CryptoError.invalidSize(Digest.DIGEST_SIZE, data.length);
204
+ this._data = new Uint8Array(data);
205
+ }
206
+ /**
207
+ * Get the digest data.
208
+ */
209
+ data() {
210
+ return this._data;
211
+ }
212
+ /**
213
+ * Create a Digest from a 32-byte array.
214
+ */
215
+ static fromData(data) {
216
+ return new Digest(new Uint8Array(data));
217
+ }
218
+ /**
219
+ * Create a Digest from data, validating the length.
220
+ * Alias for fromData for compatibility with Rust API.
221
+ */
222
+ static fromDataRef(data) {
223
+ return Digest.fromData(data);
224
+ }
225
+ /**
226
+ * Create a Digest from hex string.
227
+ *
228
+ * @throws Error if the hex string is not exactly 64 characters.
229
+ */
230
+ static fromHex(hex) {
231
+ return new Digest(hexToBytes(hex));
232
+ }
233
+ /**
234
+ * Compute SHA-256 digest of data (called "image" in Rust).
235
+ *
236
+ * @param image - The data to hash
237
+ */
238
+ static fromImage(image) {
239
+ const hashData = (0, _bcts_crypto.sha256)(image);
240
+ return new Digest(new Uint8Array(hashData));
241
+ }
242
+ /**
243
+ * Compute SHA-256 digest from multiple data parts.
244
+ *
245
+ * The parts are concatenated and then hashed.
246
+ *
247
+ * @param imageParts - Array of byte arrays to concatenate and hash
248
+ */
249
+ static fromImageParts(imageParts) {
250
+ const totalLength = imageParts.reduce((sum, part) => sum + part.length, 0);
251
+ const buf = new Uint8Array(totalLength);
252
+ let offset = 0;
253
+ for (const part of imageParts) {
254
+ buf.set(part, offset);
255
+ offset += part.length;
256
+ }
257
+ return Digest.fromImage(buf);
258
+ }
259
+ /**
260
+ * Compute SHA-256 digest from an array of Digests.
261
+ *
262
+ * The digest bytes are concatenated and then hashed.
263
+ *
264
+ * @param digests - Array of Digests to combine
265
+ */
266
+ static fromDigests(digests) {
267
+ const buf = new Uint8Array(digests.length * Digest.DIGEST_SIZE);
268
+ let offset = 0;
269
+ for (const digest of digests) {
270
+ buf.set(digest._data, offset);
271
+ offset += Digest.DIGEST_SIZE;
272
+ }
273
+ return Digest.fromImage(buf);
274
+ }
275
+ /**
276
+ * Compute SHA-256 digest of data (legacy alias for fromImage).
277
+ * @deprecated Use fromImage instead
278
+ */
279
+ static hash(data) {
280
+ return Digest.fromImage(data);
281
+ }
282
+ /**
283
+ * Get the raw digest bytes as a copy.
284
+ */
285
+ toData() {
286
+ return new Uint8Array(this._data);
287
+ }
288
+ /**
289
+ * Get a reference to the raw digest bytes.
290
+ */
291
+ asBytes() {
292
+ return this._data;
293
+ }
294
+ /**
295
+ * Get hex string representation.
296
+ */
297
+ hex() {
298
+ return bytesToHex(this._data);
299
+ }
300
+ /**
301
+ * Get hex string representation (alias for hex()).
302
+ */
303
+ toHex() {
304
+ return this.hex();
305
+ }
306
+ /**
307
+ * Get base64 representation.
308
+ */
309
+ toBase64() {
310
+ return toBase64(this._data);
311
+ }
312
+ /**
313
+ * Get the first four bytes of the digest as a hexadecimal string.
314
+ * Useful for short descriptions.
315
+ */
316
+ shortDescription() {
317
+ return bytesToHex(this._data.slice(0, 4));
318
+ }
319
+ /**
320
+ * Validate the digest against the given image.
321
+ *
322
+ * The image is hashed with SHA-256 and compared to this digest.
323
+ * @returns `true` if the digest matches the image.
324
+ */
325
+ validate(image) {
326
+ return this.equals(Digest.fromImage(image));
327
+ }
328
+ /**
329
+ * Compare with another Digest.
330
+ */
331
+ equals(other) {
332
+ if (this._data.length !== other._data.length) return false;
333
+ for (let i = 0; i < this._data.length; i++) if (this._data[i] !== other._data[i]) return false;
334
+ return true;
335
+ }
336
+ /**
337
+ * Compare digests lexicographically.
338
+ */
339
+ compare(other) {
340
+ for (let i = 0; i < this._data.length; i++) {
341
+ const a = this._data[i];
342
+ const b = other._data[i];
343
+ if (a < b) return -1;
344
+ if (a > b) return 1;
345
+ }
346
+ return 0;
347
+ }
348
+ /**
349
+ * Get string representation.
350
+ */
351
+ toString() {
352
+ return `Digest(${this.hex()})`;
353
+ }
354
+ /**
355
+ * A Digest is its own digest provider - returns itself.
356
+ */
357
+ digest() {
358
+ return this;
359
+ }
360
+ /**
361
+ * Returns the CBOR tags associated with Digest.
362
+ */
363
+ cborTags() {
364
+ return (0, _bcts_dcbor.tagsForValues)([_bcts_tags.DIGEST.value]);
365
+ }
366
+ /**
367
+ * Returns the untagged CBOR encoding (as a byte string).
368
+ */
369
+ untaggedCbor() {
370
+ return (0, _bcts_dcbor.toByteString)(this._data);
371
+ }
372
+ /**
373
+ * Returns the tagged CBOR encoding.
374
+ */
375
+ taggedCbor() {
376
+ return (0, _bcts_dcbor.createTaggedCbor)(this);
377
+ }
378
+ /**
379
+ * Returns the tagged value in CBOR binary representation.
380
+ */
381
+ taggedCborData() {
382
+ return this.taggedCbor().toData();
383
+ }
384
+ /**
385
+ * Creates a Digest by decoding it from untagged CBOR.
386
+ */
387
+ fromUntaggedCbor(cbor) {
388
+ const data = (0, _bcts_dcbor.expectBytes)(cbor);
389
+ return Digest.fromData(data);
390
+ }
391
+ /**
392
+ * Creates a Digest by decoding it from tagged CBOR.
393
+ */
394
+ fromTaggedCbor(cbor) {
395
+ (0, _bcts_dcbor.validateTag)(cbor, this.cborTags());
396
+ const content = (0, _bcts_dcbor.extractTaggedContent)(cbor);
397
+ return this.fromUntaggedCbor(content);
398
+ }
399
+ /**
400
+ * Static method to decode from tagged CBOR.
401
+ */
402
+ static fromTaggedCbor(cbor) {
403
+ return new Digest(new Uint8Array(Digest.DIGEST_SIZE)).fromTaggedCbor(cbor);
404
+ }
405
+ /**
406
+ * Static method to decode from tagged CBOR binary data.
407
+ */
408
+ static fromTaggedCborData(data) {
409
+ const cbor = (0, _bcts_dcbor.decodeCbor)(data);
410
+ return Digest.fromTaggedCbor(cbor);
411
+ }
412
+ /**
413
+ * Static method to decode from untagged CBOR binary data.
414
+ */
415
+ static fromUntaggedCborData(data) {
416
+ const bytes = (0, _bcts_dcbor.expectBytes)((0, _bcts_dcbor.decodeCbor)(data));
417
+ return Digest.fromData(bytes);
418
+ }
419
+ /**
420
+ * Returns the UR representation of the Digest.
421
+ * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.
422
+ */
423
+ ur() {
424
+ return _bcts_uniform_resources.UR.new("digest", this.untaggedCbor());
425
+ }
426
+ /**
427
+ * Returns the UR string representation.
428
+ */
429
+ urString() {
430
+ return this.ur().string();
431
+ }
432
+ /**
433
+ * Creates a Digest from a UR.
434
+ */
435
+ static fromUR(ur) {
436
+ ur.checkType("digest");
437
+ return new Digest(new Uint8Array(Digest.DIGEST_SIZE)).fromUntaggedCbor(ur.cbor());
438
+ }
439
+ /**
440
+ * Creates a Digest from a UR string.
441
+ */
442
+ static fromURString(urString) {
443
+ const ur = _bcts_uniform_resources.UR.fromURString(urString);
444
+ return Digest.fromUR(ur);
445
+ }
446
+ /**
447
+ * Validate the given data against the digest, if any.
448
+ *
449
+ * Returns `true` if the digest is `undefined` or if the digest matches the
450
+ * image's digest. Returns `false` if the digest does not match.
451
+ */
452
+ static validateOpt(image, digest) {
453
+ if (digest === void 0) return true;
454
+ return digest.validate(image);
455
+ }
456
+ };
457
+
458
+ //#endregion
459
+ Object.defineProperty(exports, 'CryptoError', {
460
+ enumerable: true,
461
+ get: function () {
462
+ return CryptoError;
463
+ }
464
+ });
465
+ Object.defineProperty(exports, 'Digest', {
466
+ enumerable: true,
467
+ get: function () {
468
+ return Digest;
469
+ }
470
+ });
471
+ Object.defineProperty(exports, 'bytesEqual', {
472
+ enumerable: true,
473
+ get: function () {
474
+ return bytesEqual;
475
+ }
476
+ });
477
+ Object.defineProperty(exports, 'bytesToHex', {
478
+ enumerable: true,
479
+ get: function () {
480
+ return bytesToHex;
481
+ }
482
+ });
483
+ Object.defineProperty(exports, 'fromBase64', {
484
+ enumerable: true,
485
+ get: function () {
486
+ return fromBase64;
487
+ }
488
+ });
489
+ Object.defineProperty(exports, 'hexToBytes', {
490
+ enumerable: true,
491
+ get: function () {
492
+ return hexToBytes;
493
+ }
494
+ });
495
+ Object.defineProperty(exports, 'isError', {
496
+ enumerable: true,
497
+ get: function () {
498
+ return isError;
499
+ }
500
+ });
501
+ Object.defineProperty(exports, 'toBase64', {
502
+ enumerable: true,
503
+ get: function () {
504
+ return toBase64;
505
+ }
506
+ });
507
+ //# sourceMappingURL=digest-dd78wg6w.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"digest-dd78wg6w.cjs","names":["BaseCryptoError","SHA256_SIZE","TAG_DIGEST","UR"],"sources":["../src/error.ts","../src/utils.ts","../src/digest.ts"],"sourcesContent":["/**\n * Error types re-exported from @bcts/crypto\n * with additional factory methods for components\n *\n * Ported from bc-components-rust/src/error.rs\n */\n\nimport { CryptoError as BaseCryptoError } from \"@bcts/crypto\";\n\nexport class CryptoError extends BaseCryptoError {\n static invalidSize(expected: number, actual: number): CryptoError {\n return new CryptoError(`Invalid size: expected ${expected}, got ${actual}`);\n }\n\n static invalidFormat(message: string): CryptoError {\n return new CryptoError(`Invalid format: ${message}`);\n }\n\n static cryptoOperation(message: string): CryptoError {\n return new CryptoError(`Crypto operation failed: ${message}`);\n }\n\n static invalidInput(message: string): CryptoError {\n return new CryptoError(`Invalid input: ${message}`);\n }\n\n static dataTooShort(name: string, minSize: number, actual: number): CryptoError {\n return new CryptoError(`${name} too short: minimum ${minSize}, got ${actual}`);\n }\n\n static invalidData(message: string): CryptoError {\n return new CryptoError(`Invalid data: ${message}`);\n }\n}\n\nexport type Result<T> = T | Error;\n\nexport function isError(result: unknown): result is Error {\n return result instanceof Error;\n}\n","/**\n * Utility functions for byte array conversions and comparisons.\n *\n * These functions provide cross-platform support for common byte manipulation\n * operations needed in cryptographic and encoding contexts.\n *\n * @packageDocumentation\n */\n\n/**\n * Convert a Uint8Array to a lowercase hexadecimal string.\n *\n * @param data - The byte array to convert\n * @returns A lowercase hex string representation (2 characters per byte)\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([0xde, 0xad, 0xbe, 0xef]);\n * bytesToHex(bytes); // \"deadbeef\"\n * ```\n */\nexport function bytesToHex(data: Uint8Array): string {\n return Array.from(data)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n}\n\n/**\n * Convert a hexadecimal string to a Uint8Array.\n *\n * @param hex - A hex string (must have even length, case-insensitive)\n * @returns The decoded byte array\n * @throws {Error} If the hex string has odd length or contains invalid characters\n *\n * @example\n * ```typescript\n * hexToBytes(\"deadbeef\"); // Uint8Array([0xde, 0xad, 0xbe, 0xef])\n * hexToBytes(\"DEADBEEF\"); // Uint8Array([0xde, 0xad, 0xbe, 0xef])\n * hexToBytes(\"xyz\"); // throws Error: Invalid hex string\n * ```\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (hex.length % 2 !== 0) {\n throw new Error(`Hex string must have even length, got ${hex.length}`);\n }\n if (!/^[0-9A-Fa-f]*$/.test(hex)) {\n throw new Error(\"Invalid hex string: contains non-hexadecimal characters\");\n }\n const data = new Uint8Array(hex.length / 2);\n for (let i = 0; i < hex.length; i += 2) {\n data[i / 2] = parseInt(hex.substring(i, i + 2), 16);\n }\n return data;\n}\n\n/**\n * Convert a Uint8Array to a base64-encoded string.\n *\n * This function works in both browser and Node.js environments.\n * Uses btoa which is available in browsers and Node.js 16+.\n *\n * @param data - The byte array to encode\n * @returns A base64-encoded string\n *\n * @example\n * ```typescript\n * const bytes = new Uint8Array([72, 101, 108, 108, 111]); // \"Hello\"\n * toBase64(bytes); // \"SGVsbG8=\"\n * ```\n */\nexport function toBase64(data: Uint8Array): string {\n // Convert bytes to binary string without spread operator to avoid\n // call stack limits for large arrays (spread would fail at ~65k bytes)\n let binary = \"\";\n for (const byte of data) {\n binary += String.fromCharCode(byte);\n }\n return btoa(binary);\n}\n\n/**\n * Convert a base64-encoded string to a Uint8Array.\n *\n * This function works in both browser and Node.js environments.\n * Uses atob which is available in browsers and Node.js 16+.\n *\n * @param base64 - A base64-encoded string\n * @returns The decoded byte array\n *\n * @example\n * ```typescript\n * fromBase64(\"SGVsbG8=\"); // Uint8Array([72, 101, 108, 108, 111])\n * ```\n */\nexport function fromBase64(base64: string): Uint8Array {\n const binary = atob(base64);\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) {\n bytes[i] = binary.charCodeAt(i);\n }\n return bytes;\n}\n\n/**\n * Compare two Uint8Arrays for equality using constant-time comparison.\n *\n * This function is designed to be resistant to timing attacks by always\n * comparing all bytes regardless of where a difference is found. The\n * comparison time depends only on the length of the arrays, not on where\n * they differ.\n *\n * **Security Note**: If the arrays have different lengths, this function\n * returns `false` immediately, which does leak length information. For\n * cryptographic uses where length should also be secret, ensure both\n * arrays are the same length before comparison.\n *\n * @param a - First byte array\n * @param b - Second byte array\n * @returns `true` if both arrays have the same length and identical contents\n *\n * @example\n * ```typescript\n * const key1 = new Uint8Array([1, 2, 3, 4]);\n * const key2 = new Uint8Array([1, 2, 3, 4]);\n * const key3 = new Uint8Array([1, 2, 3, 5]);\n *\n * bytesEqual(key1, key2); // true\n * bytesEqual(key1, key3); // false\n * ```\n */\nexport function bytesEqual(a: Uint8Array, b: Uint8Array): boolean {\n if (a.length !== b.length) return false;\n let result = 0;\n for (let i = 0; i < a.length; i++) {\n result |= a[i] ^ b[i];\n }\n return result === 0;\n}\n","/**\n * SHA-256 cryptographic digest (32 bytes)\n *\n * Ported from bc-components-rust/src/digest.rs\n *\n * A `Digest` represents the cryptographic hash of some data. In this\n * implementation, SHA-256 is used, which produces a 32-byte hash value.\n * Digests are used throughout the crate for data verification and as unique\n * identifiers derived from data.\n *\n * # CBOR Serialization\n *\n * `Digest` implements the CBOR tagged encoding interfaces, which means it can be\n * serialized to and deserialized from CBOR with a specific tag (TAG_DIGEST = 40001).\n *\n * # UR Serialization\n *\n * When serialized as a Uniform Resource (UR), a `Digest` is represented as a\n * binary blob with the type \"digest\".\n *\n * @example\n * ```typescript\n * import { Digest } from '@bcts/components';\n *\n * // Create a digest from a string\n * const data = new TextEncoder().encode(\"hello world\");\n * const digest = Digest.fromImage(data);\n *\n * // Validate that the digest matches the original data\n * console.log(digest.validate(data)); // true\n *\n * // Create a digest from a hex string\n * const hexString = \"b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9\";\n * const digest2 = Digest.fromHex(hexString);\n *\n * // Retrieve the digest as hex\n * console.log(digest2.hex()); // b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9\n * ```\n */\n\nimport { sha256, SHA256_SIZE } from \"@bcts/crypto\";\nimport {\n type Cbor,\n type Tag,\n type CborTaggedEncodable,\n type CborTaggedDecodable,\n toByteString,\n expectBytes,\n createTaggedCbor,\n validateTag,\n extractTaggedContent,\n decodeCbor,\n tagsForValues,\n} from \"@bcts/dcbor\";\nimport { DIGEST as TAG_DIGEST } from \"@bcts/tags\";\nimport { UR, type UREncodable } from \"@bcts/uniform-resources\";\nimport { CryptoError } from \"./error.js\";\nimport { bytesToHex, hexToBytes, toBase64 } from \"./utils.js\";\nimport type { DigestProvider } from \"./digest-provider.js\";\n\nexport class Digest\n implements DigestProvider, CborTaggedEncodable, CborTaggedDecodable<Digest>, UREncodable\n{\n static readonly DIGEST_SIZE = SHA256_SIZE;\n\n private readonly _data: Uint8Array;\n\n private constructor(data: Uint8Array) {\n if (data.length !== Digest.DIGEST_SIZE) {\n throw CryptoError.invalidSize(Digest.DIGEST_SIZE, data.length);\n }\n this._data = new Uint8Array(data);\n }\n\n /**\n * Get the digest data.\n */\n data(): Uint8Array {\n return this._data;\n }\n\n // ============================================================================\n // Static Factory Methods\n // ============================================================================\n\n /**\n * Create a Digest from a 32-byte array.\n */\n static fromData(data: Uint8Array): Digest {\n return new Digest(new Uint8Array(data));\n }\n\n /**\n * Create a Digest from data, validating the length.\n * Alias for fromData for compatibility with Rust API.\n */\n static fromDataRef(data: Uint8Array): Digest {\n return Digest.fromData(data);\n }\n\n /**\n * Create a Digest from hex string.\n *\n * @throws Error if the hex string is not exactly 64 characters.\n */\n static fromHex(hex: string): Digest {\n return new Digest(hexToBytes(hex));\n }\n\n /**\n * Compute SHA-256 digest of data (called \"image\" in Rust).\n *\n * @param image - The data to hash\n */\n static fromImage(image: Uint8Array): Digest {\n const hashData = sha256(image);\n return new Digest(new Uint8Array(hashData));\n }\n\n /**\n * Compute SHA-256 digest from multiple data parts.\n *\n * The parts are concatenated and then hashed.\n *\n * @param imageParts - Array of byte arrays to concatenate and hash\n */\n static fromImageParts(imageParts: Uint8Array[]): Digest {\n const totalLength = imageParts.reduce((sum, part) => sum + part.length, 0);\n const buf = new Uint8Array(totalLength);\n let offset = 0;\n for (const part of imageParts) {\n buf.set(part, offset);\n offset += part.length;\n }\n return Digest.fromImage(buf);\n }\n\n /**\n * Compute SHA-256 digest from an array of Digests.\n *\n * The digest bytes are concatenated and then hashed.\n *\n * @param digests - Array of Digests to combine\n */\n static fromDigests(digests: Digest[]): Digest {\n const buf = new Uint8Array(digests.length * Digest.DIGEST_SIZE);\n let offset = 0;\n for (const digest of digests) {\n buf.set(digest._data, offset);\n offset += Digest.DIGEST_SIZE;\n }\n return Digest.fromImage(buf);\n }\n\n /**\n * Compute SHA-256 digest of data (legacy alias for fromImage).\n * @deprecated Use fromImage instead\n */\n static hash(data: Uint8Array): Digest {\n return Digest.fromImage(data);\n }\n\n // ============================================================================\n // Instance Methods\n // ============================================================================\n\n /**\n * Get the raw digest bytes as a copy.\n */\n toData(): Uint8Array {\n return new Uint8Array(this._data);\n }\n\n /**\n * Get a reference to the raw digest bytes.\n */\n asBytes(): Uint8Array {\n return this._data;\n }\n\n /**\n * Get hex string representation.\n */\n hex(): string {\n return bytesToHex(this._data);\n }\n\n /**\n * Get hex string representation (alias for hex()).\n */\n toHex(): string {\n return this.hex();\n }\n\n /**\n * Get base64 representation.\n */\n toBase64(): string {\n return toBase64(this._data);\n }\n\n /**\n * Get the first four bytes of the digest as a hexadecimal string.\n * Useful for short descriptions.\n */\n shortDescription(): string {\n return bytesToHex(this._data.slice(0, 4));\n }\n\n /**\n * Validate the digest against the given image.\n *\n * The image is hashed with SHA-256 and compared to this digest.\n * @returns `true` if the digest matches the image.\n */\n validate(image: Uint8Array): boolean {\n return this.equals(Digest.fromImage(image));\n }\n\n /**\n * Compare with another Digest.\n */\n equals(other: Digest): boolean {\n if (this._data.length !== other._data.length) return false;\n for (let i = 0; i < this._data.length; i++) {\n if (this._data[i] !== other._data[i]) return false;\n }\n return true;\n }\n\n /**\n * Compare digests lexicographically.\n */\n compare(other: Digest): number {\n for (let i = 0; i < this._data.length; i++) {\n const a = this._data[i];\n const b = other._data[i];\n if (a < b) return -1;\n if (a > b) return 1;\n }\n return 0;\n }\n\n /**\n * Get string representation.\n */\n toString(): string {\n return `Digest(${this.hex()})`;\n }\n\n // ============================================================================\n // DigestProvider Implementation\n // ============================================================================\n\n /**\n * A Digest is its own digest provider - returns itself.\n */\n digest(): Digest {\n return this;\n }\n\n // ============================================================================\n // CBOR Serialization (CborTaggedEncodable)\n // ============================================================================\n\n /**\n * Returns the CBOR tags associated with Digest.\n */\n cborTags(): Tag[] {\n return tagsForValues([TAG_DIGEST.value]);\n }\n\n /**\n * Returns the untagged CBOR encoding (as a byte string).\n */\n untaggedCbor(): Cbor {\n return toByteString(this._data);\n }\n\n /**\n * Returns the tagged CBOR encoding.\n */\n taggedCbor(): Cbor {\n return createTaggedCbor(this);\n }\n\n /**\n * Returns the tagged value in CBOR binary representation.\n */\n taggedCborData(): Uint8Array {\n return this.taggedCbor().toData();\n }\n\n // ============================================================================\n // CBOR Deserialization (CborTaggedDecodable)\n // ============================================================================\n\n /**\n * Creates a Digest by decoding it from untagged CBOR.\n */\n fromUntaggedCbor(cbor: Cbor): Digest {\n const data = expectBytes(cbor);\n return Digest.fromData(data);\n }\n\n /**\n * Creates a Digest by decoding it from tagged CBOR.\n */\n fromTaggedCbor(cbor: Cbor): Digest {\n validateTag(cbor, this.cborTags());\n const content = extractTaggedContent(cbor);\n return this.fromUntaggedCbor(content);\n }\n\n /**\n * Static method to decode from tagged CBOR.\n */\n static fromTaggedCbor(cbor: Cbor): Digest {\n const instance = new Digest(new Uint8Array(Digest.DIGEST_SIZE));\n return instance.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from tagged CBOR binary data.\n */\n static fromTaggedCborData(data: Uint8Array): Digest {\n const cbor = decodeCbor(data);\n return Digest.fromTaggedCbor(cbor);\n }\n\n /**\n * Static method to decode from untagged CBOR binary data.\n */\n static fromUntaggedCborData(data: Uint8Array): Digest {\n const cbor = decodeCbor(data);\n const bytes = expectBytes(cbor);\n return Digest.fromData(bytes);\n }\n\n // ============================================================================\n // UR Serialization (UREncodable)\n // ============================================================================\n\n /**\n * Returns the UR representation of the Digest.\n * Note: URs use untagged CBOR since the type is conveyed by the UR type itself.\n */\n ur(): UR {\n return UR.new(\"digest\", this.untaggedCbor());\n }\n\n /**\n * Returns the UR string representation.\n */\n urString(): string {\n return this.ur().string();\n }\n\n /**\n * Creates a Digest from a UR.\n */\n static fromUR(ur: UR): Digest {\n ur.checkType(\"digest\");\n const instance = new Digest(new Uint8Array(Digest.DIGEST_SIZE));\n return instance.fromUntaggedCbor(ur.cbor());\n }\n\n /**\n * Creates a Digest from a UR string.\n */\n static fromURString(urString: string): Digest {\n const ur = UR.fromURString(urString);\n return Digest.fromUR(ur);\n }\n\n // ============================================================================\n // Static Utility Methods\n // ============================================================================\n\n /**\n * Validate the given data against the digest, if any.\n *\n * Returns `true` if the digest is `undefined` or if the digest matches the\n * image's digest. Returns `false` if the digest does not match.\n */\n static validateOpt(image: Uint8Array, digest: Digest | undefined): boolean {\n if (digest === undefined) {\n return true;\n }\n return digest.validate(image);\n }\n}\n"],"mappings":";;;;;;;;;;;;;AASA,IAAa,cAAb,MAAa,oBAAoBA,yBAAgB;CAC/C,OAAO,YAAY,UAAkB,QAA6B;AAChE,SAAO,IAAI,YAAY,0BAA0B,SAAS,QAAQ,SAAS;;CAG7E,OAAO,cAAc,SAA8B;AACjD,SAAO,IAAI,YAAY,mBAAmB,UAAU;;CAGtD,OAAO,gBAAgB,SAA8B;AACnD,SAAO,IAAI,YAAY,4BAA4B,UAAU;;CAG/D,OAAO,aAAa,SAA8B;AAChD,SAAO,IAAI,YAAY,kBAAkB,UAAU;;CAGrD,OAAO,aAAa,MAAc,SAAiB,QAA6B;AAC9E,SAAO,IAAI,YAAY,GAAG,KAAK,sBAAsB,QAAQ,QAAQ,SAAS;;CAGhF,OAAO,YAAY,SAA8B;AAC/C,SAAO,IAAI,YAAY,iBAAiB,UAAU;;;AAMtD,SAAgB,QAAQ,QAAkC;AACxD,QAAO,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;ACjB3B,SAAgB,WAAW,MAA0B;AACnD,QAAO,MAAM,KAAK,KAAK,CACpB,KAAK,MAAM,EAAE,SAAS,GAAG,CAAC,SAAS,GAAG,IAAI,CAAC,CAC3C,KAAK,GAAG;;;;;;;;;;;;;;;;AAiBb,SAAgB,WAAW,KAAyB;AAClD,KAAI,IAAI,SAAS,MAAM,EACrB,OAAM,IAAI,MAAM,yCAAyC,IAAI,SAAS;AAExE,KAAI,CAA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