@wishknish/knishio-client-ts 0.9.5 → 0.9.7

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.
@@ -57,8 +57,8 @@ var KnishIO = (function (exports) {
57
57
  var __esm = (fn, res) => function __init() {
58
58
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
59
59
  };
60
- var __commonJS = (cb, mod2) => function __require() {
61
- return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
60
+ var __commonJS = (cb, mod) => function __require() {
61
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
62
62
  };
63
63
  var __export = (target, all) => {
64
64
  for (var name2 in all)
@@ -72,15 +72,15 @@ var KnishIO = (function (exports) {
72
72
  }
73
73
  return to;
74
74
  };
75
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
75
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
76
76
  // If the importer is in node compatibility mode or this is not an ESM
77
77
  // file that has been converted to a CommonJS file using a Babel-
78
78
  // compatible transform (i.e. "__esModule" has not been set), then set
79
79
  // "default" to the CommonJS "module.exports" for node compatibility.
80
- __defProp(target, "default", { value: mod2, enumerable: true }) ,
81
- mod2
80
+ __defProp(target, "default", { value: mod, enumerable: true }) ,
81
+ mod
82
82
  ));
83
- var __toCommonJS = (mod2) => __copyProps(__defProp({}, "__esModule", { value: true }), mod2);
83
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
84
84
 
85
85
  // src/exception/BaseException.ts
86
86
  exports.BaseException = void 0;
@@ -20064,6 +20064,55 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20064
20064
  }
20065
20065
  });
20066
20066
 
20067
+ // src/exception/SecretStorageException.ts
20068
+ exports.SecretStorageException = void 0;
20069
+ var init_SecretStorageException = __esm({
20070
+ "src/exception/SecretStorageException.ts"() {
20071
+ init_BaseException();
20072
+ exports.SecretStorageException = class _SecretStorageException extends exports.BaseException {
20073
+ constructor(message = "Secret storage operation failed", options = {}) {
20074
+ super("WALLET_CREDENTIAL_ERROR", message, {
20075
+ code: "SECRET_STORAGE_ERROR",
20076
+ ...options
20077
+ });
20078
+ }
20079
+ /**
20080
+ * Secret not found for the requested bundle hash
20081
+ */
20082
+ static notFound(bundleHash) {
20083
+ return new _SecretStorageException(`Secret not found for bundle: ${bundleHash}`, {
20084
+ code: "SECRET_NOT_FOUND",
20085
+ details: { bundleHash }
20086
+ });
20087
+ }
20088
+ /**
20089
+ * Decryption failed (wrong passphrase or corrupted payload)
20090
+ */
20091
+ static decryptionFailed(reason) {
20092
+ return new _SecretStorageException(
20093
+ `Failed to decrypt master secret: ${reason || "Invalid passphrase or corrupted ciphertext"}`,
20094
+ {
20095
+ code: "DECRYPTION_FAILED",
20096
+ details: { reason }
20097
+ }
20098
+ );
20099
+ }
20100
+ /**
20101
+ * Provider is unavailable in current platform
20102
+ */
20103
+ static unavailable(provider, reason) {
20104
+ return new _SecretStorageException(
20105
+ `Secret storage provider '${provider}' is unavailable: ${reason || "Hardware or API not accessible"}`,
20106
+ {
20107
+ code: "STORAGE_UNAVAILABLE",
20108
+ details: { provider, reason }
20109
+ }
20110
+ );
20111
+ }
20112
+ };
20113
+ }
20114
+ });
20115
+
20067
20116
  // src/exception/InvalidResponseException.ts
20068
20117
  exports.InvalidResponseException = void 0;
20069
20118
  var init_InvalidResponseException = __esm({
@@ -20526,6 +20575,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
20526
20575
  init_SignatureMismatchException();
20527
20576
  init_TransferBalanceException();
20528
20577
  init_WalletCredentialException();
20578
+ init_SecretStorageException();
20529
20579
  init_InvalidResponseException();
20530
20580
  init_BalanceInsufficientException();
20531
20581
  init_BatchIdException();
@@ -39975,11 +40025,9 @@ ${operationTypes.join("\n")}
39975
40025
  const base17Hash = convertToBase17(molecularHash);
39976
40026
  const enumerated = enumerateMolecularHash(base17Hash);
39977
40027
  const normalized = normalizeMolecularHash(enumerated);
39978
- let ots = otsFragments;
40028
+ const ots = otsFragments;
39979
40029
  if (ots.length !== 2048) {
39980
- if (ots.length !== 2048) {
39981
- return false;
39982
- }
40030
+ return false;
39983
40031
  }
39984
40032
  const otsChunks = [];
39985
40033
  for (let i4 = 0; i4 < ots.length; i4 += CRYPTO_CONSTANTS.KEY_FRAGMENT_SIZE) {
@@ -40482,6 +40530,123 @@ ${operationTypes.join("\n")}
40482
40530
  });
40483
40531
  }
40484
40532
  };
40533
+
40534
+ // src/libraries/array.ts
40535
+ function deepCloning(o3, h3) {
40536
+ let i4;
40537
+ let r3;
40538
+ let x2;
40539
+ const t3 = [Array, Date, Number, String, Boolean];
40540
+ const s2 = Object.prototype.toString;
40541
+ h3 = h3 || [];
40542
+ for (i4 = 0; i4 < h3.length; i4 += 2) {
40543
+ if (o3 === h3[i4]) {
40544
+ return h3[i4 + 1];
40545
+ }
40546
+ }
40547
+ if (!r3 && o3 && typeof o3 === "object") {
40548
+ r3 = {};
40549
+ for (i4 = 0; i4 < t3.length; i4++) {
40550
+ if (s2.call(o3) === s2.call(x2 = new t3[i4](o3))) {
40551
+ r3 = i4 ? x2 : [];
40552
+ }
40553
+ }
40554
+ h3.push(o3, r3);
40555
+ for (i4 in o3) {
40556
+ if (Object.prototype.hasOwnProperty.call(o3, i4)) {
40557
+ r3[i4] = deepCloning(o3[i4], h3);
40558
+ }
40559
+ }
40560
+ }
40561
+ return r3 || o3;
40562
+ }
40563
+ function chunkArray(arr, size) {
40564
+ const chunks = [];
40565
+ for (let i4 = 0; i4 < arr.length; i4 += size) {
40566
+ chunks.push(arr.slice(i4, i4 + size));
40567
+ }
40568
+ return chunks;
40569
+ }
40570
+ function diff(...arrays) {
40571
+ return [].concat(...arrays.map((arr, i4) => {
40572
+ const others = arrays.slice(0);
40573
+ others.splice(i4, 1);
40574
+ const unique = [...new Set([].concat(...others))];
40575
+ return arr.filter((item) => !unique.includes(item));
40576
+ }));
40577
+ }
40578
+ function intersect(...arrays) {
40579
+ if (arrays.length === 0) return [];
40580
+ if (arrays.length === 1) return arrays[0];
40581
+ return arrays.reduce(
40582
+ (first, second) => first.filter((item) => second.includes(item))
40583
+ );
40584
+ }
40585
+
40586
+ // src/core/PolicyMeta.ts
40587
+ var PolicyMeta = class _PolicyMeta {
40588
+ policy;
40589
+ /**
40590
+ * Create new PolicyMeta instance
40591
+ * Matches JavaScript SDK constructor signature exactly
40592
+ */
40593
+ constructor(policy = {}, metaKeys = []) {
40594
+ this.policy = _PolicyMeta.normalizePolicy(policy);
40595
+ this.fillDefault(metaKeys);
40596
+ }
40597
+ /**
40598
+ * Normalize policy object structure
40599
+ * Matches JavaScript SDK normalizePolicy method exactly
40600
+ */
40601
+ static normalizePolicy(policy = {}) {
40602
+ const policyMeta = {};
40603
+ for (const [policyKey, value2] of Object.entries(policy)) {
40604
+ if (value2 !== null && ["read", "write"].includes(policyKey)) {
40605
+ policyMeta[policyKey] = {};
40606
+ for (const [key, content] of Object.entries(value2)) {
40607
+ policyMeta[policyKey][key] = content;
40608
+ }
40609
+ }
40610
+ }
40611
+ return policyMeta;
40612
+ }
40613
+ /**
40614
+ * Fill default policy values for metadata keys
40615
+ * Matches JavaScript SDK fillDefault method exactly
40616
+ */
40617
+ fillDefault(metaKeys = []) {
40618
+ const readPolicy = Array.from(this.policy).filter((item) => item.action === "read");
40619
+ const writePolicy = Array.from(this.policy).filter((item) => item.action === "write");
40620
+ for (const [type2, value2] of Object.entries({
40621
+ read: readPolicy,
40622
+ write: writePolicy
40623
+ })) {
40624
+ const policyKey = value2.map((item) => item.key);
40625
+ if (!this.policy[type2]) {
40626
+ this.policy[type2] = {};
40627
+ }
40628
+ for (const key of diff(metaKeys, policyKey)) {
40629
+ if (!this.policy[type2][key]) {
40630
+ this.policy[type2][key] = type2 === "write" && !["characters", "pubkey"].includes(key) ? ["self"] : ["all"];
40631
+ }
40632
+ }
40633
+ }
40634
+ }
40635
+ /**
40636
+ * Get the policy object
40637
+ * Matches JavaScript SDK get method exactly
40638
+ */
40639
+ get() {
40640
+ return this.policy;
40641
+ }
40642
+ /**
40643
+ * Convert policy to JSON string
40644
+ * Matches JavaScript SDK toJson method exactly
40645
+ */
40646
+ toJson() {
40647
+ return JSON.stringify(this.get());
40648
+ }
40649
+ };
40485
40650
  var AtomMeta = class _AtomMeta {
40486
40651
  meta;
40487
40652
  /**
@@ -40577,8 +40742,9 @@ ${operationTypes.join("\n")}
40577
40742
  * @return This instance for chaining
40578
40743
  */
40579
40744
  addPolicy(policy) {
40745
+ const policyMeta = new PolicyMeta(policy, Object.keys(this.meta));
40580
40746
  this.merge({
40581
- policy: JSON.stringify(policy)
40747
+ policy: policyMeta.toJson()
40582
40748
  });
40583
40749
  return this;
40584
40750
  }
@@ -41214,8 +41380,89 @@ ${operationTypes.join("\n")}
41214
41380
  return value2;
41215
41381
  }
41216
41382
 
41383
+ // src/core/TokenUnit.ts
41384
+ var TokenUnit = class _TokenUnit {
41385
+ id;
41386
+ name;
41387
+ metas;
41388
+ /**
41389
+ * Create new TokenUnit instance
41390
+ * Matches JavaScript SDK constructor signature exactly
41391
+ */
41392
+ constructor(id, name2, metas) {
41393
+ this.id = id;
41394
+ this.name = name2;
41395
+ this.metas = metas || {};
41396
+ }
41397
+ /**
41398
+ * Create TokenUnit from GraphQL response data
41399
+ * Matches JavaScript SDK createFromGraphQL method exactly
41400
+ */
41401
+ static createFromGraphQL(data) {
41402
+ let metas = data.metas || {};
41403
+ if (Array.isArray(metas) && metas.length) {
41404
+ try {
41405
+ metas = JSON.parse(metas);
41406
+ if (!metas) {
41407
+ metas = {};
41408
+ }
41409
+ } catch (error62) {
41410
+ metas = {};
41411
+ }
41412
+ }
41413
+ return new _TokenUnit(
41414
+ data.id,
41415
+ data.name,
41416
+ metas
41417
+ );
41418
+ }
41419
+ /**
41420
+ * Create TokenUnit from database array data
41421
+ * Matches JavaScript SDK createFromDB method exactly
41422
+ */
41423
+ static createFromDB(data) {
41424
+ return new _TokenUnit(
41425
+ data[0],
41426
+ data[1],
41427
+ data.length > 2 ? data[2] : {}
41428
+ );
41429
+ }
41430
+ /**
41431
+ * Get fragment zone from metadata
41432
+ * Matches JavaScript SDK getFragmentZone method exactly
41433
+ */
41434
+ getFragmentZone() {
41435
+ return this.metas.fragmentZone || null;
41436
+ }
41437
+ /**
41438
+ * Get fused token units from metadata
41439
+ * Matches JavaScript SDK getFusedTokenUnits method exactly
41440
+ */
41441
+ getFusedTokenUnits() {
41442
+ return this.metas.fusedTokenUnits || null;
41443
+ }
41444
+ /**
41445
+ * Convert to data array format
41446
+ * Matches JavaScript SDK toData method exactly
41447
+ */
41448
+ toData() {
41449
+ return [this.id, this.name, this.metas];
41450
+ }
41451
+ /**
41452
+ * Convert to GraphQL response format
41453
+ * Matches JavaScript SDK toGraphQLResponse method exactly
41454
+ */
41455
+ toGraphQLResponse() {
41456
+ return {
41457
+ id: this.id,
41458
+ name: this.name,
41459
+ metas: JSON.stringify(this.metas)
41460
+ };
41461
+ }
41462
+ };
41463
+
41217
41464
  // node_modules/@noble/hashes/_u64.js
41218
- var U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
41465
+ var U32_MASK64 = /* @__PURE__ */ (() => BigInt(2 ** 32 - 1))();
41219
41466
  var _32n = /* @__PURE__ */ BigInt(32);
41220
41467
  function fromBig(n3, le = false) {
41221
41468
  if (le)
@@ -41232,44 +41479,60 @@ ${operationTypes.join("\n")}
41232
41479
  }
41233
41480
  return [Ah, Al];
41234
41481
  }
41235
- var rotlSH = (h3, l3, s2) => h3 << s2 | l3 >>> 32 - s2;
41236
- var rotlSL = (h3, l3, s2) => l3 << s2 | h3 >>> 32 - s2;
41237
- var rotlBH = (h3, l3, s2) => l3 << s2 - 32 | h3 >>> 64 - s2;
41238
- var rotlBL = (h3, l3, s2) => h3 << s2 - 32 | l3 >>> 64 - s2;
41239
41482
 
41240
41483
  // node_modules/@noble/hashes/utils.js
41241
41484
  function isBytes(a3) {
41242
- return a3 instanceof Uint8Array || ArrayBuffer.isView(a3) && a3.constructor.name === "Uint8Array";
41485
+ return a3 instanceof Uint8Array || ArrayBuffer.isView(a3) && a3.constructor.name === "Uint8Array" && "BYTES_PER_ELEMENT" in a3 && a3.BYTES_PER_ELEMENT === 1;
41243
41486
  }
41487
+ var atitle = (title) => title ? `"${title}" ` : "";
41244
41488
  function anumber(n3, title = "") {
41245
- if (!Number.isSafeInteger(n3) || n3 < 0) {
41246
- const prefix = title && `"${title}" `;
41247
- throw new Error(`${prefix}expected integer >= 0, got ${n3}`);
41248
- }
41489
+ if (typeof n3 !== "number")
41490
+ throw new TypeError(atitle(title) + "expected number, got " + typeof n3);
41491
+ if (!Number.isSafeInteger(n3) || n3 < 0)
41492
+ throw new RangeError(atitle(title) + "expected integer >= 0, got " + n3);
41493
+ return n3;
41249
41494
  }
