Skip to content

Instantly share code, notes, and snippets.

@xantiagoma
Created January 10, 2026 03:17
Show Gist options
  • Select an option

  • Save xantiagoma/3247e3540c2c81e3c39fb9e59b608c40 to your computer and use it in GitHub Desktop.

Select an option

Save xantiagoma/3247e3540c2c81e3c39fb9e59b608c40 to your computer and use it in GitHub Desktop.
const Base64 = (() => {
const STD =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
const URL =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_';
// Reverse lookup that accepts BOTH base64 and base64url chars
const REV = new Int16Array(128).fill(-1);
for (let i = 0; i < 64; i++) {
REV[STD.charCodeAt(i)] = i;
REV[URL.charCodeAt(i)] = i;
}
function encode(bytes, { urlSafe = false, pad = true } = {}) {
// Fast path: Node (and some bundler/browser envs) may have Buffer
if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
const b64 = Buffer.from(bytes).toString('base64');
const out = urlSafe ? b64.replace(/\+/g, '-').replace(/\//g, '_') : b64;
return pad ? out : out.replace(/=+$/g, '');
}
const abc = urlSafe ? URL : STD;
let out = '';
const len = bytes.length;
for (let i = 0; i < len; i += 3) {
const b0 = bytes[i];
const b1 = i + 1 < len ? bytes[i + 1] : 0;
const b2 = i + 2 < len ? bytes[i + 2] : 0;
const n = (b0 << 16) | (b1 << 8) | b2;
out += abc[(n >>> 18) & 63];
out += abc[(n >>> 12) & 63];
out += i + 1 < len ? abc[(n >>> 6) & 63] : pad ? '=' : '';
out += i + 2 < len ? abc[n & 63] : pad ? '=' : '';
}
return pad ? out : out.replace(/=+$/g, '');
}
function decode(str) {
// Fast path: Buffer
if (typeof Buffer !== 'undefined' && typeof Buffer.from === 'function') {
// Buffer doesn't accept raw base64url reliably in older nodes, normalize first
let b64 = str.replace(/-/g, '+').replace(/_/g, '/');
b64 += '==='.slice((b64.length + 3) % 4);
return new Uint8Array(Buffer.from(b64, 'base64'));
}
// Pure JS decode (accepts base64 or base64url, with or without padding)
let s = str.trim();
// restore padding if missing
s += '==='.slice((s.length + 3) % 4);
const out = [];
for (let i = 0; i < s.length; i += 4) {
const c0 = s.charCodeAt(i);
const c1 = s.charCodeAt(i + 1);
const c2 = s.charCodeAt(i + 2);
const c3 = s.charCodeAt(i + 3);
const v0 = c0 === 61 ? -1 : REV[c0]; // '='
const v1 = c1 === 61 ? -1 : REV[c1];
const v2 = c2 === 61 ? -1 : REV[c2];
const v3 = c3 === 61 ? -1 : REV[c3];
if (v0 < 0 || v1 < 0 || (v2 < 0 && c2 !== 61) || (v3 < 0 && c3 !== 61)) {
throw new Error('Invalid base64/base64url input');
}
const n = (v0 << 18) | (v1 << 12) | ((v2 & 63) << 6) | (v3 & 63);
out.push((n >>> 16) & 255);
if (c2 !== 61) out.push((n >>> 8) & 255);
if (c3 !== 61) out.push(n & 255);
}
return new Uint8Array(out);
}
return { encode, decode };
})();
function uuidToB64Url(uuid) {
// "587a7cd1-e4e4-43e9-9392-03103dcd5500" -> "WHp80eTkQ-mTkgMQPc1VAA"
const hex = uuid.replace(/-/g, '');
if (!/^[0-9a-fA-F]{32}$/.test(hex)) throw new Error('Invalid UUID');
const bytes = new Uint8Array(16);
for (let i = 0; i < 16; i++)
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
return Base64.encode(bytes, { urlSafe: true, pad: false });
}
function b64UrlToUuid(b64url) {
// "WHp80eTkQ-mTkgMQPc1VAA" -> "587a7cd1-e4e4-43e9-9392-03103dcd5500"
const bytes = Base64.decode(b64url);
if (bytes.length !== 16)
throw new Error(`Decoded length ${bytes.length} != 16; not UUID-bytes`);
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(
''
);
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(
12,
16
)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment