function __awaiter(thisArg, _arguments, P, generator) {
  function adopt(value) {
    return value instanceof P ? value : new P(function(resolve) {
      resolve(value);
    });
  }
  return new (P || (P = Promise))(function(resolve, reject) {
    function fulfilled(value) {
      try {
        step(generator.next(value));
      } catch (e) {
        reject(e);
      }
    }
    function rejected(value) {
      try {
        step(generator["throw"](value));
      } catch (e) {
        reject(e);
      }
    }
    function step(result) {
      result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
    }
    step((generator = generator.apply(thisArg, [])).next());
  });
}
typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
  var e = new Error(message);
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
class Mutex {
  constructor() {
    this.mutex = Promise.resolve();
  }
  lock() {
    let begin = () => {
    };
    this.mutex = this.mutex.then(() => new Promise(begin));
    return new Promise((res) => {
      begin = res;
    });
  }
  dispatch(fn) {
    return __awaiter(this, void 0, void 0, function* () {
      const unlock = yield this.lock();
      try {
        return yield Promise.resolve(fn());
      } finally {
        unlock();
      }
    });
  }
}
var _a;
function getGlobal() {
  if (typeof globalThis !== "undefined")
    return globalThis;
  if (typeof self !== "undefined")
    return self;
  if (typeof window !== "undefined")
    return window;
  return global;
}
const globalObject = getGlobal();
const nodeBuffer = (_a = globalObject.Buffer) !== null && _a !== void 0 ? _a : null;
const textEncoder = globalObject.TextEncoder ? new globalObject.TextEncoder() : null;
function hexCharCodesToInt(a, b) {
  return (a & 15) + (a >> 6 | a >> 3 & 8) << 4 | (b & 15) + (b >> 6 | b >> 3 & 8);
}
function writeHexToUInt8(buf, str) {
  const size = str.length >> 1;
  for (let i = 0; i < size; i++) {
    const index = i << 1;
    buf[i] = hexCharCodesToInt(str.charCodeAt(index), str.charCodeAt(index + 1));
  }
}
function hexStringEqualsUInt8(str, buf) {
  if (str.length !== buf.length * 2) {
    return false;
  }
  for (let i = 0; i < buf.length; i++) {
    const strIndex = i << 1;
    if (buf[i] !== hexCharCodesToInt(str.charCodeAt(strIndex), str.charCodeAt(strIndex + 1))) {
      return false;
    }
  }
  return true;
}
const alpha = "a".charCodeAt(0) - 10;
const digit = "0".charCodeAt(0);
function getDigestHex(tmpBuffer, input, hashLength) {
  let p = 0;
  for (let i = 0; i < hashLength; i++) {
    let nibble = input[i] >>> 4;
    tmpBuffer[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
    nibble = input[i] & 15;
    tmpBuffer[p++] = nibble > 9 ? nibble + alpha : nibble + digit;
  }
  return String.fromCharCode.apply(null, tmpBuffer);
}
const getUInt8Buffer = nodeBuffer !== null ? (data) => {
  if (typeof data === "string") {
    const buf = nodeBuffer.from(data, "utf8");
    return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
  }
  if (nodeBuffer.isBuffer(data)) {
    return new Uint8Array(data.buffer, data.byteOffset, data.length);
  }
  if (ArrayBuffer.isView(data)) {
    return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  }
  throw new Error("Invalid data type!");
} : (data) => {
  if (typeof data === "string") {
    return textEncoder.encode(data);
  }
  if (ArrayBuffer.isView(data)) {
    return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
  }
  throw new Error("Invalid data type!");
};
const base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const base64Lookup = new Uint8Array(256);
for (let i = 0; i < base64Chars.length; i++) {
  base64Lookup[base64Chars.charCodeAt(i)] = i;
}
function encodeBase64(data, pad = true) {
  const len = data.length;
  const extraBytes = len % 3;
  const parts = [];
  const len2 = len - extraBytes;
  for (let i = 0; i < len2; i += 3) {
    const tmp = (data[i] << 16 & 16711680) + (data[i + 1] << 8 & 65280) + (data[i + 2] & 255);
    const triplet = base64Chars.charAt(tmp >> 18 & 63) + base64Chars.charAt(tmp >> 12 & 63) + base64Chars.charAt(tmp >> 6 & 63) + base64Chars.charAt(tmp & 63);
    parts.push(triplet);
  }
  if (extraBytes === 1) {
    const tmp = data[len - 1];
    const a = base64Chars.charAt(tmp >> 2);
    const b = base64Chars.charAt(tmp << 4 & 63);
    parts.push(`${a}${b}`);
    if (pad) {
      parts.push("==");
    }
  } else if (extraBytes === 2) {
    const tmp = (data[len - 2] << 8) + data[len - 1];
    const a = base64Chars.charAt(tmp >> 10);
    const b = base64Chars.charAt(tmp >> 4 & 63);
    const c = base64Chars.charAt(tmp << 2 & 63);
    parts.push(`${a}${b}${c}`);
    if (pad) {
      parts.push("=");
    }
  }
  return parts.join("");
}
function getDecodeBase64Length(data) {
  let bufferLength = Math.floor(data.length * 0.75);
  const len = data.length;
  if (data[len - 1] === "=") {
    bufferLength -= 1;
    if (data[len - 2] === "=") {
      bufferLength -= 1;
    }
  }
  return bufferLength;
}
function decodeBase64(data) {
  const bufferLength = getDecodeBase64Length(data);
  const len = data.length;
  const bytes = new Uint8Array(bufferLength);
  let p = 0;
  for (let i = 0; i < len; i += 4) {
    const encoded1 = base64Lookup[data.charCodeAt(i)];
    const encoded2 = base64Lookup[data.charCodeAt(i + 1)];
    const encoded3 = base64Lookup[data.charCodeAt(i + 2)];
    const encoded4 = base64Lookup[data.charCodeAt(i + 3)];
    bytes[p] = encoded1 << 2 | encoded2 >> 4;
    p += 1;
    bytes[p] = (encoded2 & 15) << 4 | encoded3 >> 2;
    p += 1;
    bytes[p] = (encoded3 & 3) << 6 | encoded4 & 63;
    p += 1;
  }
  return bytes;
}
const MAX_HEAP = 16 * 1024;
const WASM_FUNC_HASH_LENGTH = 4;
const wasmMutex = new Mutex();
const wasmModuleCache = /* @__PURE__ */ new Map();
function WASMInterface(binary, hashLength) {
  return __awaiter(this, void 0, void 0, function* () {
    let wasmInstance = null;
    let memoryView = null;
    let initialized = false;
    if (typeof WebAssembly === "undefined") {
      throw new Error("WebAssembly is not supported in this environment!");
    }
    const writeMemory = (data, offset = 0) => {
      memoryView.set(data, offset);
    };
    const getMemory = () => memoryView;
    const getExports = () => wasmInstance.exports;
    const setMemorySize = (totalSize) => {
      wasmInstance.exports.Hash_SetMemorySize(totalSize);
      const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
      const memoryBuffer = wasmInstance.exports.memory.buffer;
      memoryView = new Uint8Array(memoryBuffer, arrayOffset, totalSize);
    };
    const getStateSize = () => {
      const view = new DataView(wasmInstance.exports.memory.buffer);
      const stateSize = view.getUint32(wasmInstance.exports.STATE_SIZE, true);
      return stateSize;
    };
    const loadWASMPromise = wasmMutex.dispatch(() => __awaiter(this, void 0, void 0, function* () {
      if (!wasmModuleCache.has(binary.name)) {
        const asm = decodeBase64(binary.data);
        const promise = WebAssembly.compile(asm);
        wasmModuleCache.set(binary.name, promise);
      }
      const module = yield wasmModuleCache.get(binary.name);
      wasmInstance = yield WebAssembly.instantiate(module, {
        // env: {
        //   emscripten_memcpy_big: (dest, src, num) => {
        //     const memoryBuffer = wasmInstance.exports.memory.buffer;
        //     const memView = new Uint8Array(memoryBuffer, 0);
        //     memView.set(memView.subarray(src, src + num), dest);
        //   },
        //   print_memory: (offset, len) => {
        //     const memoryBuffer = wasmInstance.exports.memory.buffer;
        //     const memView = new Uint8Array(memoryBuffer, 0);
        //     console.log('print_int32', memView.subarray(offset, offset + len));
        //   },
        // },
      });
    }));
    const setupInterface = () => __awaiter(this, void 0, void 0, function* () {
      if (!wasmInstance) {
        yield loadWASMPromise;
      }
      const arrayOffset = wasmInstance.exports.Hash_GetBuffer();
      const memoryBuffer = wasmInstance.exports.memory.buffer;
      memoryView = new Uint8Array(memoryBuffer, arrayOffset, MAX_HEAP);
    });
    const init = (bits = null) => {
      initialized = true;
      wasmInstance.exports.Hash_Init(bits);
    };
    const updateUInt8Array = (data) => {
      let read = 0;
      while (read < data.length) {
        const chunk = data.subarray(read, read + MAX_HEAP);
        read += chunk.length;
        memoryView.set(chunk);
        wasmInstance.exports.Hash_Update(chunk.length);
      }
    };
    const update = (data) => {
      if (!initialized) {
        throw new Error("update() called before init()");
      }
      const Uint8Buffer = getUInt8Buffer(data);
      updateUInt8Array(Uint8Buffer);
    };
    const digestChars = new Uint8Array(hashLength * 2);
    const digest = (outputType, padding = null) => {
      if (!initialized) {
        throw new Error("digest() called before init()");
      }
      initialized = false;
      wasmInstance.exports.Hash_Final(padding);
      if (outputType === "binary") {
        return memoryView.slice(0, hashLength);
      }
      return getDigestHex(digestChars, memoryView, hashLength);
    };
    const save = () => {
      if (!initialized) {
        throw new Error("save() can only be called after init() and before digest()");
      }
      const stateOffset = wasmInstance.exports.Hash_GetState();
      const stateLength = getStateSize();
      const memoryBuffer = wasmInstance.exports.memory.buffer;
      const internalState = new Uint8Array(memoryBuffer, stateOffset, stateLength);
      const prefixedState = new Uint8Array(WASM_FUNC_HASH_LENGTH + stateLength);
      writeHexToUInt8(prefixedState, binary.hash);
      prefixedState.set(internalState, WASM_FUNC_HASH_LENGTH);
      return prefixedState;
    };
    const load = (state) => {
      if (!(state instanceof Uint8Array)) {
        throw new Error("load() expects an Uint8Array generated by save()");
      }
      const stateOffset = wasmInstance.exports.Hash_GetState();
      const stateLength = getStateSize();
      const overallLength = WASM_FUNC_HASH_LENGTH + stateLength;
      const memoryBuffer = wasmInstance.exports.memory.buffer;
      if (state.length !== overallLength) {
        throw new Error(`Bad state length (expected ${overallLength} bytes, got ${state.length})`);
      }
      if (!hexStringEqualsUInt8(binary.hash, state.subarray(0, WASM_FUNC_HASH_LENGTH))) {
        throw new Error("This state was written by an incompatible hash implementation");
      }
      const internalState = state.subarray(WASM_FUNC_HASH_LENGTH);
      new Uint8Array(memoryBuffer, stateOffset, stateLength).set(internalState);
      initialized = true;
    };
    const isDataShort = (data) => {
      if (typeof data === "string") {
        return data.length < MAX_HEAP / 4;
      }
      return data.byteLength < MAX_HEAP;
    };
    let canSimplify = isDataShort;
    switch (binary.name) {
      case "argon2":
      case "scrypt":
        canSimplify = () => true;
        break;
      case "blake2b":
      case "blake2s":
        canSimplify = (data, initParam) => initParam <= 512 && isDataShort(data);
        break;
      case "blake3":
        canSimplify = (data, initParam) => initParam === 0 && isDataShort(data);
        break;
      case "xxhash64":
      // cannot simplify
      case "xxhash3":
      case "xxhash128":
      case "crc64":
        canSimplify = () => false;
        break;
    }
    const calculate = (data, initParam = null, digestParam = null) => {
      if (!canSimplify(data, initParam)) {
        init(initParam);
        update(data);
        return digest("hex", digestParam);
      }
      const buffer = getUInt8Buffer(data);
      memoryView.set(buffer);
      wasmInstance.exports.Hash_Calculate(buffer.length, initParam, digestParam);
      return getDigestHex(digestChars, memoryView, hashLength);
    };
    yield setupInterface();
    return {
      getMemory,
      writeMemory,
      getExports,
      setMemorySize,
      init,
      update,
      digest,
      save,
      load,
      calculate,
      hashLength
    };
  });
}
new Mutex();
var name$k = "argon2";
var data$k = "[encoded data, 8880 characters]";
var hash$k = "e4cdc523";
var wasmJson$k = {
  name: name$k,
  data: data$k,
  hash: hash$k
};
var name$j = "blake2b";
var data$j = "[encoded data, 9924 characters]";
var hash$j = "c6f286e6";
var wasmJson$j = {
  name: name$j,
  data: data$j,
  hash: hash$j
};
new Mutex();
function validateBits$4(bits) {
  if (!Number.isInteger(bits) || bits < 8 || bits > 512 || bits % 8 !== 0) {
    return new Error("Invalid variant! Valid values: 8, 16, ..., 512");
  }
  return null;
}
function getInitParam$1(outputBits, keyBits) {
  return outputBits | keyBits << 16;
}
function createBLAKE2b(bits = 512, key = null) {
  if (validateBits$4(bits)) {
    return Promise.reject(validateBits$4(bits));
  }
  let keyBuffer = null;
  let initParam = bits;
  if (key !== null) {
    keyBuffer = getUInt8Buffer(key);
    if (keyBuffer.length > 64) {
      return Promise.reject(new Error("Max key length is 64 bytes"));
    }
    initParam = getInitParam$1(bits, keyBuffer.length);
  }
  const outputSize = bits / 8;
  return WASMInterface(wasmJson$j, outputSize).then((wasm) => {
    if (initParam > 512) {
      wasm.writeMemory(keyBuffer);
    }
    wasm.init(initParam);
    const obj = {
      init: initParam > 512 ? () => {
        wasm.writeMemory(keyBuffer);
        wasm.init(initParam);
        return obj;
      } : () => {
        wasm.init(initParam);
        return obj;
      },
      update: (data) => {
        wasm.update(data);
        return obj;
      },
      // biome-ignore lint/suspicious/noExplicitAny: Conflict with IHasher type
      digest: (outputType) => wasm.digest(outputType),
      save: () => wasm.save(),
      load: (data) => {
        wasm.load(data);
        return obj;
      },
      blockSize: 128,
      digestSize: outputSize
    };
    return obj;
  });
}
function encodeResult(salt, options, res) {
  const parameters = [
    `m=${options.memorySize}`,
    `t=${options.iterations}`,
    `p=${options.parallelism}`
  ].join(",");
  return `$argon2${options.hashType}$v=19$${parameters}$${encodeBase64(salt, false)}$${encodeBase64(res, false)}`;
}
const uint32View = new DataView(new ArrayBuffer(4));
function int32LE(x) {
  uint32View.setInt32(0, x, true);
  return new Uint8Array(uint32View.buffer);
}
function hashFunc(blake512, buf, len) {
  return __awaiter(this, void 0, void 0, function* () {
    if (len <= 64) {
      const blake = yield createBLAKE2b(len * 8);
      blake.update(int32LE(len));
      blake.update(buf);
      return blake.digest("binary");
    }
    const r = Math.ceil(len / 32) - 2;
    const ret = new Uint8Array(len);
    blake512.init();
    blake512.update(int32LE(len));
    blake512.update(buf);
    let vp = blake512.digest("binary");
    ret.set(vp.subarray(0, 32), 0);
    for (let i = 1; i < r; i++) {
      blake512.init();
      blake512.update(vp);
      vp = blake512.digest("binary");
      ret.set(vp.subarray(0, 32), i * 32);
    }
    const partialBytesNeeded = len - 32 * r;
    let blakeSmall;
    if (partialBytesNeeded === 64) {
      blakeSmall = blake512;
      blakeSmall.init();
    } else {
      blakeSmall = yield createBLAKE2b(partialBytesNeeded * 8);
    }
    blakeSmall.update(vp);
    vp = blakeSmall.digest("binary");
    ret.set(vp.subarray(0, partialBytesNeeded), r * 32);
    return ret;
  });
}
function getHashType(type) {
  switch (type) {
    case "d":
      return 0;
    case "i":
      return 1;
    default:
      return 2;
  }
}
function argon2Internal(options) {
  return __awaiter(this, void 0, void 0, function* () {
    var _a2;
    const { parallelism, iterations, hashLength } = options;
    const password = getUInt8Buffer(options.password);
    const salt = getUInt8Buffer(options.salt);
    const version = 19;
    const hashType = getHashType(options.hashType);
    const { memorySize } = options;
    const secret = getUInt8Buffer((_a2 = options.secret) !== null && _a2 !== void 0 ? _a2 : "");
    const [argon2Interface, blake512] = yield Promise.all([
      WASMInterface(wasmJson$k, 1024),
      createBLAKE2b(512)
    ]);
    argon2Interface.setMemorySize(memorySize * 1024 + 1024);
    const initVector = new Uint8Array(24);
    const initVectorView = new DataView(initVector.buffer);
    initVectorView.setInt32(0, parallelism, true);
    initVectorView.setInt32(4, hashLength, true);
    initVectorView.setInt32(8, memorySize, true);
    initVectorView.setInt32(12, iterations, true);
    initVectorView.setInt32(16, version, true);
    initVectorView.setInt32(20, hashType, true);
    argon2Interface.writeMemory(initVector, memorySize * 1024);
    blake512.init();
    blake512.update(initVector);
    blake512.update(int32LE(password.length));
    blake512.update(password);
    blake512.update(int32LE(salt.length));
    blake512.update(salt);
    blake512.update(int32LE(secret.length));
    blake512.update(secret);
    blake512.update(int32LE(0));
    const segments = Math.floor(memorySize / (parallelism * 4));
    const lanes = segments * 4;
    const param = new Uint8Array(72);
    const H0 = blake512.digest("binary");
    param.set(H0);
    for (let lane = 0; lane < parallelism; lane++) {
      param.set(int32LE(0), 64);
      param.set(int32LE(lane), 68);
      let position = lane * lanes;
      let chunk = yield hashFunc(blake512, param, 1024);
      argon2Interface.writeMemory(chunk, position * 1024);
      position += 1;
      param.set(int32LE(1), 64);
      chunk = yield hashFunc(blake512, param, 1024);
      argon2Interface.writeMemory(chunk, position * 1024);
    }
    const C = new Uint8Array(1024);
    writeHexToUInt8(C, argon2Interface.calculate(new Uint8Array([]), memorySize));
    const res = yield hashFunc(blake512, C, hashLength);
    if (options.outputType === "hex") {
      const digestChars = new Uint8Array(hashLength * 2);
      return getDigestHex(digestChars, res, hashLength);
    }
    if (options.outputType === "encoded") {
      return encodeResult(salt, options, res);
    }
    return res;
  });
}
const validateOptions$3 = (options) => {
  var _a2;
  if (!options || typeof options !== "object") {
    throw new Error("Invalid options parameter. It requires an object.");
  }
  if (!options.password) {
    throw new Error("Password must be specified");
  }
  options.password = getUInt8Buffer(options.password);
  if (options.password.length < 1) {
    throw new Error("Password must be specified");
  }
  if (!options.salt) {
    throw new Error("Salt must be specified");
  }
  options.salt = getUInt8Buffer(options.salt);
  if (options.salt.length < 8) {
    throw new Error("Salt should be at least 8 bytes long");
  }
  options.secret = getUInt8Buffer((_a2 = options.secret) !== null && _a2 !== void 0 ? _a2 : "");
  if (!Number.isInteger(options.iterations) || options.iterations < 1) {
    throw new Error("Iterations should be a positive number");
  }
  if (!Number.isInteger(options.parallelism) || options.parallelism < 1) {
    throw new Error("Parallelism should be a positive number");
  }
  if (!Number.isInteger(options.hashLength) || options.hashLength < 4) {
    throw new Error("Hash length should be at least 4 bytes.");
  }
  if (!Number.isInteger(options.memorySize)) {
    throw new Error("Memory size should be specified.");
  }
  if (options.memorySize < 8 * options.parallelism) {
    throw new Error("Memory size should be at least 8 * parallelism.");
  }
  if (options.outputType === void 0) {
    options.outputType = "hex";
  }
  if (!["hex", "binary", "encoded"].includes(options.outputType)) {
    throw new Error(`Insupported output type ${options.outputType}. Valid values: ['hex', 'binary', 'encoded']`);
  }
};
function argon2id$1(options) {
  return __awaiter(this, void 0, void 0, function* () {
    validateOptions$3(options);
    return argon2Internal(Object.assign(Object.assign({}, options), { hashType: "id" }));
  });
}
new Mutex();
new Mutex();
new Mutex();
new Mutex();
new Mutex();
new Mutex();
new Mutex();
new Mutex();
new Mutex();
var name$a = "sha256";
var data$a = "[encoded data, 12920 characters]";
var hash$a = "8c18dd94";
var wasmJson$a = {
  name: name$a,
  data: data$a,
  hash: hash$a
};
new Mutex();
new Mutex();
function createSHA256() {
  return WASMInterface(wasmJson$a, 32).then((wasm) => {
    wasm.init(256);
    const obj = {
      init: () => {
        wasm.init(256);
        return obj;
      },
      update: (data) => {
        wasm.update(data);
        return obj;
      },
      // biome-ignore lint/suspicious/noExplicitAny: Conflict with IHasher type
      digest: (outputType) => wasm.digest(outputType),
      save: () => wasm.save(),
      load: (data) => {
        wasm.load(data);
        return obj;
      },
      blockSize: 64,
      digestSize: 32
    };
    return obj;
  });
}
new Mutex();
new Mutex();
new Mutex();
new Mutex();
new Mutex();
new Mutex();
new Mutex();
function calculateKeyBuffer(hasher, key) {
  const { blockSize } = hasher;
  const buf = getUInt8Buffer(key);
  if (buf.length > blockSize) {
    hasher.update(buf);
    const uintArr = hasher.digest("binary");
    hasher.init();
    return uintArr;
  }
  return new Uint8Array(buf.buffer, buf.byteOffset, buf.length);
}
function calculateHmac(hasher, key) {
  hasher.init();
  const { blockSize } = hasher;
  const keyBuf = calculateKeyBuffer(hasher, key);
  const keyBuffer = new Uint8Array(blockSize);
  keyBuffer.set(keyBuf);
  const opad = new Uint8Array(blockSize);
  for (let i = 0; i < blockSize; i++) {
    const v = keyBuffer[i];
    opad[i] = v ^ 92;
    keyBuffer[i] = v ^ 54;
  }
  hasher.update(keyBuffer);
  const obj = {
    init: () => {
      hasher.init();
      hasher.update(keyBuffer);
      return obj;
    },
    update: (data) => {
      hasher.update(data);
      return obj;
    },
    digest: ((outputType) => {
      const uintArr = hasher.digest("binary");
      hasher.init();
      hasher.update(opad);
      hasher.update(uintArr);
      return hasher.digest(outputType);
    }),
    save: () => {
      throw new Error("save() not supported");
    },
    load: () => {
      throw new Error("load() not supported");
    },
    blockSize: hasher.blockSize,
    digestSize: hasher.digestSize
  };
  return obj;
}
function createHMAC(hash2, key) {
  if (!hash2 || !hash2.then) {
    throw new Error('Invalid hash function is provided! Usage: createHMAC(createMD5(), "key").');
  }
  return hash2.then((hasher) => calculateHmac(hasher, key));
}
function calculatePBKDF2(digest, salt, iterations, hashLength, outputType) {
  return __awaiter(this, void 0, void 0, function* () {
    const DK = new Uint8Array(hashLength);
    const block1 = new Uint8Array(salt.length + 4);
    const block1View = new DataView(block1.buffer);
    const saltBuffer = getUInt8Buffer(salt);
    const saltUIntBuffer = new Uint8Array(saltBuffer.buffer, saltBuffer.byteOffset, saltBuffer.length);
    block1.set(saltUIntBuffer);
    let destPos = 0;
    const hLen = digest.digestSize;
    const l = Math.ceil(hashLength / hLen);
    let T = null;
    let U = null;
    for (let i = 1; i <= l; i++) {
      block1View.setUint32(salt.length, i);
      digest.init();
      digest.update(block1);
      T = digest.digest("binary");
      U = T.slice();
      for (let j = 1; j < iterations; j++) {
        digest.init();
        digest.update(U);
        U = digest.digest("binary");
        for (let k = 0; k < hLen; k++) {
          T[k] ^= U[k];
        }
      }
      DK.set(T.subarray(0, hashLength - destPos), destPos);
      destPos += hLen;
    }
    if (outputType === "binary") {
      return DK;
    }
    const digestChars = new Uint8Array(hashLength * 2);
    return getDigestHex(digestChars, DK, hashLength);
  });
}
const validateOptions$2 = (options) => {
  if (!options || typeof options !== "object") {
    throw new Error("Invalid options parameter. It requires an object.");
  }
  if (!options.hashFunction || !options.hashFunction.then) {
    throw new Error('Invalid hash function is provided! Usage: pbkdf2("password", "salt", 1000, 32, createSHA1()).');
  }
  if (!Number.isInteger(options.iterations) || options.iterations < 1) {
    throw new Error("Iterations should be a positive number");
  }
  if (!Number.isInteger(options.hashLength) || options.hashLength < 1) {
    throw new Error("Hash length should be a positive number");
  }
  if (options.outputType === void 0) {
    options.outputType = "hex";
  }
  if (!["hex", "binary"].includes(options.outputType)) {
    throw new Error(`Insupported output type ${options.outputType}. Valid values: ['hex', 'binary']`);
  }
};
function pbkdf2$1(options) {
  return __awaiter(this, void 0, void 0, function* () {
    validateOptions$2(options);
    const hmac2 = yield createHMAC(options.hashFunction, options.password);
    return calculatePBKDF2(hmac2, options.salt, options.iterations, options.hashLength, options.outputType);
  });
}
var name$3 = "scrypt";
var data$3 = "[encoded data, 6800 characters]";
var hash$3 = "b32721f8";
var wasmJson$3 = {
  name: name$3,
  data: data$3,
  hash: hash$3
};
function scryptInternal(options) {
  return __awaiter(this, void 0, void 0, function* () {
    const { costFactor, blockSize, parallelism, hashLength } = options;
    const SHA256Hasher = createSHA256();
    const blockData = yield pbkdf2$1({
      password: options.password,
      salt: options.salt,
      iterations: 1,
      hashLength: 128 * blockSize * parallelism,
      hashFunction: SHA256Hasher,
      outputType: "binary"
    });
    const scryptInterface = yield WASMInterface(wasmJson$3, 0);
    const VSize = 128 * blockSize * costFactor;
    const XYSize = 256 * blockSize;
    scryptInterface.setMemorySize(blockData.length + VSize + XYSize);
    scryptInterface.writeMemory(blockData, 0);
    scryptInterface.getExports().scrypt(blockSize, costFactor, parallelism);
    const expensiveSalt = scryptInterface.getMemory().subarray(0, 128 * blockSize * parallelism);
    const outputData = yield pbkdf2$1({
      password: options.password,
      salt: expensiveSalt,
      iterations: 1,
      hashLength,
      hashFunction: SHA256Hasher,
      outputType: "binary"
    });
    if (options.outputType === "hex") {
      const digestChars = new Uint8Array(hashLength * 2);
      return getDigestHex(digestChars, outputData, hashLength);
    }
    return outputData;
  });
}
const isPowerOfTwo = (v) => v && !(v & v - 1);
const validateOptions$1 = (options) => {
  if (!options || typeof options !== "object") {
    throw new Error("Invalid options parameter. It requires an object.");
  }
  if (!Number.isInteger(options.blockSize) || options.blockSize < 1) {
    throw new Error("Block size should be a positive number");
  }
  if (!Number.isInteger(options.costFactor) || options.costFactor < 2 || !isPowerOfTwo(options.costFactor)) {
    throw new Error("Cost factor should be a power of 2, greater than 1");
  }
  if (!Number.isInteger(options.parallelism) || options.parallelism < 1) {
    throw new Error("Parallelism should be a positive number");
  }
  if (!Number.isInteger(options.hashLength) || options.hashLength < 1) {
    throw new Error("Hash length should be a positive number.");
  }
  if (options.outputType === void 0) {
    options.outputType = "hex";
  }
  if (!["hex", "binary"].includes(options.outputType)) {
    throw new Error(`Insupported output type ${options.outputType}. Valid values: ['hex', 'binary']`);
  }
};
function scrypt$1(options) {
  return __awaiter(this, void 0, void 0, function* () {
    validateOptions$1(options);
    return scryptInternal(options);
  });
}
new Mutex();
new Mutex();
async function deriveKey$3(parameters, salt, password) {
  const {
    cost,
    keyLength = 32,
    memoryCost = 16384,
    // in KB
    parallelism = 1
  } = parameters;
  return {
    parameters: {
      memoryCost,
      parallelism
    },
    derivedKey: await argon2id$1({
      password,
      salt,
      parallelism,
      iterations: cost,
      memorySize: memoryCost,
      hashLength: keyLength,
      outputType: "binary"
    })
  };
}
const argon2id = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  deriveKey: deriveKey$3
}, Symbol.toStringTag, { value: "Module" }));
function getDigest(algorithm) {
  switch (algorithm) {
    case "PBKDF2/SHA-512":
      return "SHA-512";
    case "PBKDF2/SHA-384":
      return "SHA-384";
    case "PBKDF2/SHA-256":
    default:
      return "SHA-256";
  }
}
async function deriveKey$2(parameters, salt, password) {
  const { algorithm, cost, keyLength = 32 } = parameters;
  const passwordKey = await crypto.subtle.importKey(
    "raw",
    password,
    { name: "PBKDF2" },
    false,
    ["deriveKey"]
  );
  const derivedKey = await crypto.subtle.deriveKey(
    {
      name: "PBKDF2",
      salt,
      iterations: cost,
      hash: getDigest(algorithm)
    },
    passwordKey,
    { name: "AES-GCM", length: keyLength * 8 },
    true,
    ["encrypt"]
  );
  return {
    derivedKey: new Uint8Array(await crypto.subtle.exportKey("raw", derivedKey))
  };
}
const pbkdf2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  deriveKey: deriveKey$2
}, Symbol.toStringTag, { value: "Module" }));
async function deriveKey$1(parameters, salt, password) {
  const { cost, keyLength = 32, memoryCost = 8, parallelism = 1 } = parameters;
  return {
    parameters: {
      memoryCost,
      parallelism
    },
    derivedKey: await scrypt$1({
      password,
      salt,
      blockSize: memoryCost,
      costFactor: cost,
      hashLength: keyLength,
      parallelism,
      outputType: "binary"
    })
  };
}
const scrypt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  deriveKey: deriveKey$1
}, Symbol.toStringTag, { value: "Module" }));
function bufferStartsWith(buffer, prefix) {
  if (prefix.length > buffer.length) {
    return false;
  }
  for (let i = 0; i < prefix.length; i++) {
    if (buffer[i] !== prefix[i]) {
      return false;
    }
  }
  return true;
}
function bufferToHex(buffer) {
  return Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
}
function canonicalJSON(obj) {
  return JSON.stringify(sortKeys(obj));
}
function concatBuffers(a, b) {
  const out = new Uint8Array(a.length + b.length);
  out.set(a, 0);
  out.set(b, a.length);
  return out;
}
function hexToBuffer(hex) {
  if (hex.length % 2 !== 0) {
    throw new Error(`Hex string must have an even length. Got: ${hex}`);
  }
  const buffer = new ArrayBuffer(hex.length / 2);
  const view = new DataView(buffer);
  for (let i = 0; i < hex.length; i += 2) {
    const byteString = hex.substring(i, i + 2);
    const byteValue = parseInt(byteString, 16);
    view.setUint8(i / 2, byteValue);
  }
  return new Uint8Array(buffer);
}
function constantTimeEqual(a, b) {
  if (a.length !== b.length) {
    return false;
  }
  let result = 0;
  for (let i = 0; i < a.length; i++) {
    result |= a.charCodeAt(i) ^ b.charCodeAt(i);
  }
  return result === 0;
}
async function delay(ms) {
  await new Promise((resolve) => setTimeout(resolve, ms));
}
async function hash(algorithm, data) {
  return new Uint8Array(
    await crypto.subtle.digest(
      algorithm.toUpperCase(),
      typeof data === "string" ? new TextEncoder().encode(data) : new Uint8Array(data)
    )
  );
}
async function hmac(algorithm, data, keyStr) {
  const key = await crypto.subtle.importKey(
    "raw",
    new TextEncoder().encode(keyStr),
    {
      name: "HMAC",
      hash: { name: algorithm }
    },
    false,
    ["sign", "verify"]
  );
  const signature = await crypto.subtle.sign(
    "HMAC",
    key,
    typeof data === "string" ? new TextEncoder().encode(data) : data
  );
  return new Uint8Array(signature);
}
function sortKeys(obj) {
  if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
    return obj;
  }
  return Object.keys(obj).sort().reduce((acc, key) => {
    const value = obj[key];
    if (value !== void 0) {
      acc[key] = sortKeys(value);
    }
    return acc;
  }, {});
}
function timeDuration(start) {
  return Math.floor((performance.now() - start) * 10) / 10;
}
async function deriveKey(parameters, salt, password) {
  const { algorithm, keyLength = 32 } = parameters;
  const iterations = Math.max(1, parameters.cost);
  let data = void 0;
  let derivedKey = void 0;
  for (let i = 0; i < iterations; i++) {
    if (i === 0) {
      data = concatBuffers(salt, password);
    } else {
      data = derivedKey;
    }
    derivedKey = new Uint8Array(
      (await crypto.subtle.digest(algorithm, data)).slice(0, keyLength)
    );
  }
  return {
    parameters: {},
    derivedKey
  };
}
const sha = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  deriveKey
}, Symbol.toStringTag, { value: "Module" }));
var HmacAlgorithm = /* @__PURE__ */ ((HmacAlgorithm2) => {
  HmacAlgorithm2["SHA_256"] = "SHA-256";
  HmacAlgorithm2["SHA_384"] = "SHA-384";
  HmacAlgorithm2["SHA_512"] = "SHA-512";
  return HmacAlgorithm2;
})(HmacAlgorithm || {});
class PasswordBuffer {
  constructor(nonce, mode = "uint32") {
    this.nonce = nonce;
    this.mode = mode;
    this.buffer = new Uint8Array(this.nonce.length + this.COUNTER_BYTES);
    this.buffer.set(this.nonce, 0);
    this.dataView = new DataView(this.buffer.buffer);
  }
  nonce;
  mode;
  COUNTER_BYTES = 4;
  buffer;
  dataView;
  encoder = new TextEncoder();
  /**
   * Appends the counter to the nonce buffer.
   * In 'string' mode, encodes the counter as a UTF-8 string.
   * In 'uint32' mode, writes the counter as a big-endian 32-bit integer.
   */
  setCounter(n) {
    if (this.mode === "string") {
      return concatBuffers(this.nonce, this.encoder.encode(n.toString()));
    }
    this.dataView.setUint32(this.nonce.length, n, false);
    return this.buffer;
  }
}
async function createChallenge(options) {
  const {
    algorithm,
    counter,
    counterMode = "uint32",
    cost,
    deriveKey: deriveKey2,
    data,
    expiresAt,
    hmacAlgorithm = HmacAlgorithm.SHA_256,
    hmacKeySignatureSecret,
    hmacSignatureSecret,
    keyLength = 32,
    keyPrefix = "00",
    keyPrefixLength = keyLength / 2,
    memoryCost,
    parallelism
  } = options;
  const parameters = {
    algorithm,
    nonce: bufferToHex(crypto.getRandomValues(new Uint8Array(16))),
    salt: bufferToHex(crypto.getRandomValues(new Uint8Array(16))),
    cost,
    keyLength,
    memoryCost,
    parallelism,
    keyPrefix,
    expiresAt: expiresAt instanceof Date ? Math.floor(expiresAt.getTime() / 1e3) : expiresAt,
    data
  };
  let deriveKeyResult = null;
  if (counter !== void 0) {
    const nonceBuf = hexToBuffer(parameters.nonce);
    deriveKeyResult = await deriveKey2(
      parameters,
      hexToBuffer(parameters.salt),
      new PasswordBuffer(nonceBuf, counterMode).setCounter(counter)
    );
    if (deriveKeyResult.parameters) {
      Object.assign(parameters, deriveKeyResult.parameters);
    }
    parameters.keyPrefix = bufferToHex(deriveKeyResult.derivedKey.slice(0, keyPrefixLength));
  }
  if (!hmacSignatureSecret) {
    return {
      parameters: sortKeys(parameters)
    };
  }
  return signChallenge(
    hmacAlgorithm,
    parameters,
    deriveKeyResult?.derivedKey,
    hmacSignatureSecret,
    hmacKeySignatureSecret
  );
}
async function solveChallenge(options) {
  const {
    challenge,
    controller,
    counterMode = "uint32",
    counterStart = 0,
    counterStep = 1,
    deriveKey: deriveKey2,
    timeout = 9e4
  } = options;
  const { nonce, keyPrefix, salt } = challenge.parameters;
  const nonceBuf = hexToBuffer(nonce);
  const saltBuf = hexToBuffer(salt);
  const keyPrefixBuf = keyPrefix.length % 2 === 0 ? hexToBuffer(keyPrefix) : null;
  const password = new PasswordBuffer(nonceBuf, counterMode);
  const start = performance.now();
  let counter = counterStart;
  let iterations = 0;
  let derivedKeyHex = "";
  let lastYield = start;
  while (true) {
    if (controller?.signal.aborted || timeout && iterations % 10 === 0 && performance.now() - start > timeout) {
      return null;
    }
    const { derivedKey } = await deriveKey2(
      challenge.parameters,
      saltBuf,
      password.setCounter(counter)
    );
    if (iterations % 10 === 0 && performance.now() - lastYield > 200) {
      await delay(0);
      lastYield = performance.now();
    }
    if (keyPrefixBuf ? bufferStartsWith(derivedKey, keyPrefixBuf) : bufferToHex(derivedKey).startsWith(keyPrefix)) {
      derivedKeyHex = bufferToHex(derivedKey);
      break;
    }
    counter = counter + counterStep;
    iterations = iterations + 1;
  }
  return {
    counter,
    derivedKey: derivedKeyHex,
    time: timeDuration(start)
  };
}
async function solveChallengeWorkers(options) {
  const {
    challenge,
    concurrency = navigator.hardwareConcurrency,
    controller = new AbortController(),
    createWorker,
    onOutOfMemory = (c) => c > 1 ? Math.floor(c / 2) : 0,
    counterMode,
    timeout = 9e4
  } = options;
  const workersConcurrency = Math.min(16, Math.max(1, concurrency));
  const workersInstances = [];
  const terminate = () => {
    for (const worker of workersInstances) {
      worker.terminate();
    }
  };
  for (let i = 0; i < workersConcurrency; i++) {
    workersInstances.push(await createWorker(challenge.parameters.algorithm));
  }
  let solution = null;
  try {
    solution = await Promise.race(
      workersInstances.map((worker, i) => {
        controller.signal.addEventListener("abort", () => {
          worker.postMessage({ type: "abort" });
        });
        return new Promise((resolve, reject) => {
          worker.addEventListener("error", (err) => {
            reject(err);
          });
          worker.addEventListener("message", (message) => {
            if (message.data) {
              for (const w of workersInstances) {
                if (w !== worker) {
                  w.postMessage({ type: "abort" });
                }
              }
              if (message.data.error) {
                return reject(new Error(message.data.error));
              }
            }
            resolve(message.data);
          });
          worker.postMessage({
            challenge,
            counterMode,
            counterStart: i,
            counterStep: workersConcurrency,
            timeout,
            type: "work"
          });
        });
      })
    );
  } catch (err) {
    const isOOM = err instanceof Error && !!err?.message?.includes("Out of memory");
    if (isOOM) {
      if (onOutOfMemory) {
        terminate();
        const retryConcurrency = onOutOfMemory(workersConcurrency);
        if (retryConcurrency) {
          return solveChallengeWorkers({
            ...options,
            challenge,
            controller,
            concurrency: retryConcurrency,
            createWorker
          });
        }
      }
    }
    throw err;
  } finally {
    terminate();
  }
  if (controller.signal.aborted) {
    return null;
  }
  return solution || null;
}
async function signChallenge(algorithm, parameters, derivedKey, hmacSignatureSecret, hmacKeySignatureSecret) {
  if (derivedKey && hmacKeySignatureSecret) {
    parameters.keySignature = bufferToHex(
      await hmac(algorithm, derivedKey, hmacKeySignatureSecret)
    );
  }
  parameters = sortKeys(parameters);
  return {
    parameters,
    signature: bufferToHex(await hmac(algorithm, JSON.stringify(parameters), hmacSignatureSecret))
  };
}
async function verifySolution(options) {
  const {
    challenge,
    counterMode,
    deriveKey: deriveKey2,
    hmacAlgorithm = HmacAlgorithm.SHA_256,
    hmacKeySignatureSecret,
    hmacSignatureSecret,
    solution
  } = options;
  const start = performance.now();
  if (challenge.parameters.expiresAt && challenge.parameters.expiresAt < Date.now() / 1e3) {
    return {
      expired: true,
      invalidSignature: null,
      invalidSolution: null,
      time: timeDuration(start),
      verified: false
    };
  }
  if (!challenge.signature) {
    return {
      expired: false,
      invalidSignature: true,
      invalidSolution: null,
      time: timeDuration(start),
      verified: false
    };
  }
  const signatureCheck = bufferToHex(
    await hmac(hmacAlgorithm, canonicalJSON(challenge.parameters), hmacSignatureSecret)
  );
  const signatureVerified = constantTimeEqual(challenge.signature, signatureCheck);
  if (!signatureVerified) {
    return {
      expired: false,
      invalidSignature: true,
      invalidSolution: null,
      time: timeDuration(start),
      verified: false
    };
  }
  if (challenge.parameters.keySignature && hmacKeySignatureSecret) {
    const derivedKeySignatureCheck = bufferToHex(
      await hmac(hmacAlgorithm, hexToBuffer(solution.derivedKey), hmacKeySignatureSecret)
    );
    const derivedKeySignatureValid = constantTimeEqual(
      challenge.parameters.keySignature,
      derivedKeySignatureCheck
    );
    return {
      expired: false,
      invalidSignature: false,
      invalidSolution: !derivedKeySignatureValid,
      time: timeDuration(start),
      verified: derivedKeySignatureValid
    };
  }
  const nonceBuf = hexToBuffer(challenge.parameters.nonce);
  const saltBuf = hexToBuffer(challenge.parameters.salt);
  const { derivedKey } = await deriveKey2(
    challenge.parameters,
    saltBuf,
    new PasswordBuffer(nonceBuf, counterMode).setCounter(solution.counter)
  );
  const derivedKeyHex = bufferToHex(derivedKey);
  const invalidSolution = !constantTimeEqual(derivedKeyHex, solution.derivedKey);
  return {
    expired: false,
    invalidSignature: false,
    invalidSolution,
    time: timeDuration(start),
    verified: !invalidSolution && signatureVerified
  };
}
function parseVerificationData(data, convertToArray = ["fields", "reasons"]) {
  const verificationData = {};
  try {
    const params = new URLSearchParams(data);
    for (const [key, value] of params.entries()) {
      if (value === "true" || value === "false") {
        verificationData[key] = value === "true";
      } else if (value !== null && /^\d+?$/.test(value)) {
        verificationData[key] = parseInt(value, 10);
      } else if (value !== null && /^\d+\.\d+?$/.test(value)) {
        verificationData[key] = parseFloat(value);
      } else if (value !== null) {
        verificationData[key] = convertToArray.includes(key) ? value.trim().split(",") : value.trim();
      }
    }
  } catch {
    return null;
  }
  return verificationData;
}
async function verifyFieldsHash(options) {
  const { algorithm = "SHA-256", formData, fields, fieldsHash } = options;
  const data = formData instanceof FormData ? Object.fromEntries(formData) : formData;
  const lines = [];
  for (const field of fields) {
    lines.push(String(data[field] || ""));
  }
  return bufferToHex(await hash(algorithm, lines.join("\n"))) === fieldsHash;
}
async function verifyServerSignature(options) {
  const { hmacSecret, payload } = options;
  const start = performance.now();
  const signature = bufferToHex(
    await hmac(
      payload.algorithm,
      await hash(payload.algorithm, payload.verificationData),
      hmacSecret
    )
  );
  const verificationData = parseVerificationData(payload.verificationData);
  const expired = !!verificationData && !!verificationData.expire && verificationData.expire < Math.floor(Date.now() / 1e3);
  const invalidSignature = !constantTimeEqual(payload.signature, signature);
  const invalidSolution = !verificationData || verificationData.verified !== true || payload.verified !== true;
  const verified = !expired && !invalidSignature && !invalidSolution;
  return {
    expired,
    invalidSignature,
    invalidSolution,
    time: timeDuration(start),
    verificationData,
    verified
  };
}
export {
  argon2id,
  createChallenge,
  parseVerificationData,
  pbkdf2,
  scrypt,
  sha,
  solveChallenge,
  solveChallengeWorkers,
  verifyFieldsHash,
  verifyServerSignature,
  verifySolution
};