41250
- function abytes(value2, length, title = "") {
41251
- const bytes = isBytes(value2);
41252
- const len = value2?.length;
41253
- const needsLen = length !== void 0;
41254
- if (!bytes || needsLen && len !== length) {
41255
- const prefix = title && `"${title}" `;
41256
- const ofLen = needsLen ? ` of length ${length}` : "";
41257
- const got = bytes ? `length=${len}` : `type=${typeof value2}`;
41258
- throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
41259
- }
41495
+ function abool(value2, title = "") {
41496
+ if (typeof value2 !== "boolean")
41497
+ throw new TypeError(atitle(title) + "expected boolean, got type=" + typeof value2);
41260
41498
  return value2;
41261
41499
  }
41500
+ function abytes(value2, length, title = "") {
41501
+ if (isBytes(value2) && (length === void 0 || value2.length === length))
41502
+ return value2;
41503
+ if (length !== void 0)
41504
+ anumber(length, "length");
41505
+ const bytes = isBytes(value2);
41506
+ const ofLen = length !== void 0 ? ` of length ${length}` : "";
41507
+ const got = bytes ? `length=${value2.length}` : `type=${typeof value2}`;
41508
+ const message = atitle(title) + "expected Uint8Array" + ofLen + ", got " + got;
41509
+ if (!bytes)
41510
+ throw new TypeError(message);
41511
+ throw new RangeError(message);
41512
+ }
41513
+ var aobject = (value2, label) => {
41514
+ if (value2 === null || typeof value2 !== "object" || Array.isArray(value2))
41515
+ throw new TypeError((label === "object" ? "" : `"${label}" `) + "expected object, got type=" + typeof value2);
41516
+ };
41517
+ var aopts = (value2, label) => {
41518
+ aobject(value2, label);
41519
+ const proto = Object.getPrototypeOf(value2);
41520
+ if (proto !== Object.prototype && proto !== null)
41521
+ throw new TypeError(`"${label}" expected plain object`);
41522
+ if (Object.hasOwn(value2, "__proto__"))
41523
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
41524
+ };
41262
41525
  function aexists(instance, checkFinished = true) {
41263
41526
  if (instance.destroyed)
41264
- throw new Error("Hash instance has been destroyed");
41527
+ throw new Error("hash was destroyed");
41265
41528
  if (checkFinished && instance.finished)
41266
- throw new Error("Hash#digest() has already been called");
41529
+ throw new Error("digest() was already called");
41267
41530
  }
41268
41531
  function aoutput(out, instance) {
41269
- abytes(out, void 0, "digestInto() output");
41532
+ abytes(out, void 0, "output");
41270
41533
  const min = instance.outputLen;
41271
- if (out.length < min) {
41272
- throw new Error('"digestInto() output" expected to be of length >=' + min);
41534
+ if (!(out.length >= min)) {
41535
+ throw new RangeError('"output" expected length >= ' + min);
41273
41536
  }
41274
41537
  }
41275
41538
  function u32(arr) {
@@ -41291,22 +41554,38 @@ ${operationTypes.join("\n")}
41291
41554
  return arr;
41292
41555
  }
41293
41556
  var swap32IfBE = isLE ? (u4) => u4 : byteSwap32;
41557
+ function checkOpts(defaults, opts2, title = "opts") {
41558
+ aopts(defaults, "defaults");
41559
+ if (opts2 !== void 0)
41560
+ aopts(opts2, title);
41561
+ const merged = Object.assign(/* @__PURE__ */ Object.create(null), defaults, opts2);
41562
+ return merged;
41563
+ }
41294
41564
  function createHasher(hashCons, info = {}) {
41565
+ if (typeof hashCons !== "function")
41566
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
41567
+ info = checkOpts({}, info, "info");
41295
41568
  const hashC = (msg, opts2) => hashCons(opts2).update(msg).digest();
41296
41569
  const tmp = hashCons(void 0);
41297
41570
  hashC.outputLen = tmp.outputLen;
41298
41571
  hashC.blockLen = tmp.blockLen;
41572
+ hashC.canXOF = tmp.canXOF;
41299
41573
  hashC.create = (opts2) => hashCons(opts2);
41300
41574
  Object.assign(hashC, info);
41301
41575
  return Object.freeze(hashC);
41302
41576
  }
41303
41577
  function randomBytes(bytesLength = 32) {
41578
+ anumber(bytesLength, "bytesLength");
41304
41579
  const cr = typeof globalThis === "object" ? globalThis.crypto : null;
41305
41580
  if (typeof cr?.getRandomValues !== "function")
41306
41581
  throw new Error("crypto.getRandomValues must be defined");
41582
+ if (bytesLength > 65536)
41583
+ throw new RangeError(`"bytesLength" expected <= 65536, got ${bytesLength}`);
41307
41584
  return cr.getRandomValues(new Uint8Array(bytesLength));
41308
41585
  }
41309
41586
  var oidNist = (suffix) => ({
41587
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
41588
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
41310
41589
  oid: Uint8Array.from([6, 9, 96, 134, 72, 1, 101, 3, 4, 2, suffix])
41311
41590
  });
41312
41591
 
@@ -41335,10 +41614,21 @@ ${operationTypes.join("\n")}
41335
41614
  var IOTAS = split(_SHA3_IOTA, true);
41336
41615
  var SHA3_IOTA_H = IOTAS[0];
41337
41616
  var SHA3_IOTA_L = IOTAS[1];
41617
+ var rotlSH = (h3, l3, s2) => h3 << s2 | l3 >>> 32 - s2;
41618
+ var rotlSL = (h3, l3, s2) => l3 << s2 | h3 >>> 32 - s2;
41619
+ var rotlBH = (h3, l3, s2) => l3 << s2 - 32 | h3 >>> 64 - s2;
41620
+ var rotlBL = (h3, l3, s2) => h3 << s2 - 32 | l3 >>> 64 - s2;
41338
41621
  var rotlH = (h3, l3, s2) => s2 > 32 ? rotlBH(h3, l3, s2) : rotlSH(h3, l3, s2);
41339
41622
  var rotlL = (h3, l3, s2) => s2 > 32 ? rotlBL(h3, l3, s2) : rotlSL(h3, l3, s2);
41623
+ var B2 = new Uint32Array(5 * 2);
41340
41624
  function keccakP(s2, rounds = 24) {
41341
- const B2 = new Uint32Array(5 * 2);
41625
+ if (!(s2 instanceof Uint32Array))
41626
+ throw new TypeError('"s" expected Uint32Array(50), got type=' + typeof s2);
41627
+ if (s2.length !== 50)
41628
+ throw new RangeError('"s" expected Uint32Array(50), got length=' + s2.length);
41629
+ anumber(rounds, "rounds");
41630
+ if (rounds < 1 || rounds > 24)
41631
+ throw new Error('"rounds" expected integer 1..24');
41342
41632
  for (let round = 24 - rounds; round < 24; round++) {
41343
41633
  for (let x2 = 0; x2 < 10; x2++)
41344
41634
  B2[x2] = s2[x2] ^ s2[x2 + 10] ^ s2[x2 + 20] ^ s2[x2 + 30] ^ s2[x2 + 40];
@@ -41367,10 +41657,17 @@ ${operationTypes.join("\n")}
41367
41657
  s2[PI + 1] = Tl;
41368
41658
  }
41369
41659
  for (let y3 = 0; y3 < 50; y3 += 10) {
41370
- for (let x2 = 0; x2 < 10; x2++)
41371
- B2[x2] = s2[y3 + x2];
41372
- for (let x2 = 0; x2 < 10; x2++)
41373
- s2[y3 + x2] ^= ~B2[(x2 + 2) % 10] & B2[(x2 + 4) % 10];
41660
+ const b0 = s2[y3], b1 = s2[y3 + 1], b2 = s2[y3 + 2], b3 = s2[y3 + 3];
41661
+ s2[y3] ^= ~s2[y3 + 2] & s2[y3 + 4];
41662
+ s2[y3 + 1] ^= ~s2[y3 + 3] & s2[y3 + 5];
41663
+ s2[y3 + 2] ^= ~s2[y3 + 4] & s2[y3 + 6];
41664
+ s2[y3 + 3] ^= ~s2[y3 + 5] & s2[y3 + 7];
41665
+ s2[y3 + 4] ^= ~s2[y3 + 6] & s2[y3 + 8];
41666
+ s2[y3 + 5] ^= ~s2[y3 + 7] & s2[y3 + 9];
41667
+ s2[y3 + 6] ^= ~s2[y3 + 8] & b0;
41668
+ s2[y3 + 7] ^= ~s2[y3 + 9] & b1;
41669
+ s2[y3 + 8] ^= ~b0 & b2;
41670
+ s2[y3 + 9] ^= ~b1 & b3;
41374
41671
  }
41375
41672
  s2[0] ^= SHA3_IOTA_H[round];
41376
41673
  s2[1] ^= SHA3_IOTA_L[round];
@@ -41387,18 +41684,24 @@ ${operationTypes.join("\n")}
41387
41684
  blockLen;
41388
41685
  suffix;
41389
41686
  outputLen;
41687
+ canXOF;
41390
41688
  enableXOF = false;
41391
41689
  rounds;
41392
41690
  // NOTE: we accept arguments in bytes instead of bits here.
41393
41691
  constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {
41692
+ anumber(blockLen, "blockLen");
41693
+ anumber(suffix, "suffix");
41694
+ anumber(rounds, "rounds");
41695
+ abool(enableXOF, "enableXOF");
41394
41696
  this.blockLen = blockLen;
41395
41697
  this.suffix = suffix;
41396
41698
  this.outputLen = outputLen;
41397
41699
  this.enableXOF = enableXOF;
41700
+ this.canXOF = enableXOF;
41398
41701
  this.rounds = rounds;
41399
41702
  anumber(outputLen, "outputLen");
41400
41703
  if (!(0 < blockLen && blockLen < 200))
41401
- throw new Error("only keccak-f1600 function is supported");
41704
+ throw new Error('"blockLen" must be 1..199');
41402
41705
  this.state = new Uint8Array(200);
41403
41706
  this.state32 = u32(this.state);
41404
41707
  }
@@ -41415,9 +41718,20 @@ ${operationTypes.join("\n")}
41415
41718
  update(data) {
41416
41719
  aexists(this);
41417
41720
  abytes(data);
41418
- const { blockLen, state } = this;
41721
+ const { blockLen, state, state32 } = this;
41419
41722
  const len = data.length;
41723
+ const canUseU32 = blockLen % 4 === 0 && data.byteOffset % 4 === 0;
41724
+ const blockLen32 = blockLen / 4;
41725
+ const data32 = canUseU32 && len >= blockLen ? u32(data) : void 0;
41420
41726
  for (let pos = 0; pos < len; ) {
41727
+ if (data32 !== void 0 && this.pos === 0 && pos % 4 === 0 && len - pos >= blockLen) {
41728
+ for (let i4 = 0, o3 = pos / 4; i4 < blockLen32; i4++)
41729
+ state32[i4] ^= data32[o3 + i4];
41730
+ pos += blockLen;
41731
+ this.pos = blockLen;
41732
+ this.keccak();
41733
+ continue;
41734
+ }
41421
41735
  const take2 = Math.min(blockLen - this.pos, len - pos);
41422
41736
  for (let i4 = 0; i4 < take2; i4++)
41423
41737
  state[this.pos++] ^= data[pos++];
@@ -41455,7 +41769,7 @@ ${operationTypes.join("\n")}
41455
41769
  }
41456
41770
  xofInto(out) {
41457
41771
  if (!this.enableXOF)
41458
- throw new Error("XOF is not possible for this instance");
41772
+ throw new Error("XOF is not enabled");
41459
41773
  return this.writeInto(out);
41460
41774
  }
41461
41775
  xof(bytes) {
@@ -41466,12 +41780,13 @@ ${operationTypes.join("\n")}
41466
41780
  aoutput(out, this);
41467
41781
  if (this.finished)
41468
41782
  throw new Error("digest() was already called");
41469
- this.writeInto(out);
41783
+ this.writeInto(out.length === this.outputLen ? out : out.subarray(0, this.outputLen));
41470
41784
  this.destroy();
41471
- return out;
41472
41785
  }
41473
41786
  digest() {
41474
- return this.digestInto(new Uint8Array(this.outputLen));
41787
+ const out = new Uint8Array(this.outputLen);
41788
+ this.digestInto(out);
41789
+ return out;
41475
41790
  }
41476
41791
  destroy() {
41477
41792
  this.destroyed = true;
@@ -41480,6 +41795,7 @@ ${operationTypes.join("\n")}
41480
41795
  _cloneInto(to) {
41481
41796
  const { blockLen, suffix, outputLen, rounds, enableXOF } = this;
41482
41797
  to ||= new _Keccak(blockLen, suffix, outputLen, enableXOF, rounds);
41798
+ to.blockLen = blockLen;
41483
41799
  to.state32.set(this.state32);
41484
41800
  to.pos = this.pos;
41485
41801
  to.posOut = this.posOut;
@@ -41488,6 +41804,7 @@ ${operationTypes.join("\n")}
41488
41804
  to.suffix = suffix;
41489
41805
  to.outputLen = outputLen;
41490
41806
  to.enableXOF = enableXOF;
41807
+ to.canXOF = this.canXOF;
41491
41808
  to.destroyed = this.destroyed;
41492
41809
  return to;
41493
41810
  }
@@ -41505,35 +41822,73 @@ ${operationTypes.join("\n")}
41505
41822
  64,
41506
41823
  /* @__PURE__ */ oidNist(10)
41507
41824
  );
41508
- var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true), info);
41825
+ var genShake = (suffix, blockLen, outputLen, info = {}) => createHasher((opts2 = {}) => {
41826
+ opts2 = checkOpts({}, opts2);
41827
+ return new Keccak(blockLen, suffix, opts2.dkLen === void 0 ? outputLen : opts2.dkLen, true);
41828
+ }, info);
41509
41829
  var shake128 = /* @__PURE__ */ genShake(31, 168, 16, /* @__PURE__ */ oidNist(11));
41510
41830
  var shake2562 = /* @__PURE__ */ genShake(31, 136, 32, /* @__PURE__ */ oidNist(12));
41511
41831
 
41832
+ // node_modules/@noble/curves/utils.js
41833
+ function aobject2(value2, title = "object") {
41834
+ if (value2 === null || typeof value2 !== "object" || Array.isArray(value2))
41835
+ throw new TypeError(title === "object" ? "expected valid options object" : `"${title}" expected object, got type=${typeof value2}`);
41836
+ return value2;
41837
+ }
41838
+ function validateObject(object2, fields = {}, optFields = {}, title = "object") {
41839
+ aobject2(object2, title);
41840
+ aobject2(fields, "fields");
41841
+ aobject2(optFields, "optFields");
41842
+ function checkField(fieldName, expectedType, isOpt) {
41843
+ const label = title === "object" ? `param "${String(fieldName)}"` : `"${title}.${String(fieldName)}"`;
41844
+ const val = object2[fieldName];
41845
+ if (!Object.hasOwn(object2, fieldName) && (isOpt ? val !== void 0 : expectedType !== "function")) {
41846
+ throw new TypeError(`${label} is invalid: expected own property`);
41847
+ }
41848
+ if (isOpt && val === void 0)
41849
+ return;
41850
+ const current = typeof val;
41851
+ if (current !== expectedType || val === null)
41852
+ throw new TypeError(`${label} is invalid: expected ${expectedType}, got ${current}`);
41853
+ }
41854
+ const iter = (f3, isOpt) => Object.entries(f3).forEach(([k2, v3]) => checkField(k2, v3, isOpt));
41855
+ iter(fields, false);
41856
+ iter(optFields, true);
41857
+ }
41858
+
41512
41859
  // node_modules/@noble/curves/abstract/fft.js
41513
- function checkU32(n3) {
41860
+ function checkU32(n3, title = "n") {
41861
+ if (typeof n3 !== "number")
41862
+ throw new TypeError(`wrong u32 integer "${title}": expected number, got type=${typeof n3}`);
41514
41863
  if (!Number.isSafeInteger(n3) || n3 < 0 || n3 > 4294967295)
41515
- throw new Error("wrong u32 integer:" + n3);
41864
+ throw new RangeError(`wrong u32 integer "${title}": expected 0..4294967295, got ${n3}`);
41516
41865
  return n3;
41517
41866
  }
41518
41867
  function isPowerOfTwo(x2) {
41519
- checkU32(x2);
41868
+ checkU32(x2, "x");
41520
41869
  return (x2 & x2 - 1) === 0 && x2 !== 0;
41521
41870
  }
41522
41871
  function reverseBits(n3, bits) {
41523
41872
  checkU32(n3);
41873
+ if (typeof bits !== "number")
41874
+ throw new TypeError('"bits" expected number, got type=' + typeof bits);
41875
+ if (!Number.isSafeInteger(bits) || bits < 0 || bits > 32)
41876
+ throw new Error(`expected integer 0 <= bits <= 32, got ${bits}`);
41524
41877
  let reversed = 0;
41525
41878
  for (let i4 = 0; i4 < bits; i4++, n3 >>>= 1)
41526
41879
  reversed = reversed << 1 | n3 & 1;
41527
- return reversed;
41880
+ return reversed >>> 0;
41528
41881
  }
41529
41882
  function log2(n3) {
41530
41883
  checkU32(n3);
41531
41884
  return 31 - Math.clz32(n3);
41532
41885
  }
41533
41886
  function bitReversalInplace(values) {
41887
+ if (!values || typeof values !== "object" || typeof values.length !== "number")
41888
+ throw new TypeError('"values" expected array-like, got type=' + typeof values);
41534
41889
  const n3 = values.length;
41535
- if (n3 < 2 || !isPowerOfTwo(n3))
41536
- throw new Error("n must be a power of 2 and greater than 1. Got " + n3);
41890
+ if (!isPowerOfTwo(n3))
41891
+ throw new Error("expected positive power-of-two length, got " + n3);
41537
41892
  const bits = log2(n3);
41538
41893
  for (let i4 = 0; i4 < n3; i4++) {
41539
41894
  const j2 = reverseBits(i4, bits);
@@ -41546,10 +41901,18 @@ ${operationTypes.join("\n")}
41546
41901
  return values;
41547
41902
  }
41548
41903
  var FFTCore = (F3, coreOpts) => {
41904
+ validateObject(coreOpts, { N: "number", roots: "object", dit: "boolean" }, { invertButterflies: "boolean", skipStages: "number", brp: "boolean" }, "coreOpts");
41549
41905
  const { N: N3, roots, dit, invertButterflies = false, skipStages = 0, brp = true } = coreOpts;
41906
+ checkU32(N3, "coreOpts.N");
41550
41907
  const bits = log2(N3);
41551
41908
  if (!isPowerOfTwo(N3))
41552
41909
  throw new Error("FFT: Polynomial size should be power of two");
41910
+ checkU32(skipStages, "coreOpts.skipStages");
41911
+ const maxSkipStages = bits === 0 ? 0 : bits - 1;
41912
+ if (skipStages > maxSkipStages)
41913
+ throw new Error(`FFT: wrong skipStages: expected 0 <= skipStages <= ${maxSkipStages}`);
41914
+ if (roots.length !== N3)
41915
+ throw new Error(`FFT: wrong roots length: expected ${N3}, got ${roots.length}`);
41553
41916
  const isDit = dit !== invertButterflies;
41554
41917
  return (values) => {
41555
41918
  if (values.length !== N3)
@@ -41590,8 +41953,19 @@ ${operationTypes.join("\n")}
41590
41953
  };
41591
41954
 
41592
41955
  // node_modules/@noble/post-quantum/utils.js
41956
+ var abytesDoc = abytes;
41593
41957
  var randomBytes2 = randomBytes;
41958
+ function aarray2(item, title, inner = () => {
41959
+ }) {
41960
+ if (!Array.isArray(item))
41961
+ throw new TypeError(`"${title}" expected array, got type=${typeof item}`);
41962
+ for (let i4 = 0; i4 < item.length; i4++)
41963
+ inner(item[i4], `${title}[${i4}]`);
41964
+ return item;
41965
+ }
41594
41966
  function equalBytes(a3, b2) {
41967
+ a3 = abytes(a3);
41968
+ b2 = abytes(b2);
41595
41969
  if (a3.length !== b2.length)
41596
41970
  return false;
41597
41971
  let diff3 = 0;
@@ -41600,7 +41974,7 @@ ${operationTypes.join("\n")}
41600
41974
  return diff3 === 0;
41601
41975
  }
41602
41976
  function copyBytes(bytes) {
41603
- return Uint8Array.from(bytes);
41977
+ return new Uint8Array(abytes(bytes));
41604
41978
  }
41605
41979
  function splitCoder(label, ...lengths) {
41606
41980
  const getLength = (c3) => typeof c3 === "number" ? c3 : c3.bytesLen;
@@ -41635,15 +42009,17 @@ ${operationTypes.join("\n")}
41635
42009
  };
41636
42010
  }
41637
42011
  function vecCoder(c3, vecLen) {
41638
- const bytesLen = vecLen * c3.bytesLen;
42012
+ const coder = c3;
42013
+ const bytesLen = vecLen * coder.bytesLen;
41639
42014
  return {
41640
42015
  bytesLen,
41641
42016
  encode: (u4) => {
41642
- if (u4.length !== vecLen)
41643
- throw new Error(`vecCoder.encode: wrong length=${u4.length}. Expected: ${vecLen}`);
42017
+ const uArr = aarray2(u4, "u");
42018
+ if (uArr.length !== vecLen)
42019
+ throw new RangeError(`vecCoder.encode: wrong length=${uArr.length}. Expected: ${vecLen}`);
41644
42020
  const res = new Uint8Array(bytesLen);
41645
- for (let i4 = 0, pos = 0; i4 < u4.length; i4++) {
41646
- const b2 = c3.encode(u4[i4]);
42021
+ for (let i4 = 0, pos = 0; i4 < uArr.length; i4++) {
42022
+ const b2 = coder.encode(uArr[i4]);
41647
42023
  res.set(b2, pos);
41648
42024
  b2.fill(0);
41649
42025
  pos += b2.length;
@@ -41653,8 +42029,8 @@ ${operationTypes.join("\n")}
41653
42029
  decode: (a3) => {
41654
42030
  abytes(a3, bytesLen);
41655
42031
  const r3 = [];
41656
- for (let i4 = 0; i4 < a3.length; i4 += c3.bytesLen)
41657
- r3.push(c3.decode(a3.subarray(i4, i4 + c3.bytesLen)));
42032
+ for (let i4 = 0; i4 < a3.length; i4 += coder.bytesLen)
42033
+ r3.push(coder.decode(a3.subarray(i4, i4 + coder.bytesLen)));
41658
42034
  return r3;
41659
42035
  }
41660
42036
  };
@@ -41669,18 +42045,21 @@ ${operationTypes.join("\n")}
41669
42045
  }
41670
42046
  }
41671
42047
  function getMask(bits) {
41672
- return (1 << bits) - 1;
42048
+ anumber(bits, "bits");
42049
+ if (bits > 32)
42050
+ throw new RangeError('"bits" expected <= 32, got ' + bits);
42051
+ return bits === 32 ? 4294967295 : ~(-1 << bits) >>> 0;
41673
42052
  }
41674
42053
 
41675
42054
  // node_modules/@noble/post-quantum/_crystals.js
41676
42055
  var genCrystals = (opts2) => {
41677
42056
  const { newPoly, N: N3, Q: Q4, F: F3, ROOT_OF_UNITY: ROOT_OF_UNITY2, brvBits} = opts2;
41678
- const mod2 = (a3, modulo = Q4) => {
42057
+ const mod = (a3, modulo = Q4) => {
41679
42058
  const result = a3 % modulo | 0;
41680
42059
  return (result >= 0 ? result | 0 : modulo + result | 0) | 0;
41681
42060
  };
41682
42061
  const smod = (a3, modulo = Q4) => {
41683
- const r3 = mod2(a3, modulo) | 0;
42062
+ const r3 = mod(a3, modulo) | 0;
41684
42063
  return (r3 > modulo >> 1 ? r3 - modulo | 0 : r3) | 0;
41685
42064
  };
41686
42065
  function getZettas() {
@@ -41692,47 +42071,61 @@ ${operationTypes.join("\n")}
41692
42071
  }
41693
42072
  return out;
41694
42073
  }
41695
- const nttZetas2 = getZettas();
41696
- const field = {
41697
- add: (a3, b2) => mod2((a3 | 0) + (b2 | 0)) | 0,
41698
- sub: (a3, b2) => mod2((a3 | 0) - (b2 | 0)) | 0,
41699
- mul: (a3, b2) => mod2((a3 | 0) * (b2 | 0)) | 0,
41700
- inv: (_a3) => {
41701
- throw new Error("not implemented");
41702
- }
42074
+ const nttZetas = getZettas();
42075
+ const inv = (_a3) => {
42076
+ throw new Error("not implemented");
41703
42077
  };
42078
+ const field = {
42079
+ add: (a3, b2) => {
42080
+ const r3 = a3 + b2 | 0;
42081
+ return r3 >= Q4 ? r3 - Q4 | 0 : r3;
42082
+ },
42083
+ sub: (a3, b2) => {
42084
+ const r3 = a3 - b2 | 0;
42085
+ return r3 < 0 ? r3 + Q4 | 0 : r3;
42086
+ },
42087
+ mul: (a3, b2) => mod((a3 | 0) * (b2 | 0)) | 0,
42088
+ inv
42089
+ } ;
41704
42090
  const nttOpts = {
41705
42091
  N: N3,
41706
- roots: nttZetas2,
42092
+ roots: nttZetas,
41707
42093
  invertButterflies: true,
41708
42094
  skipStages: 1 ,
41709
42095
  brp: false
41710
42096
  };
41711
42097
  const dif = FFTCore(field, { dit: false, ...nttOpts });
41712
42098
  const dit = FFTCore(field, { dit: true, ...nttOpts });
41713
- const NTT2 = {
42099
+ const NTT = {
41714
42100
  encode: (r3) => {
41715
42101
  return dif(r3);
41716
42102
  },
41717
42103
  decode: (r3) => {
41718
42104
  dit(r3);
41719
42105
  for (let i4 = 0; i4 < r3.length; i4++)
41720
- r3[i4] = mod2(F3 * r3[i4]);
42106
+ r3[i4] = mod(F3 * r3[i4]);
41721
42107
  return r3;
41722
42108
  }
41723
42109
  };
41724
- const bitsCoder2 = (d4, c3) => {
42110
+ const bitsCoder = (d4, c3) => {
42111
+ for (let i4 = 0, bufLen = 0; i4 < N3; i4++) {
42112
+ bufLen += d4;
42113
+ if (bufLen > 32)
42114
+ getMask(bufLen);
42115
+ bufLen %= 8;
42116
+ }
41725
42117
  const mask = getMask(d4);
41726
42118
  const bytesLen = d4 * (N3 / 8);
41727
42119
  return {
41728
42120
  bytesLen,
41729
- encode: (poly) => {
42121
+ encode: (poly_) => {
42122
+ const poly = poly_;
41730
42123
  const r3 = new Uint8Array(bytesLen);
41731
42124
  for (let i4 = 0, buf = 0, bufLen = 0, pos = 0; i4 < poly.length; i4++) {
41732
42125
  buf |= (c3.encode(poly[i4]) & mask) << bufLen;
41733
42126
  bufLen += d4;
41734
42127
  for (; bufLen >= 8; bufLen -= 8, buf >>= 8)
41735
- r3[pos++] = buf & getMask(bufLen);
42128
+ r3[pos++] = buf & 255;
41736
42129
  }
41737
42130
  return r3;
41738
42131
  },
@@ -41748,7 +42141,16 @@ ${operationTypes.join("\n")}
41748
42141
  }
41749
42142
  };
41750
42143
  };
41751
- return { mod: mod2, smod, nttZetas: nttZetas2, NTT: NTT2, bitsCoder: bitsCoder2 };
42144
+ return {
42145
+ mod,
42146
+ smod,
42147
+ nttZetas,
42148
+ NTT: {
42149
+ encode: (r3) => NTT.encode(r3),
42150
+ decode: (r3) => NTT.decode(r3)
42151
+ },
42152
+ bitsCoder
42153
+ };
41752
42154
  };
41753
42155
  var createXofShake = (shake) => (seed, blockLen) => {
41754
42156
  if (!blockLen)
@@ -41786,43 +42188,57 @@ ${operationTypes.join("\n")}
41786
42188
  var Q2 = 3329;
41787
42189
  var F2 = 3303;
41788
42190
  var ROOT_OF_UNITY = 17;
41789
- var { mod, nttZetas, NTT, bitsCoder } = genCrystals({
42191
+ var crystals = /* @__PURE__ */ genCrystals({
41790
42192
  N: N2,
41791
42193
  Q: Q2,
41792
42194
  F: F2,
41793
42195
  ROOT_OF_UNITY,
41794
42196
  newPoly: (n3) => new Uint16Array(n3),
41795
42197
  brvBits: 7});
41796
- var PARAMS = {
41797
- 768: { N: N2, Q: Q2, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }};
42198
+ var PARAMS = /* @__PURE__ */ (() => Object.freeze({
42199
+ 512: Object.freeze({ N: N2, Q: Q2, K: 2, ETA1: 3, ETA2: 2, du: 10, dv: 4, RBGstrength: 128 }),
42200
+ 768: Object.freeze({ N: N2, Q: Q2, K: 3, ETA1: 2, ETA2: 2, du: 10, dv: 4, RBGstrength: 192 }),
42201
+ 1024: Object.freeze({ N: N2, Q: Q2, K: 4, ETA1: 2, ETA2: 2, du: 11, dv: 5, RBGstrength: 256 })
42202
+ }))();
41798
42203
  var compress = (d4) => {
41799
42204
  if (d4 >= 12)
41800
- return { encode: (i4) => i4, decode: (i4) => i4 };
42205
+ return { encode: (i4) => i4, decode: (i4) => i4 >= Q2 ? i4 - Q2 : i4 };
41801
42206
  const a3 = 2 ** (d4 - 1);
41802
42207
  return {
41803
- // const compress = (i: number) => round((2 ** d / Q) * i) % 2 ** d;
42208
+ // This only matches standalone Compress_d after bitsCoder masks the result into Z_(2^d).
41804
42209
  encode: (i4) => ((i4 << d4) + Q2 / 2) / Q2,
41805
42210
  // const decompress = (i: number) => round((Q / 2 ** d) * i);
41806
42211
  decode: (i4) => i4 * Q2 + a3 >>> d4
41807
42212
  };
41808
42213
  };
41809
- var polyCoder = (d4) => bitsCoder(d4, compress(d4));
41810
- function polyAdd(a3, b2) {
41811
- for (let i4 = 0; i4 < N2; i4++)
41812
- a3[i4] = mod(a3[i4] + b2[i4]);
42214
+ var byteCoder = (d4) => crystals.bitsCoder(d4, { encode: (i4) => i4, decode: (i4) => i4 >= Q2 ? i4 - Q2 : i4 } );
42215
+ var polyCoder = (d4) => d4 === 12 ? byteCoder(12) : crystals.bitsCoder(d4, compress(d4));
42216
+ function polyAdd(a_, b_) {
42217
+ const a3 = a_;
42218
+ const b2 = b_;
42219
+ for (let i4 = 0; i4 < N2; i4++) {
42220
+ const r3 = a3[i4] + b2[i4];
42221
+ a3[i4] = r3 >= Q2 ? r3 - Q2 : r3;
42222
+ }
41813
42223
  }
41814
- function polySub(a3, b2) {
41815
- for (let i4 = 0; i4 < N2; i4++)
41816
- a3[i4] = mod(a3[i4] - b2[i4]);
42224
+ function polySub(a_, b_) {
42225
+ const a3 = a_;
42226
+ const b2 = b_;
42227
+ for (let i4 = 0; i4 < N2; i4++) {
42228
+ const r3 = a3[i4] - b2[i4];
42229
+ a3[i4] = r3 < 0 ? r3 + Q2 : r3;
42230
+ }
41817
42231
  }
41818
42232
  function BaseCaseMultiply(a0, a1, b0, b1, zeta) {
41819
- const c0 = mod(a1 * b1 * zeta + a0 * b0);
41820
- const c1 = mod(a0 * b1 + a1 * b0);
42233
+ const c0 = crystals.mod(crystals.mod(a1 * b1) * zeta + a0 * b0);
42234
+ const c1 = crystals.mod(a0 * b1 + a1 * b0);
41821
42235
  return { c0, c1 };
41822
42236
  }
41823
- function MultiplyNTTs(f3, g2) {
42237
+ function MultiplyNTTs(f_, g_) {
42238
+ const f3 = f_;
42239
+ const g2 = g_;
41824
42240
  for (let i4 = 0; i4 < N2 / 2; i4++) {
41825
- let z3 = nttZetas[64 + (i4 >> 1)];
42241
+ let z3 = crystals.nttZetas[64 + (i4 >> 1)];
41826
42242
  if (i4 & 1)
41827
42243
  z3 = -z3;
41828
42244
  const { c0, c1 } = BaseCaseMultiply(f3[2 * i4 + 0], f3[2 * i4 + 1], g2[2 * i4 + 0], g2[2 * i4 + 1], z3);
@@ -41831,7 +42247,8 @@ ${operationTypes.join("\n")}
41831
42247
  }
41832
42248
  return f3;
41833
42249
  }
41834
- function SampleNTT(xof) {
42250
+ function SampleNTT(xof_) {
42251
+ const xof = xof_;
41835
42252
  const r3 = new Uint16Array(N2);
41836
42253
  for (let j2 = 0; j2 < N2; ) {
41837
42254
  const b2 = xof();
@@ -41848,10 +42265,10 @@ ${operationTypes.join("\n")}
41848
42265
  }
41849
42266
  return r3;
41850
42267
  }
41851
- function sampleCBD(PRF, seed, nonce, eta) {
41852
- const buf = PRF(eta * N2 / 4, seed, nonce);
42268
+ var sampleCBDBytes = (buf, eta) => {
41853
42269
  const r3 = new Uint16Array(N2);
41854
42270
  const b32 = u32(buf);
42271
+ swap32IfBE(b32);
41855
42272
  let len = 0;
41856
42273
  for (let i4 = 0, p3 = 0, bb = 0, t0 = 0; i4 < b32.length; i4++) {
41857
42274
  let b2 = b32[i4];
@@ -41863,17 +42280,23 @@ ${operationTypes.join("\n")}
41863
42280
  t0 = bb;
41864
42281
  bb = 0;
41865
42282
  } else if (len === 2 * eta) {
41866
- r3[p3++] = mod(t0 - bb);
42283
+ r3[p3++] = crystals.mod(t0 - bb);
41867
42284
  bb = 0;
41868
42285
  len = 0;
41869
42286
  }
41870
42287
  }
41871
42288
  }
42289
+ swap32IfBE(b32);
41872
42290
  if (len)
41873
42291
  throw new Error(`sampleCBD: leftover bits: ${len}`);
41874
42292
  return r3;
42293
+ };
42294
+ function sampleCBD(PRF_, seed, nonce, eta) {
42295
+ const PRF = PRF_;
42296
+ return sampleCBDBytes(PRF(eta * N2 / 4, seed, nonce), eta);
41875
42297
  }
41876
- var genKPKE = (opts2) => {
42298
+ var genKPKE = (opts_) => {
42299
+ const opts2 = opts_;
41877
42300
  const { K: K2, PRF, XOF, HASH512, ETA1, ETA2, du, dv } = opts2;
41878
42301
  const poly1 = polyCoder(1);
41879
42302
  const polyV = polyCoder(dv);
@@ -41882,6 +42305,31 @@ ${operationTypes.join("\n")}
41882
42305
  const secretCoder = vecCoder(polyCoder(12), K2);
41883
42306
  const cipherCoder = splitCoder("ciphertext", vecCoder(polyU, K2), polyV);
41884
42307
  const seedCoder = splitCoder("seed", 32, 32);
42308
+ const encryptCore = (tHat, getA, msg, seed) => {
42309
+ const rHat = [];
42310
+ for (let i4 = 0; i4 < K2; i4++)
42311
+ rHat.push(crystals.NTT.encode(sampleCBD(PRF, seed, i4, ETA1)));
42312
+ const tmp2 = new Uint16Array(N2);
42313
+ const u4 = [];
42314
+ for (let i4 = 0; i4 < K2; i4++) {
42315
+ const e1 = sampleCBD(PRF, seed, K2 + i4, ETA2);
42316
+ const tmp = new Uint16Array(N2);
42317
+ for (let j2 = 0; j2 < K2; j2++) {
42318
+ const aij = getA(i4, j2);
42319
+ polyAdd(tmp, MultiplyNTTs(aij, rHat[j2]));
42320
+ }
42321
+ polyAdd(e1, crystals.NTT.decode(tmp));
42322
+ u4.push(e1);
42323
+ polyAdd(tmp2, MultiplyNTTs(tHat[i4], rHat[i4]));
42324
+ cleanBytes(tmp);
42325
+ }
42326
+ const e22 = sampleCBD(PRF, seed, 2 * K2, ETA2);
42327
+ polyAdd(e22, crystals.NTT.decode(tmp2));
42328
+ const v3 = poly1.decode(msg);
42329
+ polyAdd(v3, e22);
42330
+ cleanBytes(tHat, rHat, tmp2, e22);
42331
+ return cipherCoder.encode([u4, v3]);
42332
+ };
41885
42333
  return {
41886
42334
  secretCoder,
41887
42335
  lengths: {
@@ -41890,7 +42338,7 @@ ${operationTypes.join("\n")}
41890
42338
  cipherText: cipherCoder.bytesLen
41891
42339
  },
41892
42340
  keygen: (seed) => {
41893
- abytes(seed, 32, "seed");
42341
+ abytesDoc(seed, 32, "seed");
41894
42342
  const seedDst = new Uint8Array(33);
41895
42343
  seedDst.set(seed);
41896
42344
  seedDst[32] = K2;
@@ -41899,10 +42347,10 @@ ${operationTypes.join("\n")}
41899
42347
  const sHat = [];
41900
42348
  const tHat = [];
41901
42349
  for (let i4 = 0; i4 < K2; i4++)
41902
- sHat.push(NTT.encode(sampleCBD(PRF, sigma, i4, ETA1)));
42350
+ sHat.push(crystals.NTT.encode(sampleCBD(PRF, sigma, i4, ETA1)));
41903
42351
  const x2 = XOF(rho);
41904
42352
  for (let i4 = 0; i4 < K2; i4++) {
41905
- const e4 = NTT.encode(sampleCBD(PRF, sigma, K2 + i4, ETA1));
42353
+ const e4 = crystals.NTT.encode(sampleCBD(PRF, sigma, K2 + i4, ETA1));
41906
42354
  for (let j2 = 0; j2 < K2; j2++) {
41907
42355
  const aji = SampleNTT(x2.get(j2, i4));
41908
42356
  polyAdd(e4, MultiplyNTTs(aji, sHat[j2]));
@@ -41919,90 +42367,119 @@ ${operationTypes.join("\n")}
41919
42367
  },
41920
42368
  encrypt: (publicKey, msg, seed) => {
41921
42369
  const [tHat, rho] = publicCoder.decode(publicKey);
41922
- const rHat = [];
41923
- for (let i4 = 0; i4 < K2; i4++)
41924
- rHat.push(NTT.encode(sampleCBD(PRF, seed, i4, ETA1)));
41925
42370
  const x2 = XOF(rho);
41926
- const tmp2 = new Uint16Array(N2);
41927
- const u4 = [];
41928
- for (let i4 = 0; i4 < K2; i4++) {
41929
- const e1 = sampleCBD(PRF, seed, K2 + i4, ETA2);
41930
- const tmp = new Uint16Array(N2);
41931
- for (let j2 = 0; j2 < K2; j2++) {
41932
- const aij = SampleNTT(x2.get(i4, j2));
41933
- polyAdd(tmp, MultiplyNTTs(aij, rHat[j2]));
41934
- }
41935
- polyAdd(e1, NTT.decode(tmp));
41936
- u4.push(e1);
41937
- polyAdd(tmp2, MultiplyNTTs(tHat[i4], rHat[i4]));
41938
- cleanBytes(tmp);
41939
- }
42371
+ const res = encryptCore(tHat, (i4, j2) => SampleNTT(x2.get(i4, j2)), msg, seed);
42372
+ x2.clean();
42373
+ return res;
42374
+ },
42375
+ // Expands the full  matrix (public data derived from rho) once, so repeated encryptions
42376
+ // against the same ek skip the K² SampleNTT XOF expansions. Cached polys are copied per
42377
+ // call because encryptCore mutates its inputs in place.
42378
+ prepare: (publicKey) => {
42379
+ const [tHat, rho] = publicCoder.decode(publicKey);
42380
+ const x2 = XOF(rho);
42381
+ const A2 = [];
42382
+ for (let i4 = 0; i4 < K2; i4++)
42383
+ for (let j2 = 0; j2 < K2; j2++)
42384
+ A2.push(SampleNTT(x2.get(i4, j2)));
41940
42385
  x2.clean();
41941
- const e22 = sampleCBD(PRF, seed, 2 * K2, ETA2);
41942
- polyAdd(e22, NTT.decode(tmp2));
41943
- const v3 = poly1.decode(msg);
41944
- polyAdd(v3, e22);
41945
- cleanBytes(tHat, rHat, tmp2, e22);
41946
- return cipherCoder.encode([u4, v3]);
42386
+ return {
42387
+ encrypt: (msg, seed) => encryptCore(tHat.map((p3) => p3.slice()), (i4, j2) => A2[i4 * K2 + j2].slice(), msg, seed),
42388
+ clean: () => cleanBytes(tHat, A2)
42389
+ };
41947
42390
  },
41948
42391
  decrypt: (cipherText, privateKey) => {
41949
42392
  const [u4, v3] = cipherCoder.decode(cipherText);
41950
42393
  const sk = secretCoder.decode(privateKey);
41951
42394
  const tmp = new Uint16Array(N2);
41952
42395
  for (let i4 = 0; i4 < K2; i4++)
41953
- polyAdd(tmp, MultiplyNTTs(sk[i4], NTT.encode(u4[i4])));
41954
- polySub(v3, NTT.decode(tmp));
41955
- cleanBytes(tmp, sk, u4);
41956
- return poly1.encode(v3);
42396
+ polyAdd(tmp, MultiplyNTTs(sk[i4], crystals.NTT.encode(u4[i4])));
42397
+ polySub(v3, crystals.NTT.decode(tmp));
42398
+ const res = poly1.encode(v3);
42399
+ cleanBytes(tmp, sk, u4, v3);
42400
+ return res;
41957
42401
  }
41958
42402
  };
41959
42403
  };
41960
42404
  function createKyber(opts2) {
41961
- const KPKE = genKPKE(opts2);
41962
- const { HASH256, HASH512, KDF } = opts2;
42405
+ const rawOpts = opts2;
42406
+ const KPKE = genKPKE(rawOpts);
42407
+ const { HASH256, HASH512, KDF } = rawOpts;
41963
42408
  const { secretCoder: KPKESecretCoder, lengths } = KPKE;
41964
42409
  const secretCoder = splitCoder("secretKey", lengths.secretKey, lengths.publicKey, 32, 32);
41965
42410
  const msgLen = 32;
41966
42411
  const seedLen = 64;
41967
- return {
41968
- info: { type: "ml-kem" },
41969
- lengths: {
41970
- ...lengths,
41971
- seed: 64,
41972
- msg: msgLen,
41973
- msgRand: msgLen,
41974
- secretKey: secretCoder.bytesLen
41975
- },
41976
- keygen: (seed = randomBytes2(seedLen)) => {
41977
- abytes(seed, seedLen, "seed");
41978
- const { publicKey, secretKey: sk } = KPKE.keygen(seed.subarray(0, 32));
41979
- const publicKeyHash = HASH256(publicKey);
41980
- const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, seed.subarray(32)]);
41981
- cleanBytes(sk, publicKeyHash);
41982
- return { publicKey, secretKey };
42412
+ const validateModulus = (publicKey, fn) => {
42413
+ const eke = publicKey.subarray(0, 384 * rawOpts.K);
42414
+ const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));
42415
+ const ok = equalBytes(ek, eke);
42416
+ cleanBytes(ek);
42417
+ if (!ok)
42418
+ throw new Error(`ML-KEM.${fn}: wrong publicKey modulus`);
42419
+ };
42420
+ const kemLengths = Object.freeze({
42421
+ ...lengths,
42422
+ seed: 64,
42423
+ msg: msgLen,
42424
+ msgRand: msgLen,
42425
+ secretKey: secretCoder.bytesLen
42426
+ });
42427
+ return Object.freeze({
42428
+ info: Object.freeze({ type: "ml-kem" }),
42429
+ lengths: kemLengths,
42430
+ keygen: (seed) => {
42431
+ const ownSeed = seed === void 0;
42432
+ const s2 = ownSeed ? randomBytes2(seedLen) : seed;
42433
+ let sk;
42434
+ let publicKeyHash;
42435
+ try {
42436
+ abytesDoc(s2, seedLen, "seed");
42437
+ const keys = KPKE.keygen(s2.subarray(0, 32));
42438
+ const publicKey = keys.publicKey;
42439
+ sk = keys.secretKey;
42440
+ publicKeyHash = HASH256(publicKey);
42441
+ const secretKey = secretCoder.encode([sk, publicKey, publicKeyHash, s2.subarray(32)]);
42442
+ return {
42443
+ publicKey,
42444
+ secretKey
42445
+ };
42446
+ } finally {
42447
+ if (sk !== void 0)
42448
+ cleanBytes(sk);
42449
+ if (publicKeyHash !== void 0)
42450
+ cleanBytes(publicKeyHash);
42451
+ if (ownSeed)
42452
+ cleanBytes(s2);
42453
+ }
41983
42454
  },
41984
42455
  getPublicKey: (secretKey) => {
41985
42456
  const [_sk, publicKey, _publicKeyHash, _z] = secretCoder.decode(secretKey);
41986
42457
  return Uint8Array.from(publicKey);
41987
42458
  },
41988
- encapsulate: (publicKey, msg = randomBytes2(msgLen)) => {
41989
- abytes(publicKey, lengths.publicKey, "publicKey");
41990
- abytes(msg, msgLen, "message");
41991
- const eke = publicKey.subarray(0, 384 * opts2.K);
41992
- const ek = KPKESecretCoder.encode(KPKESecretCoder.decode(copyBytes(eke)));
41993
- if (!equalBytes(ek, eke)) {
41994
- cleanBytes(ek);
41995
- throw new Error("ML-KEM.encapsulate: wrong publicKey modulus");
41996
- }
41997
- cleanBytes(ek);
41998
- const kr = HASH512.create().update(msg).update(HASH256(publicKey)).digest();
41999
- const cipherText = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
42000
- cleanBytes(kr.subarray(32));
42001
- return { cipherText, sharedSecret: kr.subarray(0, 32) };
42459
+ encapsulate: (publicKey, msg) => {
42460
+ const ownMsg = msg === void 0;
42461
+ const m2 = ownMsg ? randomBytes2(msgLen) : msg;
42462
+ let kr;
42463
+ try {
42464
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
42465
+ abytesDoc(m2, msgLen, "message");
42466
+ validateModulus(publicKey, "encapsulate");
42467
+ kr = HASH512.create().update(m2).update(HASH256(publicKey)).digest();
42468
+ const cipherText = KPKE.encrypt(publicKey, m2, kr.subarray(32, 64));
42469
+ return {
42470
+ cipherText,
42471
+ sharedSecret: kr.subarray(0, 32)
42472
+ };
42473
+ } finally {
42474
+ if (kr !== void 0)
42475
+ cleanBytes(kr.subarray(32));
42476
+ if (ownMsg)
42477
+ cleanBytes(m2);
42478
+ }
42002
42479
  },
42003
42480
  decapsulate: (cipherText, secretKey) => {
42004
- abytes(secretKey, secretCoder.bytesLen, "secretKey");
42005
- abytes(cipherText, lengths.cipherText, "cipherText");
42481
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
42482
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
42006
42483
  const k768 = secretCoder.bytesLen - 96;
42007
42484
  const start2 = k768 + 32;
42008
42485
  const test = HASH256(secretKey.subarray(k768 / 2, start2));
@@ -42015,25 +42492,76 @@ ${operationTypes.join("\n")}
42015
42492
  const cipherText2 = KPKE.encrypt(publicKey, msg, kr.subarray(32, 64));
42016
42493
  const isValid = equalBytes(cipherText, cipherText2);
42017
42494
  const Kbar = KDF.create({ dkLen: 32 }).update(z3).update(cipherText).digest();
42018
- cleanBytes(msg, cipherText2, !isValid ? Khat : Kbar);
42495
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
42019
42496
  return isValid ? Khat : Kbar;
42497
+ },
42498
+ /**
42499
+ * Experimental prototype: pre-expand a public key so repeated encapsulate/decapsulate
42500
+ * against the same key skip re-validation, H(ek), t̂ decoding and the K² SampleNTT
42501
+ * XOF expansions of Â. Only public data is cached; see {@link KEMPrepared}.
42502
+ */
42503
+ prepare: (publicKey) => {
42504
+ abytesDoc(publicKey, lengths.publicKey, "publicKey");
42505
+ validateModulus(publicKey, "prepare");
42506
+ const ek = copyBytes(publicKey);
42507
+ const publicKeyHash = HASH256(ek);
42508
+ const cached2 = KPKE.prepare(ek);
42509
+ return Object.freeze({
42510
+ publicKey: ek,
42511
+ encapsulate: (msg) => {
42512
+ const ownMsg = msg === void 0;
42513
+ const m2 = ownMsg ? randomBytes2(msgLen) : msg;
42514
+ let kr;
42515
+ try {
42516
+ abytesDoc(m2, msgLen, "message");
42517
+ kr = HASH512.create().update(m2).update(publicKeyHash).digest();
42518
+ const cipherText = cached2.encrypt(m2, kr.subarray(32, 64));
42519
+ return {
42520
+ cipherText,
42521
+ sharedSecret: kr.subarray(0, 32)
42522
+ };
42523
+ } finally {
42524
+ if (kr !== void 0)
42525
+ cleanBytes(kr.subarray(32));
42526
+ if (ownMsg)
42527
+ cleanBytes(m2);
42528
+ }
42529
+ },
42530
+ decapsulate: (cipherText, secretKey) => {
42531
+ abytesDoc(secretKey, secretCoder.bytesLen, "secretKey");
42532
+ abytesDoc(cipherText, lengths.cipherText, "cipherText");
42533
+ const [sk, ekEmbedded, storedHash, z3] = secretCoder.decode(secretKey);
42534
+ if (!equalBytes(ekEmbedded, ek) || !equalBytes(storedHash, publicKeyHash))
42535
+ throw new Error("ML-KEM.decapsulate: secretKey does not match prepared publicKey");
42536
+ const msg = KPKE.decrypt(cipherText, sk);
42537
+ const kr = HASH512.create().update(msg).update(publicKeyHash).digest();
42538
+ const Khat = kr.subarray(0, 32);
42539
+ const cipherText2 = cached2.encrypt(msg, kr.subarray(32, 64));
42540
+ const isValid = equalBytes(cipherText, cipherText2);
42541
+ const Kbar = KDF.create({ dkLen: 32 }).update(z3).update(cipherText).digest();
42542
+ cleanBytes(msg, cipherText2, kr.subarray(32), !isValid ? Khat : Kbar);
42543
+ return isValid ? Khat : Kbar;
42544
+ },
42545
+ clean: cached2.clean
42546
+ });
42020
42547
  }
42021
- };
42548
+ });
42022
42549
  }
42023
42550
  function shakePRF(dkLen, key, nonce) {
42024
42551
  return shake2562.create({ dkLen }).update(key).update(new Uint8Array([nonce])).digest();
42025
42552
  }
42026
- var opts = {
42553
+ var opts = /* @__PURE__ */ (() => ({
42027
42554
  HASH256: sha3_256,
42028
42555
  HASH512: sha3_512,
42029
42556
  KDF: shake2562,
42030
42557
  XOF: XOF128,
42031
42558
  PRF: shakePRF
42032
- };
42033
- var ml_kem768 = /* @__PURE__ */ createKyber({
42559
+ }))();
42560
+ var mk = (params) => createKyber({
42034
42561
  ...opts,
42035
- ...PARAMS[768]
42562
+ ...params
42036
42563
  });
42564
+ var ml_kem768 = /* @__PURE__ */ (() => mk(PARAMS[768]))();
42037
42565
 
42038
42566
  // src/core/Wallet.ts
42039
42567
  var Wallet = class _Wallet {
@@ -42176,11 +42704,13 @@ ${operationTypes.join("\n")}
42176
42704
  return typeof maybeBundleHash === "string" && isBundleHash(maybeBundleHash);
42177
42705
  }
42178
42706
  /**
42179
- * Get formatted token units from raw data
42180
- * Stub implementation for now
42707
+ * Map raw token-unit tuples to TokenUnit instances.
42708
+ * Matches JS SDK Wallet.getTokenUnits (Wallet.js:190-196). The serialised shape reaches hashed
42709
+ * atom meta via AtomMeta.setAtomWallet -> JSON.stringify(getTokenUnitsData()), so returning raw
42710
+ * tuples here would diverge from every other SDK.
42181
42711
  */
42182
42712
  static getTokenUnits(unitsData) {
42183
- return unitsData;
42713
+ return unitsData.map((unitData) => TokenUnit.createFromDB(unitData));
42184
42714
  }
42185
42715
  /**
42186
42716
  * Create a remainder wallet for transactions
@@ -42480,7 +43010,7 @@ ${operationTypes.join("\n")}
42480
43010
  var TokenSlugSchema = external_exports.string().min(1, "Token slug cannot be empty").max(64, "Token slug cannot exceed 64 characters").transform((val) => val.toUpperCase()).brand();
42481
43011
  var MetaTypeSchema = external_exports.string().min(1, "Meta type cannot be empty").max(256, "Meta type cannot exceed 256 characters").brand();
42482
43012
  var MetaIdSchema = external_exports.string().min(1, "Meta ID cannot be empty").brand();
42483
- var BatchIdSchema = external_exports.string().min(1, "Batch ID cannot be empty").brand();
43013
+ var BatchIdSchema = external_exports.string().regex(/^[0-9a-fA-F]{64}$/, "Batch ID must be 64 hexadecimal characters").brand();
42484
43014
  var CellSlugSchema = external_exports.string().min(1, "Cell slug cannot be empty").max(64, "Cell slug cannot exceed 64 characters").brand();
42485
43015
  var AtomIsotopeSchema = external_exports.enum(["C", "V", "U", "T", "M", "I", "R", "B", "F"], {
42486
43016
  error: "Invalid atom isotope. Must be one of: C, V, U, T, M, I, R, B, F"
@@ -42541,7 +43071,8 @@ ${operationTypes.join("\n")}
42541
43071
  socket: external_exports.unknown().optional(),
42542
43072
  serverSdkVersion: external_exports.number().int().min(1).optional(),
42543
43073
  logging: external_exports.boolean().optional(),
42544
- defaultRequestPolicy: external_exports.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional()
43074
+ defaultRequestPolicy: external_exports.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional(),
43075
+ secretStorage: external_exports.unknown().optional()
42545
43076
  }).strict();
42546
43077
  external_exports.object({
42547
43078
  token: external_exports.string().min(1, "Auth token cannot be empty"),
@@ -42804,58 +43335,6 @@ ${operationTypes.join("\n")}
42804
43335
  };
42805
43336
  var RuleArgumentException_default = RuleArgumentException;
42806
43337
 
42807
- // src/libraries/array.ts
42808
- function deepCloning(o3, h3) {
42809
- let i4;
42810
- let r3;
42811
- let x2;
42812
- const t3 = [Array, Date, Number, String, Boolean];
42813
- const s2 = Object.prototype.toString;
42814
- h3 = h3 || [];
42815
- for (i4 = 0; i4 < h3.length; i4 += 2) {
42816
- if (o3 === h3[i4]) {
42817
- return h3[i4 + 1];
42818
- }
42819
- }
42820
- if (!r3 && o3 && typeof o3 === "object") {
42821
- r3 = {};
42822
- for (i4 = 0; i4 < t3.length; i4++) {
42823
- if (s2.call(o3) === s2.call(x2 = new t3[i4](o3))) {
42824
- r3 = i4 ? x2 : [];
42825
- }
42826
- }
42827
- h3.push(o3, r3);
42828
- for (i4 in o3) {
42829
- if (Object.prototype.hasOwnProperty.call(o3, i4)) {
42830
- r3[i4] = deepCloning(o3[i4], h3);
42831
- }
42832
- }
42833
- }
42834
- return r3 || o3;
42835
- }
42836
- function chunkArray(arr, size) {
42837
- const chunks = [];
42838
- for (let i4 = 0; i4 < arr.length; i4 += size) {
42839
- chunks.push(arr.slice(i4, i4 + size));
42840
- }
42841
- return chunks;
42842
- }
42843
- function diff(...arrays) {
42844
- return [].concat(...arrays.map((arr, i4) => {
42845
- const others = arrays.slice(0);
42846
- others.splice(i4, 1);
42847
- const unique = [...new Set([].concat(...others))];
42848
- return arr.filter((item) => !unique.includes(item));
42849
- }));
42850
- }
42851
- function intersect(...arrays) {
42852
- if (arrays.length === 0) return [];
42853
- if (arrays.length === 1) return arrays[0];
42854
- return arrays.reduce(
42855
- (first, second) => first.filter((item) => second.includes(item))
42856
- );
42857
- }
42858
-
42859
43338
  // src/instance/rules/Callback.ts
42860
43339
  init_exception();
42861
43340
  init_zod();
@@ -44187,6 +44666,51 @@ ${operationTypes.join("\n")}
44187
44666
  }));
44188
44667
  return this;
44189
44668
  }
44669
+ /**
44670
+ * Replenishes non-finite token supplies.
44671
+ * Matches JS SDK Molecule.replenishToken (Molecule.js:521-566) exactly.
44672
+ *
44673
+ * Two orderings here are load-bearing for the molecular hash and must not be reordered:
44674
+ * the remainder balance is computed BEFORE the source balance is overwritten, and the
44675
+ * source V-atom is added BEFORE the remainder V-atom.
44676
+ */
44677
+ replenishToken({
44678
+ amount,
44679
+ units = []
44680
+ }) {
44681
+ if (amount < 0) {
44682
+ throw new NegativeAmountException("Molecule::replenishToken() - Amount to replenish must be positive!");
44683
+ }
44684
+ if (!this.sourceWallet || !this.remainderWallet) {
44685
+ throw new Error("Source and remainder wallets required for token replenishment");
44686
+ }
44687
+ if (units.length) {
44688
+ const formatted = Wallet.getTokenUnits(units);
44689
+ this.remainderWallet.tokenUnits = this.sourceWallet.tokenUnits;
44690
+ for (const unit of formatted) {
44691
+ this.remainderWallet.tokenUnits.push(unit);
44692
+ }
44693
+ this.remainderWallet.balance = String(this.remainderWallet.tokenUnits.length);
44694
+ this.sourceWallet.tokenUnits = formatted;
44695
+ this.sourceWallet.balance = String(this.sourceWallet.tokenUnits.length);
44696
+ } else {
44697
+ this.remainderWallet.balance = String(Number(this.sourceWallet.balance) + amount);
44698
+ this.sourceWallet.balance = String(amount);
44699
+ }
44700
+ this.addAtom(Atom.create({
44701
+ isotope: "V",
44702
+ wallet: this.sourceWallet,
44703
+ value: Number(this.sourceWallet.balance)
44704
+ }));
44705
+ this.addAtom(Atom.create({
44706
+ isotope: "V",
44707
+ wallet: this.remainderWallet,
44708
+ value: Number(this.remainderWallet.balance),
44709
+ metaType: "walletBundle",
44710
+ metaId: this.remainderWallet.bundle
44711
+ }));
44712
+ return this;
44713
+ }
44190
44714
  /**
44191
44715
  * Initialize authorization request
44192
44716
  * Creates U-isotope (authorization) atom for requesting auth token
@@ -46130,21 +46654,22 @@ ${operationTypes.join("\n")}
46130
46654
  }
46131
46655
  };
46132
46656
  var makeResult = (e4, r3, t3) => {
46133
- if (!("data" in r3 || "errors" in r3 && Array.isArray(r3.errors))) {
46657
+ var a3 = r3.payload || r3;
46658
+ if (!("data" in a3 || "errors" in a3 && Array.isArray(a3.errors))) {
46134
46659
  throw new Error("No Content");
46135
46660
  }
46136
- var a3 = "subscription" === e4.kind;
46661
+ var n3 = "subscription" === e4.kind;
46137
46662
  return {
46138
46663
  operation: e4,
46139
- data: r3.data,
46140
- error: Array.isArray(r3.errors) ? new CombinedError({
46141
- graphQLErrors: r3.errors,
46664
+ data: a3.data,
46665
+ error: Array.isArray(a3.errors) ? new CombinedError({
46666
+ graphQLErrors: a3.errors,
46142
46667
  response: t3
46143
46668
  }) : void 0,
46144
- extensions: r3.extensions ? {
46145
- ...r3.extensions
46669
+ extensions: a3.extensions ? {
46670
+ ...a3.extensions
46146
46671
  } : void 0,
46147
- hasNext: null == r3.hasNext ? a3 : r3.hasNext,
46672
+ hasNext: null == r3.hasNext ? n3 : r3.hasNext,
46148
46673
  stale: false
46149
46674
  };
46150
46675
  };
@@ -46537,14 +47062,14 @@ ${operationTypes.join("\n")}
46537
47062
  var o3 = [];
46538
47063
  var s2 = {};
46539
47064
  for (var c3 = 0, u4 = r3.directives.length; c3 < u4; c3++) {
46540
- var p3 = r3.directives[c3];
46541
- var d4 = p3.name.value;
46542
- if ("_" !== d4[0]) {
46543
- o3.push(p3);
47065
+ var d4 = r3.directives[c3];
47066
+ var p3 = d4.name.value;
47067
+ if ("_" !== p3[0]) {
47068
+ o3.push(d4);
46544
47069
  } else {
46545
- d4 = d4.slice(1);
47070
+ p3 = p3.slice(1);
46546
47071
  }
46547
- s2[d4] = p3;
47072
+ s2[p3] = d4;
46548
47073
  }
46549
47074
  r3 = {
46550
47075
  ...r3,
@@ -46553,17 +47078,17 @@ ${operationTypes.join("\n")}
46553
47078
  };
46554
47079
  }
46555
47080
  if ("selectionSet" in r3) {
46556
- var v3 = [];
46557
- var l3 = r3.kind === e2.OPERATION_DEFINITION;
47081
+ var l3 = [];
47082
+ var v3 = r3.kind === e2.OPERATION_DEFINITION;
46558
47083
  if (r3.selectionSet) {
46559
47084
  for (var f3 = 0, h3 = r3.selectionSet.selections.length; f3 < h3; f3++) {
46560
47085
  var k2 = r3.selectionSet.selections[f3];
46561
- l3 = l3 || k2.kind === e2.FIELD && "__typename" === k2.name.value && !k2.alias;
47086
+ v3 = v3 || k2.kind === e2.FIELD && "__typename" === k2.name.value && !k2.alias;
46562
47087
  var y3 = formatNode(k2);
46563
- v3.push(y3);
47088
+ l3.push(y3);
46564
47089
  }
46565
- if (!l3) {
46566
- v3.push({
47090
+ if (!v3) {
47091
+ l3.push({
46567
47092
  kind: e2.FIELD,
46568
47093
  name: {
46569
47094
  kind: e2.NAME,
@@ -46576,7 +47101,7 @@ ${operationTypes.join("\n")}
46576
47101
  ...r3,
46577
47102
  selectionSet: {
46578
47103
  ...r3.selectionSet,
46579
- selections: v3
47104
+ selections: l3
46580
47105
  }
46581
47106
  };
46582
47107
  }
@@ -46636,20 +47161,20 @@ ${operationTypes.join("\n")}
46636
47161
  s2 += arguments[0][c3];
46637
47162
  }
46638
47163
  o3.unshift(keyDocument(s2));
46639
- for (var p3 = 0; p3 < o3.length; p3++) {
46640
- for (var d4 = 0; d4 < o3[p3].definitions.length; d4++) {
46641
- var v3 = o3[p3].definitions[d4];
46642
- if (v3.kind === e2.FRAGMENT_DEFINITION) {
46643
- var l3 = v3.name.value;
46644
- var f3 = stringifyDocument(v3);
46645
- if (!a3.has(l3)) {
46646
- a3.set(l3, f3);
46647
- i4.push(v3);
46648
- } else if (a3.get(l3) !== f3) {
46649
- console.warn("[WARNING: Duplicate Fragment] A fragment with name `" + l3 + "` already exists in this document.\nWhile fragment names may not be unique across your source, each name must be unique per document.");
47164
+ for (var d4 = 0; d4 < o3.length; d4++) {
47165
+ for (var p3 = 0; p3 < o3[d4].definitions.length; p3++) {
47166
+ var l3 = o3[d4].definitions[p3];
47167
+ if (l3.kind === e2.FRAGMENT_DEFINITION) {
47168
+ var v3 = l3.name.value;
47169
+ var f3 = stringifyDocument(l3);
47170
+ if (!a3.has(v3)) {
47171
+ a3.set(v3, f3);
47172
+ i4.push(l3);
47173
+ } else if (a3.get(v3) !== f3) {
47174
+ console.warn("[WARNING: Duplicate Fragment] A fragment with name `" + v3 + "` already exists in this document.\nWhile fragment names may not be unique across your source, each name must be unique per document.");
46650
47175
  }
46651
47176
  } else {
46652
- i4.push(v3);
47177
+ i4.push(l3);
46653
47178
  }
46654
47179
  }
46655
47180
  }
@@ -46725,26 +47250,26 @@ ${operationTypes.join("\n")}
46725
47250
  });
46726
47251
  for (var c4 = 0; c4 < o4.length; c4++) {
46727
47252
  var u4 = o4[c4];
46728
- var p3 = i4.get(u4);
46729
- if (!p3) {
46730
- i4.set(u4, p3 = /* @__PURE__ */ new Set());
47253
+ var d4 = i4.get(u4);
47254
+ if (!d4) {
47255
+ i4.set(u4, d4 = /* @__PURE__ */ new Set());
46731
47256
  }
46732
- for (var d4 of p3.values()) {
46733
- s3.add(d4);
47257
+ for (var p3 of d4.values()) {
47258
+ s3.add(p3);
46734
47259
  }
46735
- p3.clear();
47260
+ d4.clear();
46736
47261
  }
46737
- for (var v3 of s3.values()) {
46738
- if (a3.has(v3)) {
46739
- n3 = a3.get(v3).operation;
46740
- a3.delete(v3);
47262
+ for (var l3 of s3.values()) {
47263
+ if (a3.has(l3)) {
47264
+ n3 = a3.get(l3).operation;
47265
+ a3.delete(l3);
46741
47266
  reexecuteOperation(r3, n3);
46742
47267
  }
46743
47268
  }
46744
47269
  } else if ("query" === n3.kind && e5.data) {
46745
47270
  a3.set(n3.key, e5);
46746
- for (var l3 = 0; l3 < o4.length; l3++) {
46747
- var f3 = o4[l3];
47271
+ for (var v3 = 0; v3 < o4.length; v3++) {
47272
+ var f3 = o4[v3];
46748
47273
  var h3 = i4.get(f3);
46749
47274
  if (!h3) {
46750
47275
  i4.set(f3, h3 = /* @__PURE__ */ new Set());
@@ -46795,13 +47320,12 @@ ${operationTypes.join("\n")}
46795
47320
  complete() {
46796
47321
  if (!i6) {
46797
47322
  i6 = true;
46798
- if ("subscription" === r5.kind) {
46799
- a3.reexecuteOperation(makeOperation("teardown", r5, r5.context));
46800
- }
46801
47323
  if (u6 && u6.hasNext) {
46802
47324
  nextResult({
46803
47325
  hasNext: false
46804
47326
  });
47327
+ } else if ("subscription" === r5.kind) {
47328
+ a3.reexecuteOperation(makeOperation("teardown", r5, r5.context));
46805
47329
  }
46806
47330
  e5.complete();
46807
47331
  }
@@ -46817,8 +47341,8 @@ ${operationTypes.join("\n")}
46817
47341
  }));
46818
47342
  })(t5));
46819
47343
  }))(filter(((e5) => "teardown" !== e5.kind && u4(e5)))(r4));
46820
- var p3 = i4(filter(((e5) => "teardown" === e5.kind || !u4(e5)))(r4));
46821
- return merge2([t4, p3]);
47344
+ var d4 = i4(filter(((e5) => "teardown" === e5.kind || !u4(e5)))(r4));
47345
+ return merge2([t4, d4]);
46822
47346
  };
46823
47347
  };
46824
47348
  var fetchExchange = ({ forward: e4, dispatchDebug: r3 }) => (t3) => {
@@ -46910,7 +47434,7 @@ ${operationTypes.join("\n")}
46910
47434
  fetchSubscriptions: e4.fetchSubscriptions,
46911
47435
  fetchOptions: e4.fetchOptions,
46912
47436
  fetch: e4.fetch,
46913
- preferGetMethod: e4.preferGetMethod,
47437
+ preferGetMethod: null != e4.preferGetMethod ? e4.preferGetMethod : "within-url-limit",
46914
47438
  requestPolicy: e4.requestPolicy || "cache-first"
46915
47439
  };
46916
47440
  var s2 = makeSubject();
@@ -46988,7 +47512,7 @@ ${operationTypes.join("\n")}
46988
47512
  return share(r4);
46989
47513
  };
46990
47514
  var u4 = this instanceof Client ? this : Object.create(Client.prototype);
46991
- var p3 = Object.assign(u4, {
47515
+ var d4 = Object.assign(u4, {
46992
47516
  suspense: !!e4.suspense,
46993
47517
  operations$: s2.source,
46994
47518
  reexecuteOperation(e5) {
@@ -47027,7 +47551,7 @@ ${operationTypes.join("\n")}
47027
47551
  ...o3,
47028
47552
  ...n4,
47029
47553
  requestPolicy: n4.requestPolicy || o3.requestPolicy,
47030
- suspense: n4.suspense || false !== n4.suspense && p3.suspense
47554
+ suspense: n4.suspense || false !== n4.suspense && d4.suspense
47031
47555
  });
47032
47556
  },
47033
47557
  executeRequestOperation(e5) {
@@ -47051,44 +47575,44 @@ ${operationTypes.join("\n")}
47051
47575
  })));
47052
47576
  },
47053
47577
  executeQuery(e5, r4) {
47054
- var t4 = p3.createRequestOperation("query", e5, r4);
47055
- return p3.executeRequestOperation(t4);
47578
+ var t4 = d4.createRequestOperation("query", e5, r4);
47579
+ return d4.executeRequestOperation(t4);
47056
47580
  },
47057
47581
  executeSubscription(e5, r4) {
47058
- var t4 = p3.createRequestOperation("subscription", e5, r4);
47059
- return p3.executeRequestOperation(t4);
47582
+ var t4 = d4.createRequestOperation("subscription", e5, r4);
47583
+ return d4.executeRequestOperation(t4);
47060
47584
  },
47061
47585
  executeMutation(e5, r4) {
47062
- var t4 = p3.createRequestOperation("mutation", e5, r4);
47063
- return p3.executeRequestOperation(t4);
47586
+ var t4 = d4.createRequestOperation("mutation", e5, r4);
47587
+ return d4.executeRequestOperation(t4);
47064
47588
  },
47065
47589
  readQuery(e5, r4, t4) {
47066
47590
  var n4 = null;
47067
47591
  subscribe(((e6) => {
47068
47592
  n4 = e6;
47069
- }))(p3.query(e5, r4, t4)).unsubscribe();
47593
+ }))(d4.query(e5, r4, t4)).unsubscribe();
47070
47594
  return n4;
47071
47595
  },
47072
- query: (e5, r4, t4) => p3.executeQuery(createRequest(e5, r4), t4),
47073
- subscription: (e5, r4, t4) => p3.executeSubscription(createRequest(e5, r4), t4),
47074
- mutation: (e5, r4, t4) => p3.executeMutation(createRequest(e5, r4), t4)
47596
+ query: (e5, r4, t4) => d4.executeQuery(createRequest(e5, r4), t4),
47597
+ subscription: (e5, r4, t4) => d4.executeSubscription(createRequest(e5, r4), t4),
47598
+ mutation: (e5, r4, t4) => d4.executeMutation(createRequest(e5, r4), t4)
47075
47599
  });
47076
- var d4 = noop;
47600
+ var p3 = noop;
47077
47601
  {
47078
47602
  var { next: f3, source: x2 } = makeSubject();
47079
- p3.subscribeToDebugTarget = (e5) => subscribe(e5)(x2);
47080
- d4 = f3;
47603
+ d4.subscribeToDebugTarget = (e5) => subscribe(e5)(x2);
47604
+ p3 = f3;
47081
47605
  }
47082
47606
  var w2 = composeExchanges(e4.exchanges);
47083
47607
  var E2 = share(w2({
47084
- client: p3,
47085
- dispatchDebug: d4,
47608
+ client: d4,
47609
+ dispatchDebug: p3,
47086
47610
  forward: fallbackExchange({
47087
- dispatchDebug: d4
47611
+ dispatchDebug: p3
47088
47612
  })
47089
47613
  })(s2.source));
47090
47614
  publish(E2);
47091
- return p3;
47615
+ return d4;
47092
47616
  };
47093
47617
  var Q3 = C2;
47094
47618
 
@@ -47147,16 +47671,27 @@ ${operationTypes.join("\n")}
47147
47671
  return Q3({
47148
47672
  url: serverUri,
47149
47673
  exchanges,
47150
- // PQ-transport Phase E: when encryption is on, route fetch through the CipherHash wrapper
47151
- // (encrypt the request body to the validator's ML-KEM pubkey, decrypt the response).
47152
- // Omitted → urql uses the global fetch (plaintext).
47153
- ...this.cipherLink ? { fetch: ((input2, init) => this.cipherFetch(input2, init)) } : {},
47674
+ // urql 5 had no default and always POSTed; urql 6 defaults to 'within-url-limit', which
47675
+ // URL-encodes short queries and sends NO body. That would silently disable the CipherHash
47676
+ // envelope below — cipherFetch's `typeof init.body === 'string'` guard fails on a GET, so
47677
+ // the query would leave as plaintext URL parameters with no error. Pin POST explicitly.
47678
+ preferGetMethod: false,
47679
+ // Always route through our own fetch. Two reasons: (1) PQ-transport Phase E — when
47680
+ // encryption is on, cipherFetch wraps the request body in the CipherHash envelope and
47681
+ // decrypts the response; (2) the 60s timeout. urql's makeFetchSource unconditionally
47682
+ // overwrites init.signal with its own AbortController, so a signal returned from
47683
+ // fetchOptions() is discarded and never fired. Combining it here is the only place it
47684
+ // survives.
47685
+ fetch: ((input2, init) => {
47686
+ const timeoutSignal = AbortSignal.timeout(6e4);
47687
+ const signal = init?.signal && typeof AbortSignal.any === "function" ? AbortSignal.any([init.signal, timeoutSignal]) : init?.signal ?? timeoutSignal;
47688
+ const timedInit = { ...init, signal };
47689
+ return this.cipherLink ? this.cipherFetch(input2, timedInit) : fetch(input2, timedInit);
47690
+ }),
47154
47691
  fetchOptions: () => ({
47155
47692
  headers: {
47156
47693
  "X-Auth-Token": this.$__authToken
47157
- },
47158
- // Add 60 second timeout
47159
- signal: AbortSignal.timeout(6e4)
47694
+ }
47160
47695
  })
47161
47696
  });
47162
47697
  }
@@ -47672,12 +48207,12 @@ ${operationTypes.join("\n")}
47672
48207
  );
