export function toBase64Url(buf) {
  if (buf == null) return ''
  if (typeof buf === 'string') return buf
  const b = Buffer.isBuffer(buf) ? buf : Buffer.from(buf)
  // Node supports 'base64url' on recent versions; keep fallback for safety.
  try {
    return b.toString('base64url')
  } catch {
    return b
      .toString('base64')
      .replace(/\+/g, '-')
      .replace(/\//g, '_')
      .replace(/=+$/g, '')
  }
}

export function fromBase64Url(s) {
  if (!s) return Buffer.alloc(0)
  // Node supports 'base64url' on recent versions; keep fallback for safety.
  try {
    return Buffer.from(String(s), 'base64url')
  } catch {
    let v = String(s).replace(/-/g, '+').replace(/_/g, '/')
    while (v.length % 4) v += '='
    return Buffer.from(v, 'base64')
  }
}

export function parseClientDataJSON(clientDataJSONB64Url) {
  const json = fromBase64Url(clientDataJSONB64Url).toString('utf8')
  return JSON.parse(json)
}


