import brotliInit, { compress, decompress } from "./vendor/brotli_wasm.js"; import base from "./vendor/base-x.js"; const COMPRESS_WAIT = 500; const ENCODER = new TextEncoder(); const DECODER = new TextDecoder(); const BASE66 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~"; const BASE66CODEC = base(BASE66); const QUALITY = 11; const MAX_URL = 2048; let brotli; let compressTimeout = null; let rootURLSize = 0; /** * Returns a promise that is resolved when page is loaded enough to run JavaScripts. */ function waitForLoad() { return new Promise(resolve => { // If already loaded, fire immediately if (/complete|interactive|loaded/.test(document.readyState)) { resolve(); } else { document.addEventListener('DOMContentLoaded', resolve); } }); } function maxHashLength() { if (rootURLSize === 0) { const rootURL = new URL(window.location.href); rootURL.hash = ""; rootURLSize = rootURL.toString().length; } return MAX_URL - rootURLSize - 1; } async function init() { brotli = await brotliInit(); const codeEl = document.getElementById("code"); const lengthEl = document.getElementById("length"); codeEl.addEventListener("input", () => { if (compressTimeout) { clearTimeout(compressTimeout); } if (codeEl.value === "") { history.replaceState(null, "", "#"); lengthEl.textContent = "Waiting..."; return; } compressTimeout = setTimeout(async () => { const content = codeEl.value; const compressed = compress(ENCODER.encode(content), { quality: QUALITY }); const encoded = BASE66CODEC.encode(compressed); lengthEl.textContent = `Length: ${content.length} chars -> ${compressed.length} bytes -> ${encoded.length}/${maxHashLength()} chars`; if (encoded.length <= maxHashLength()) { history.replaceState(null, "", `#${encoded}`); } else { lengthEl.textContent += " (TOO BIG!)"; } }, COMPRESS_WAIT); }); if (window.location.hash.length > 1) { try { const bytes = BASE66CODEC.decode(window.location.hash.substring(1)); const decompressed = decompress(bytes); const content = DECODER.decode(decompressed); codeEl.textContent = content; } catch (e) { codeEl.textContent = e.stack; } } } await waitForLoad(); await init();