47673
48208
  var BatchIdSchema2 = createBrandedSchema(
47674
48209
  "BatchId",
47675
- // v3's `.uuid()` regex, inlined verbatim. Zod 4's `z.uuid()` additionally enforces the
47676
- // RFC 9562 version/variant nibbles and would reject batch IDs v3 accepted.
47677
- external_exports.string().regex(
47678
- /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/,
47679
- "Invalid batch ID format"
47680
- )
48210
+ // 64 hex characters. generateBatchId (src/libraries/crypto.ts) returns either
48211
+ // shake256(molecularHash + index, 256) — 256 bits, 64 hex chars — or randomString(64) over the
48212
+ // alphabet 'abcdef0123456789'. A UUID shape matches nothing this SDK can produce, so the
48213
+ // previous 8-4-4-4-12 regex rejected every real batch ID. Agrees with isBatchId in
48214
+ // src/types/guards.ts.
48215
+ external_exports.string().regex(/^[0-9a-fA-F]{64}$/, "Invalid batch ID format")
47681
48216
  );
47682
48217
  var CellSlugSchema2 = createBrandedSchema(
47683
48218
  "CellSlug",
@@ -47767,7 +48302,9 @@ ${operationTypes.join("\n")}
47767
48302
  // Optional default urql request policy for reads (server/sync clients pass
47768
48303
  // 'network-only'). Permitted by the strict schema so the constructor option
47769
48304
  // isn't rejected.
47770
- defaultRequestPolicy: external_exports.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional()
48305
+ defaultRequestPolicy: external_exports.enum(["cache-first", "cache-only", "network-only", "cache-and-network"]).nullable().optional(),
48306
+ // Pluggable hardware envelope encryption secret storage provider
48307
+ secretStorage: external_exports.unknown().optional()
47771
48308
  }).strict();
