visionary-base64url
Version:
A lightweight, zero-dependency base64url converter for Node.js, web browsers, and worker environments. Safely encodes emojis and unicode into URL-safe base64.
79 lines (78 loc) • 2.47 kB
JavaScript
// src/runtime.ts
var cachedRuntime = null;
var detectRuntime = () => {
if (typeof Buffer !== "undefined" && typeof Buffer.from === "function") {
return "buffer";
}
if (typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined" && typeof btoa === "function" && typeof atob === "function") {
return "text-encoding";
}
throw new Error("No UTF-8 base64 implementation available");
};
var getRuntime = () => {
if (cachedRuntime === null) {
cachedRuntime = detectRuntime();
}
return cachedRuntime;
};
var bytesToBinaryString = (bytes) => {
let binary = "";
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return binary;
};
var binaryStringToBytes = (binary) => {
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
};
var padBase64 = (base64) => {
const remainder = base64.length % 4;
if (remainder === 0) {
return base64;
}
return base64 + "=".repeat(4 - remainder);
};
var encodeWithBuffer = (input) => Buffer.from(input, "utf8").toString("base64");
var decodeWithBuffer = (input) => Buffer.from(input, "base64").toString("utf8");
var encodeWithTextEncoding = (input) => btoa(bytesToBinaryString(new TextEncoder().encode(input)));
var decodeWithTextEncoding = (input) => new TextDecoder().decode(binaryStringToBytes(atob(padBase64(input))));
var utf8ToBase64 = (input) => {
switch (getRuntime()) {
case "buffer":
return encodeWithBuffer(input);
case "text-encoding":
return encodeWithTextEncoding(input);
}
};
var base64ToUtf8 = (input) => {
switch (getRuntime()) {
case "buffer":
return decodeWithBuffer(input);
case "text-encoding":
return decodeWithTextEncoding(input);
}
};
// src/index.ts
var encodeBase64Url = (input) => {
if (typeof input !== "string") {
throw new Error("encodeBase64Url: input must be a string");
}
return toBase64Url(utf8ToBase64(input));
};
var decodeBase64Url = (input) => {
if (typeof input !== "string") {
throw new Error("decodeBase64Url: input must be a string");
}
return base64ToUtf8(fromBase64Url(input));
};
var toBase64Url = (base64) => base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
var fromBase64Url = (base64Url) => base64Url.replace(/-/g, "+").replace(/_/g, "/");
export {
decodeBase64Url,
encodeBase64Url
};
//# sourceMappingURL=index.js.map