(function (Drupal) {
  'use strict';

  Drupal.moWebAuthnUtility = {
    /**
     * Convert URL encoded base64 string to base64 string.
     *
     * @param {string} base64url
     *   Target string.
     *
     * @return {Uint8Array}
     *   Convert base64 string.
     */
     base64urlToUint8Array (base64url) {
      let base64 = base64url.replace(/-/g, '+').replace(/_/g, '/').replace(/=/g, '');
      const pad = base64.length % 4;
      if (pad) {
        if (pad === 1) throw new Error('Invalid base64url string');
        base64 += '='.repeat(4 - pad);
      }
      const binary = window.atob(base64);
      return Uint8Array.from(binary, (c) => c.charCodeAt(0));
    },

    /**
     * Convert array to base64 string.
     *
     *   Target Array.
     *
     * @return {string}
     *   Convert base64 string.
     * @param buffer
     */
    uint8ArrayToBase64url (buffer) {
      return btoa(String.fromCharCode(...new Uint8Array(buffer)))
        .replace(/\+/g, '-')
        .replace(/\//g, '_')
        .replace(/=/g, '');
    }
  };
})(Drupal);
