// TEST-ONLY shim. Node/vitest's crypto.subtle has no `timingSafeEqual` (a CF
// Workers extension), so install a functional stand-in for tests. This proves the
// production helper's length-guard + subtle.timingSafeEqual *call path* under vitest;
// it is NOT the production primitive (constant-time is the CF-native helper's job,
// which stays byte-identical — never branched for the test env). Uses only DOM/ES
// globals (Uint8Array) so it typechecks without @types/node, and never ships (tsdown
// builds explicit entries index/server only — this file is not one).
// On byteLength mismatch it THROWS a RangeError, faithfully mirroring CF-native
// (and node:crypto) timingSafeEqual, which rejects unequal-length inputs. This is
// load-bearing: it pins the production length-guard — delete that guard and a
// wrong-length secret reaches the shim, throws, and the "rejects short" test fails.
const subtle = globalThis.crypto.subtle as SubtleCrypto & {
  timingSafeEqual?: (a: ArrayBufferView, b: ArrayBufferView) => boolean
}
subtle.timingSafeEqual ??= (a, b) => {
  const av = new Uint8Array(a.buffer, a.byteOffset, a.byteLength)
  const bv = new Uint8Array(b.buffer, b.byteOffset, b.byteLength)
  if (av.length !== bv.length) {
    throw new RangeError('Input buffers must have the same byte length')
  }
  let diff = 0
  for (let i = 0; i < av.length; i++) diff |= av[i]! ^ bv[i]!
  return diff === 0
}