47772
48309
  var EnvironmentConfigSchema = external_exports.object({
47773
48310
  NODE_ENV: external_exports.enum(["development", "production", "test"]).optional(),
@@ -48580,89 +49117,6 @@ ${operationTypes.join("\n")}
48580
49117
 
48581
49118
  // src/response/ResponseBalance.ts
48582
49119
  init_Response();
48583
-
48584
- // src/core/TokenUnit.ts
48585
- var TokenUnit = class _TokenUnit {
48586
- id;
48587
- name;
48588
- metas;
48589
- /**
48590
- * Create new TokenUnit instance
48591
- * Matches JavaScript SDK constructor signature exactly
48592
- */
48593
- constructor(id, name2, metas) {
48594
- this.id = id;
48595
- this.name = name2;
48596
- this.metas = metas || {};
48597
- }
48598
- /**
48599
- * Create TokenUnit from GraphQL response data
48600
- * Matches JavaScript SDK createFromGraphQL method exactly
48601
- */
48602
- static createFromGraphQL(data) {
48603
- let metas = data.metas || {};
48604
- if (Array.isArray(metas) && metas.length) {
48605
- try {
48606
- metas = JSON.parse(metas);
48607
- if (!metas) {
48608
- metas = {};
48609
- }
48610
- } catch (error62) {
48611
- metas = {};
48612
- }
48613
- }
48614
- return new _TokenUnit(
48615
- data.id,
48616
- data.name,
48617
- metas
48618
- );
48619
- }
48620
- /**
48621
- * Create TokenUnit from database array data
48622
- * Matches JavaScript SDK createFromDB method exactly
48623
- */
48624
- static createFromDB(data) {
48625
- return new _TokenUnit(
48626
- data[0],
48627
- data[1],
48628
- data.length > 2 ? data[2] : {}
48629
- );
48630
- }
48631
- /**
48632
- * Get fragment zone from metadata
48633
- * Matches JavaScript SDK getFragmentZone method exactly
48634
- */
48635
- getFragmentZone() {
48636
- return this.metas.fragmentZone || null;
48637
- }
48638
- /**
48639
- * Get fused token units from metadata
48640
- * Matches JavaScript SDK getFusedTokenUnits method exactly
48641
- */
48642
- getFusedTokenUnits() {
48643
- return this.metas.fusedTokenUnits || null;
48644
- }
48645
- /**
48646
- * Convert to data array format
48647
- * Matches JavaScript SDK toData method exactly
48648
- */
48649
- toData() {
48650
- return [this.id, this.name, this.metas];
48651
- }
48652
- /**
48653
- * Convert to GraphQL response format
48654
- * Matches JavaScript SDK toGraphQLResponse method exactly
48655
- */
48656
- toGraphQLResponse() {
48657
- return {
48658
- id: this.id,
48659
- name: this.name,
48660
- metas: JSON.stringify(this.metas)
48661
- };
48662
- }
48663
- };
48664
-
48665
- // src/response/ResponseBalance.ts
48666
49120
  var ResponseBalance = class _ResponseBalance extends exports.Response {
48667
49121
  /**
48668
49122
  * Class constructor
@@ -51201,6 +51655,12 @@ ${operationTypes.join("\n")}
51201
51655
  }
51202
51656
  };
51203
51657
 
51658
+ // src/mutation/MutationReplenishToken.ts
51659
+ var MutationReplenishToken = class extends MutationProposeMolecule {
51660
+ fillMolecule() {
51661
+ }
51662
+ };
51663
+
51204
51664
  // src/subscribe/Subscribe.ts
51205
51665
  init_exception();
51206
51666
  var Subscribe = class {
@@ -51420,9 +51880,134 @@ ${operationTypes.join("\n")}
51420
51880
 
51421
51881
  // src/KnishIOClient.ts
51422
51882
  init_exception();
51883
+
51884
+ // src/storage/MemorySecretStorageProvider.ts
51885
+ init_SecretStorageException();
51886
+
51887
+ // src/libraries/secureMemory.ts
51888
+ var textEncoder = new TextEncoder();
51889
+ function zeroizeBytes(buffer) {
51890
+ if (buffer instanceof Uint8Array) {
51891
+ buffer.fill(0);
51892
+ } else if (Array.isArray(buffer)) {
51893
+ for (let i4 = 0; i4 < buffer.length; i4++) {
51894
+ buffer[i4] = 0;
51895
+ }
51896
+ }
51897
+ }
51898
+ async function withSecureBytes(bytes, fn) {
51899
+ try {
51900
+ return await fn(bytes);
51901
+ } finally {
51902
+ zeroizeBytes(bytes);
51903
+ }
51904
+ }
51905
+ async function withSecureString(secret, fn) {
51906
+ const bytes = textEncoder.encode(secret);
51907
+ try {
51908
+ return await fn(secret);
51909
+ } finally {
51910
+ zeroizeBytes(bytes);
51911
+ }
51912
+ }
51913
+ function constantTimeCompare(a3, b2) {
51914
+ const bytesA = typeof a3 === "string" ? textEncoder.encode(a3) : a3;
51915
+ const bytesB = typeof b2 === "string" ? textEncoder.encode(b2) : b2;
51916
+ let result = bytesA.length === bytesB.length ? 0 : 1;
51917
+ const len = Math.min(bytesA.length, bytesB.length);
51918
+ for (let i4 = 0; i4 < len; i4++) {
51919
+ const byteA = bytesA[i4] ?? 0;
51920
+ const byteB = bytesB[i4] ?? 0;
51921
+ result |= byteA ^ byteB;
51922
+ }
51923
+ if (typeof a3 === "string") zeroizeBytes(bytesA);
51924
+ if (typeof b2 === "string") zeroizeBytes(bytesB);
51925
+ return result === 0;
51926
+ }
51927
+
51928
+ // src/storage/MemorySecretStorageProvider.ts
51929
+ var MemorySecretStorageProvider = class {
51930
+ providerType = "memory";
51931
+ secrets = /* @__PURE__ */ new Map();
51932
+ /**
51933
+ * Memory storage is not hardware backed
51934
+ */
51935
+ isHardwareBacked() {
51936
+ return false;
51937
+ }
51938
+ /**
51939
+ * Memory storage is always available
51940
+ */
51941
+ async isAvailable() {
51942
+ return true;
51943
+ }
51944
+ /**
51945
+ * Store a secret in memory
51946
+ */
51947
+ async storeSecret(bundleHash, secret, options) {
51948
+ if (!bundleHash) {
51949
+ throw new exports.SecretStorageException("Bundle hash cannot be empty");
51950
+ }
51951
+ if (!secret) {
51952
+ throw new exports.SecretStorageException("Secret cannot be empty");
51953
+ }
51954
+ const metadata = {
51955
+ bundleHash,
51956
+ label: options?.label,
51957
+ createdAt: Date.now(),
51958
+ hardwareBacked: false,
51959
+ providerType: this.providerType
51960
+ };
51961
+ this.secrets.set(bundleHash, { secret, metadata });
51962
+ }
51963
+ /**
51964
+ * Retrieve a secret from memory
51965
+ */
51966
+ async retrieveSecret(bundleHash) {
51967
+ const entry = this.secrets.get(bundleHash);
51968
+ return entry ? entry.secret : null;
51969
+ }
51970
+ /**
51971
+ * Delete a stored secret
51972
+ */
51973
+ async deleteSecret(bundleHash) {
51974
+ return this.secrets.delete(bundleHash);
51975
+ }
51976
+ /**
51977
+ * Check if a secret exists
51978
+ */
51979
+ async hasSecret(bundleHash) {
51980
+ return this.secrets.has(bundleHash);
51981
+ }
51982
+ /**
51983
+ * List all stored secret metadata
51984
+ */
51985
+ async listSecrets() {
51986
+ return Array.from(this.secrets.values()).map((entry) => ({ ...entry.metadata }));
51987
+ }
51988
+ /**
51989
+ * Execute callback with unwrapped secret and ensure cleanup
51990
+ */
51991
+ async withSecret(bundleHash, fn) {
51992
+ const entry = this.secrets.get(bundleHash);
51993
+ if (!entry) {
51994
+ throw exports.SecretStorageException.notFound(bundleHash);
51995
+ }
51996
+ return withSecureString(entry.secret, fn);
51997
+ }
51998
+ /**
51999
+ * Clear all secrets from memory
52000
+ */
52001
+ clear() {
52002
+ this.secrets.clear();
52003
+ }
52004
+ };
52005
+
52006
+ // src/KnishIOClient.ts
51423
52007
  var KnishIOClient = class {
51424
52008
  $__secret = "";
51425
52009
  $__bundle = "";
52010
+ $__secretStorage = null;
51426
52011
  $__cellSlug = null;
51427
52012
  $__encrypt = false;
51428
52013
  $__uris = [];
@@ -51482,6 +52067,9 @@ ${operationTypes.join("\n")}
51482
52067
  logging,
51483
52068
  defaultRequestPolicy
51484
52069
  });
52070
+ if (config2.secretStorage) {
52071
+ this.$__secretStorage = config2.secretStorage;
52072
+ }
51485
52073
  }
51486
52074
  /**
51487
52075
  * Initializes a new Knish.IO client session
@@ -51583,6 +52171,7 @@ ${operationTypes.join("\n")}
51583
52171
  reset() {
51584
52172
  this.$__secret = "";
51585
52173
  this.$__bundle = "";
52174
+ this.$__secretStorage = null;
51586
52175
  this.$__encrypt = false;
51587
52176
  this.$__cellSlug = null;
51588
52177
  this.$__authToken = null;
@@ -51644,7 +52233,7 @@ ${operationTypes.join("\n")}
51644
52233
  * Returns whether a secret is stored for this session
51645
52234
  */
51646
52235
  hasSecret() {
51647
- return !!this.$__secret && this.$__secret.length > 0;
52236
+ return !!this.$__secret && this.$__secret.length > 0 || !!this.$__secretStorage && !!this.$__bundle && this.$__bundle.length > 0;
51648
52237
  }
51649
52238
  /**
51650
52239
  * Returns the stored secret
@@ -51655,6 +52244,33 @@ ${operationTypes.join("\n")}
51655
52244
  }
51656
52245
  return this.$__secret;
51657
52246
  }
52247
+ /**
52248
+ * Sets the secret storage provider and optionally sets the bundle hash
52249
+ */
52250
+ setSecretStorage(storage, bundleHash) {
52251
+ this.$__secretStorage = storage;
52252
+ if (bundleHash) {
52253
+ this.$__bundle = bundleHash;
52254
+ }
52255
+ }
52256
+ /**
52257
+ * Returns current secret storage provider
52258
+ */
52259
+ getSecretStorage() {
52260
+ return this.$__secretStorage;
52261
+ }
52262
+ /**
52263
+ * Asynchronously retrieves the secret from storage or returns in-memory secret
52264
+ */
52265
+ async retrieveSecret(options) {
52266
+ if (this.$__secret && this.$__secret.length > 0) {
52267
+ return this.$__secret;
52268
+ }
52269
+ if (this.$__secretStorage && this.$__bundle && this.$__bundle.length > 0) {
52270
+ return await this.$__secretStorage.retrieveSecret(this.$__bundle, options);
52271
+ }
52272
+ return null;
52273
+ }
51658
52274
  /**
51659
52275
  * Returns whether a bundle hash is being stored for this session
51660
52276
  */
@@ -51693,6 +52309,13 @@ ${operationTypes.join("\n")}
51693
52309
  remainderWallet = null
51694
52310
  } = {}) {
51695
52311
  this.log("info", "KnishIOClient::createMolecule() - Creating a new molecule...");
52312
+ if (!secret) {
52313
+ if (this.$__secret && this.$__secret.length > 0) {
52314
+ secret = this.getSecret();
52315
+ } else if (this.$__secretStorage && this.$__bundle && this.$__bundle.length > 0) {
52316
+ secret = await this.$__secretStorage.retrieveSecret(this.$__bundle);
52317
+ }
52318
+ }
51696
52319
  secret = secret || this.getSecret();
51697
52320
  bundle = bundle || this.getBundle();
51698
52321
  let continuIdPosition = null;
@@ -51722,6 +52345,7 @@ ${operationTypes.join("\n")}
51722
52345
  }));
51723
52346
  return new Molecule({
51724
52347
  secret,
52348
+ bundle,
51725
52349
  sourceWallet,
51726
52350
  remainderWallet: this.getRemainderWallet(),
51727
52351
  cellSlug: this.getCellSlug(),
@@ -51768,8 +52392,9 @@ ${operationTypes.join("\n")}
51768
52392
  async executeQuery(query, variables = null, context = {}) {
51769
52393
  if (this.$__authToken && this.$__authToken.isExpired() && !this.$__authInProcess) {
51770
52394
  this.log("info", "KnishIOClient::executeQuery() - Access token is expired. Getting new one...");
52395
+ const authSecret = this.$__secret || await this.retrieveSecret() || "";
51771
52396
  await this.requestAuthToken({
51772
- secret: this.$__secret,
52397
+ secret: authSecret,
51773
52398
  cellSlug: this.$__cellSlug,
51774
52399
  encrypt: this.$__encrypt
51775
52400
  });
@@ -51809,6 +52434,13 @@ ${operationTypes.join("\n")}
51809
52434
  setSecret(secret) {
51810
52435
  this.$__secret = secret;
51811
52436
  this.$__bundle = generateBundleHash(secret);
52437
+ if (!this.$__secretStorage) {
52438
+ const memStorage = new MemorySecretStorageProvider();
52439
+ memStorage.storeSecret(this.$__bundle, secret);
52440
+ this.$__secretStorage = memStorage;
52441
+ } else {
52442
+ this.$__secretStorage.storeSecret(this.$__bundle, secret);
52443
+ }
51812
52444
  }
51813
52445
  /**
51814
52446
  * Sets the auth token for this session
@@ -51992,6 +52624,9 @@ ${operationTypes.join("\n")}
51992
52624
  if (secret === null && seed) {
51993
52625
  secret = generateSecret(seed);
51994
52626
  }
52627
+ if (secret === null && this.$__secretStorage && this.$__bundle) {
52628
+ secret = await this.$__secretStorage.retrieveSecret(this.$__bundle);
52629
+ }
51995
52630
  if (cellSlug) {
51996
52631
  this.setCellSlug(cellSlug);
51997
52632
  }
@@ -52642,20 +53277,42 @@ ${operationTypes.join("\n")}
52642
53277
  return response;
52643
53278
  }
52644
53279
  /**
52645
- * Replenish tokens
53280
+ * Replenish a non-finite token supply.
53281
+ * Matches JS SDK KnishIOClient.replenishToken (KnishIOClient.js:2195-2231).
52646
53282
  */
52647
53283
  async replenishToken({
52648
53284
  token,
52649
53285
  amount = null,
52650
53286
  units = null,
52651
- sourceWallet: _sourceWallet = null
53287
+ sourceWallet = null
52652
53288
  }) {
52653
53289
  this.log("info", `KnishIOClient::replenishToken() - Replenishing ${amount || "units"} of ${token}...`);
52654
- return this.requestTokens({
52655
- token,
52656
- amount,
52657
- units
53290
+ if (!sourceWallet) {
53291
+ sourceWallet = (await this.queryBalance({ token }))?.payload();
53292
+ }
53293
+ if (!sourceWallet) {
53294
+ throw new exports.TransferBalanceException("Source wallet is missing or invalid.");
53295
+ }
53296
+ const remainderWallet = sourceWallet.createRemainder(this.getSecret());
53297
+ const molecule = await this.createMolecule({
53298
+ sourceWallet,
53299
+ remainderWallet
53300
+ });
53301
+ molecule.replenishToken({
53302
+ amount: Number(amount ?? 0),
53303
+ units: units ?? []
53304
+ });
53305
+ molecule.sign({ bundle: this.getBundle() });
53306
+ molecule.check();
53307
+ const mutation = await this.createMoleculeMutation({
53308
+ mutationClass: MutationReplenishToken,
53309
+ molecule
52658
53310
  });
53311
+ const response = await this.executeQuery(mutation);
53312
+ if (!response) {
53313
+ throw new CodeException("Token replenishment failed");
53314
+ }
53315
+ return response;
52659
53316
  }
52660
53317
  /**
52661
53318
  * Fuse token units
@@ -53106,75 +53763,298 @@ ${operationTypes.join("\n")}
53106
53763
 
53107
53764
  // src/index.ts
53108
53765
  init_Response();
53766
+ init_exception();
53109
53767
 
53110
- // src/core/PolicyMeta.ts
53111
- var PolicyMeta = class _PolicyMeta {
53112
- policy;
53768
+ // src/storage/WebCryptoSecretStorageProvider.ts
53769
+ init_SecretStorageException();
53770
+ var MemoryStorageBackend = class {
53771
+ store = /* @__PURE__ */ new Map();
53772
+ getItem(key) {
53773
+ return this.store.get(key) ?? null;
53774
+ }
53775
+ setItem(key, value2) {
53776
+ this.store.set(key, value2);
53777
+ }
53778
+ removeItem(key) {
53779
+ return this.store.delete(key);
53780
+ }
53781
+ keys() {
53782
+ return Array.from(this.store.keys());
53783
+ }
53784
+ };
53785
+ function uint8ArrayToBase642(bytes) {
53786
+ let binary = "";
53787
+ const len = bytes.byteLength;
53788
+ for (let i4 = 0; i4 < len; i4++) {
53789
+ const byte = bytes[i4];
53790
+ if (byte !== void 0) {
53791
+ binary += String.fromCharCode(byte);
53792
+ }
53793
+ }
53794
+ return btoa(binary);
53795
+ }
53796
+ function base64ToUint8Array2(base643) {
53797
+ const binary = atob(base643);
53798
+ const len = binary.length;
53799
+ const bytes = new Uint8Array(len);
53800
+ for (let i4 = 0; i4 < len; i4++) {
53801
+ bytes[i4] = binary.charCodeAt(i4);
53802
+ }
53803
+ return bytes;
53804
+ }
53805
+ var textEncoder2 = new TextEncoder();
53806
+ var textDecoder = new TextDecoder();
53807
+ var KEY_PREFIX = "knishio:secret:";
53808
+ var DEFAULT_ITERATIONS = 1e5;
53809
+ var WebCryptoSecretStorageProvider = class {
53810
+ providerType = "webcrypto-aes-gcm";
53811
+ backend;
53812
+ defaultPassphrase;
53813
+ hardwareBacked;
53814
+ constructor(options = {}) {
53815
+ this.backend = options.backend ?? new MemoryStorageBackend();
53816
+ this.defaultPassphrase = options.defaultPassphrase;
53817
+ this.hardwareBacked = options.hardwareBacked ?? false;
53818
+ }
53113
53819
  /**
53114
- * Create new PolicyMeta instance
53115
- * Matches JavaScript SDK constructor signature exactly
53820
+ * Whether this provider is backed by hardware (e.g. WebAuthn PRF wrapping)
53116
53821
  */
53117
- constructor(policy = {}, metaKeys = []) {
53118
- this.policy = _PolicyMeta.normalizePolicy(policy);
53119
- this.fillDefault(metaKeys);
53822
+ isHardwareBacked() {
53823
+ return this.hardwareBacked;
53120
53824
  }
53121
53825
  /**
53122
- * Normalize policy object structure
53123
- * Matches JavaScript SDK normalizePolicy method exactly
53826
+ * Check if WebCrypto subtle API is available
53124
53827
  */
53125
- static normalizePolicy(policy = {}) {
53126
- const policyMeta = {};
53127
- for (const [policyKey, value2] of Object.entries(policy)) {
53128
- if (value2 !== null && ["read", "write"].includes(policyKey)) {
53129
- policyMeta[policyKey] = {};
53130
- for (const [key, content] of Object.entries(value2)) {
53131
- policyMeta[policyKey][key] = content;
53132
- }
53133
- }
53828
+ async isAvailable() {
53829
+ return typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.subtle !== "undefined";
53830
+ }
53831
+ /**
53832
+ * Derive an AES-GCM CryptoKey from a passphrase and salt using PBKDF2
53833
+ */
53834
+ async deriveKey(passphrase, salt, iterations = DEFAULT_ITERATIONS) {
53835
+ if (!await this.isAvailable()) {
53836
+ throw exports.SecretStorageException.unavailable(this.providerType, "WebCrypto API is not available");
53837
+ }
53838
+ const passphraseBytes = textEncoder2.encode(passphrase);
53839
+ try {
53840
+ const baseKey = await globalThis.crypto.subtle.importKey(
53841
+ "raw",
53842
+ passphraseBytes,
53843
+ "PBKDF2",
53844
+ false,
53845
+ ["deriveKey"]
53846
+ );
53847
+ return await globalThis.crypto.subtle.deriveKey(
53848
+ {
53849
+ name: "PBKDF2",
53850
+ salt,
53851
+ iterations,
53852
+ hash: "SHA-256"
53853
+ },
53854
+ baseKey,
53855
+ { name: "AES-GCM", length: 256 },
53856
+ false,
53857
+ ["encrypt", "decrypt"]
53858
+ );
53859
+ } finally {
53860
+ zeroizeBytes(passphraseBytes);
53134
53861
  }
53135
- return policyMeta;
53136
53862
  }
53137
53863
  /**
53138
- * Fill default policy values for metadata keys
53139
- * Matches JavaScript SDK fillDefault method exactly
53864
+ * Store and encrypt a master secret
53140
53865
  */
53141
- fillDefault(metaKeys = []) {
53142
- const readPolicy = Array.from(this.policy).filter((item) => item.action === "read");
53143
- const writePolicy = Array.from(this.policy).filter((item) => item.action === "write");
53144
- for (const [type2, value2] of Object.entries({
53145
- read: readPolicy,
53146
- write: writePolicy
53147
- })) {
53148
- const policyKey = value2.map((item) => item.key);
53149
- if (!this.policy[type2]) {
53150
- this.policy[type2] = {};
53151
- }
53152
- for (const key of diff(metaKeys, policyKey)) {
53153
- if (!this.policy[type2][key]) {
53154
- this.policy[type2][key] = type2 === "write" && !["characters", "pubkey"].includes(key) ? ["self"] : ["all"];
53155
- }
53866
+ async storeSecret(bundleHash, secret, options) {
53867
+ if (!bundleHash) {
53868
+ throw new exports.SecretStorageException("Bundle hash cannot be empty");
53869
+ }
53870
+ if (!secret) {
53871
+ throw new exports.SecretStorageException("Secret cannot be empty");
53872
+ }
53873
+ const passphrase = options?.passphrase ?? this.defaultPassphrase;
53874
+ if (!passphrase) {
53875
+ throw new exports.SecretStorageException("Passphrase required for envelope encryption");
53876
+ }
53877
+ const salt = new Uint8Array(16);
53878
+ const iv = new Uint8Array(12);
53879
+ globalThis.crypto.getRandomValues(salt);
53880
+ globalThis.crypto.getRandomValues(iv);
53881
+ const key = await this.deriveKey(passphrase, salt, DEFAULT_ITERATIONS);
53882
+ const secretBytes = textEncoder2.encode(secret);
53883
+ try {
53884
+ const encryptedBuffer = await globalThis.crypto.subtle.encrypt(
53885
+ {
53886
+ name: "AES-GCM",
53887
+ iv
53888
+ },
53889
+ key,
53890
+ secretBytes
53891
+ );
53892
+ const ciphertext = uint8ArrayToBase642(new Uint8Array(encryptedBuffer));
53893
+ const metadata = {
53894
+ bundleHash,
53895
+ label: options?.label,
53896
+ createdAt: Date.now(),
53897
+ hardwareBacked: this.hardwareBacked,
53898
+ providerType: this.providerType
53899
+ };
53900
+ const payload = {
53901
+ version: 1,
53902
+ ciphertext,
53903
+ iv: uint8ArrayToBase642(iv),
53904
+ salt: uint8ArrayToBase642(salt),
53905
+ algorithm: "AES-GCM",
53906
+ iterations: DEFAULT_ITERATIONS,
53907
+ metadata
53908
+ };
53909
+ await this.backend.setItem(`${KEY_PREFIX}${bundleHash}`, JSON.stringify(payload));
53910
+ } catch (err) {
53911
+ const msg = err instanceof Error ? err.message : String(err);
53912
+ throw new exports.SecretStorageException(`Encryption failed: ${msg}`);
53913
+ } finally {
53914
+ zeroizeBytes(secretBytes);
53915
+ }
53916
+ }
53917
+ /**
53918
+ * Retrieve and decrypt the master secret
53919
+ */
53920
+ async retrieveSecret(bundleHash, options) {
53921
+ const raw = await this.backend.getItem(`${KEY_PREFIX}${bundleHash}`);
53922
+ if (!raw) {
53923
+ return null;
53924
+ }
53925
+ let payload;
53926
+ try {
53927
+ payload = JSON.parse(raw);
53928
+ } catch {
53929
+ throw exports.SecretStorageException.decryptionFailed("Corrupted payload format");
53930
+ }
53931
+ const passphrase = options?.passphrase ?? this.defaultPassphrase;
53932
+ if (!passphrase) {
53933
+ throw new exports.SecretStorageException("Passphrase required for secret decryption");
53934
+ }
53935
+ const salt = base64ToUint8Array2(payload.salt);
53936
+ const iv = base64ToUint8Array2(payload.iv);
53937
+ const ciphertext = base64ToUint8Array2(payload.ciphertext);
53938
+ try {
53939
+ const key = await this.deriveKey(passphrase, salt, payload.iterations ?? DEFAULT_ITERATIONS);
53940
+ const decryptedBuffer = await globalThis.crypto.subtle.decrypt(
53941
+ {
53942
+ name: "AES-GCM",
53943
+ iv
53944
+ },
53945
+ key,
53946
+ ciphertext
53947
+ );
53948
+ const decryptedBytes = new Uint8Array(decryptedBuffer);
53949
+ try {
53950
+ return textDecoder.decode(decryptedBytes);
53951
+ } finally {
53952
+ zeroizeBytes(decryptedBytes);
53156
53953
  }
53954
+ } catch (err) {
53955
+ const msg = err instanceof Error ? err.message : String(err);
53956
+ throw exports.SecretStorageException.decryptionFailed(msg);
53157
53957
  }
53158
53958
  }
53159
53959
  /**
53160
- * Get the policy object
53161
- * Matches JavaScript SDK get method exactly
53960
+ * Delete a stored secret
53162
53961
  */
53163
- get() {
53164
- return this.policy;
53962
+ async deleteSecret(bundleHash) {
53963
+ const key = `${KEY_PREFIX}${bundleHash}`;
53964
+ const result = await this.backend.removeItem(key);
53965
+ return result !== false;
53165
53966
  }
53166
53967
  /**
53167
- * Convert policy to JSON string
53168
- * Matches JavaScript SDK toJson method exactly
53968
+ * Check if a secret exists
53169
53969
  */
53170
- toJson() {
53171
- return JSON.stringify(this.get());
53970
+ async hasSecret(bundleHash) {
53971
+ const raw = await this.backend.getItem(`${KEY_PREFIX}${bundleHash}`);
53972
+ return raw !== null;
53973
+ }
53974
+ /**
53975
+ * List all stored secret metadata
53976
+ */
53977
+ async listSecrets() {
53978
+ const keys = await this.backend.keys();
53979
+ const matchingKeys = keys.filter((k2) => k2.startsWith(KEY_PREFIX));
53980
+ const results = [];
53981
+ for (const key of matchingKeys) {
53982
+ const raw = await this.backend.getItem(key);
53983
+ if (raw) {
53984
+ try {
53985
+ const payload = JSON.parse(raw);
53986
+ if (payload.metadata) {
53987
+ results.push(payload.metadata);
53988
+ }
53989
+ } catch {
53990
+ }
53991
+ }
53992
+ }
53993
+ return results;
53994
+ }
53995
+ /**
53996
+ * Execute callback with unwrapped secret, zeroizing the decrypted buffer upon completion
53997
+ */
53998
+ async withSecret(bundleHash, fn, options) {
53999
+ const raw = await this.backend.getItem(`${KEY_PREFIX}${bundleHash}`);
54000
+ if (!raw) {
54001
+ throw exports.SecretStorageException.notFound(bundleHash);
54002
+ }
54003
+ let payload;
54004
+ try {
54005
+ payload = JSON.parse(raw);
54006
+ } catch {
54007
+ throw exports.SecretStorageException.decryptionFailed("Corrupted payload format");
54008
+ }
54009
+ const passphrase = options?.passphrase ?? this.defaultPassphrase;
54010
+ if (!passphrase) {
54011
+ throw new exports.SecretStorageException("Passphrase required for secret decryption");
54012
+ }
54013
+ const salt = base64ToUint8Array2(payload.salt);
54014
+ const iv = base64ToUint8Array2(payload.iv);
54015
+ const ciphertext = base64ToUint8Array2(payload.ciphertext);
54016
+ try {
54017
+ const key = await this.deriveKey(passphrase, salt, payload.iterations ?? DEFAULT_ITERATIONS);
54018
+ const decryptedBuffer = await globalThis.crypto.subtle.decrypt(
54019
+ {
54020
+ name: "AES-GCM",
54021
+ iv
54022
+ },
54023
+ key,
54024
+ ciphertext
54025
+ );
54026
+ const decryptedBytes = new Uint8Array(decryptedBuffer);
54027
+ return await withSecureBytes(decryptedBytes, async (bytes) => {
54028
+ const secretString = textDecoder.decode(bytes);
54029
+ return await fn(secretString);
54030
+ });
54031
+ } catch (err) {
54032
+ if (err instanceof exports.SecretStorageException) {
54033
+ throw err;
54034
+ }
54035
+ const msg = err instanceof Error ? err.message : String(err);
54036
+ throw exports.SecretStorageException.decryptionFailed(msg);
54037
+ }
53172
54038
  }
53173
54039
  };
53174
54040
 
54041
+ // src/storage/index.ts
54042
+ function createDefaultSecretStorage(options = {}) {
54043
+ if (options.type === "memory") {
54044
+ return new MemorySecretStorageProvider();
54045
+ }
54046
+ if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.subtle !== "undefined") {
54047
+ return new WebCryptoSecretStorageProvider({
54048
+ backend: options.backend,
54049
+ defaultPassphrase: options.defaultPassphrase,
54050
+ hardwareBacked: options.hardwareBacked
54051
+ });
54052
+ }
54053
+ return new MemorySecretStorageProvider();
54054
+ }
54055
+
53175
54056
  // src/index.ts
53176
- init_exception();
53177
- var SDK_VERSION = "0.9.5";
54057
+ var SDK_VERSION = "0.9.7";
53178
54058
  var SDK_NAME = "KnishIO-Client-TS";
53179
54059
  var COMPATIBLE_SERVER_VERSIONS = [4, 5];
53180
54060
  var SDK_INFO = {
@@ -53265,8 +54145,8 @@ ${operationTypes.join("\n")}
53265
54145
  };
53266
54146
  /*! Bundled license information:
53267
54147
 
53268
- @noble/hashes/utils.js:
53269
- (*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
54148
+ @noble/curves/utils.js:
54149
+ (*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
53270
54150
 
53271
54151
  @noble/post-quantum/utils.js:
53272
54152
  @noble/post-quantum/_crystals.js:
@@ -53285,6 +54165,8 @@ ${operationTypes.join("\n")}
53285
54165
  exports.GraphQLClient = GraphQLClient;
53286
54166
  exports.KnishIO = KnishIO;
53287
54167
  exports.KnishIOClient = KnishIOClient;
54168
+ exports.MemorySecretStorageProvider = MemorySecretStorageProvider;
54169
+ exports.MemoryStorageBackend = MemoryStorageBackend;
53288
54170
  exports.Meta = Meta;
53289
54171
  exports.Molecule = Molecule;
53290
54172
  exports.Mutation = Mutation;
@@ -53330,6 +54212,7 @@ ${operationTypes.join("\n")}
53330
54212
  exports.SDK_VERSION = SDK_VERSION;
53331
54213
  exports.TokenUnit = TokenUnit;
53332
54214
  exports.Wallet = Wallet;
54215
+ exports.WebCryptoSecretStorageProvider = WebCryptoSecretStorageProvider;
53333
54216
  exports.base64ToHex = base64ToHex;
53334
54217
  exports.bufferToHexString = bufferToHexString;
53335
54218
  exports.capitalize = capitalize;
@@ -53337,8 +54220,10 @@ ${operationTypes.join("\n")}
53337
54220
  exports.chunkArray = chunkArray;
53338
54221
  exports.chunkSubstr = chunkSubstr;
53339
54222
  exports.configureSDK = configureSDK;
54223
+ exports.constantTimeCompare = constantTimeCompare;
53340
54224
  exports.convertToBase17 = convertToBase17;
53341
54225
  exports.createBundleHash = createBundleHash;
54226
+ exports.createDefaultSecretStorage = createDefaultSecretStorage;
53342
54227
  exports.createMolecularHash = createMolecularHash;
53343
54228
  exports.createPosition = createPosition;
53344
54229
  exports.createTokenSlug = createTokenSlug;
@@ -53380,6 +54265,9 @@ ${operationTypes.join("\n")}
53380
54265
  exports.validateSecret = validateSecret;
53381
54266
  exports.validateWalletAddress = validateWalletAddress;
53382
54267
  exports.verifyOTSSignature = verifyOTSSignature;
54268
+ exports.withSecureBytes = withSecureBytes;
54269
+ exports.withSecureString = withSecureString;
54270
+ exports.zeroizeBytes = zeroizeBytes;
53383
54271
 
53384
54272
  return exports;
53385
54273