/** * Build a posprint:// URL from a .pos document (object or JSON string). * * Encoding: UTF-8 JSON → raw deflate → base64url (no padding). * Requires CompressionStream('deflate-raw') (modern browsers). * * @param {object|string} pos * @param {{ noconfirm?: boolean, origin?: string }} [options] * @returns {Promise} */ export async function posprintUrl(pos, options = {}) { const json = typeof pos === 'string' ? pos : JSON.stringify(pos); if (typeof CompressionStream === 'undefined') { throw new Error("CompressionStream('deflate-raw') is not available in this browser"); } const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw')); const buffer = await new Response(stream).arrayBuffer(); const b64 = bytesToBase64Url(new Uint8Array(buffer)); let url = `posprint://print?v=1&d=${b64}`; if (options.noconfirm) { url += '&noconfirm=1'; } if (options.origin) { const host = normalizeOrigin(options.origin); if (host) { url += `&origin=${encodeURIComponent(host)}`; } } return url; } function normalizeOrigin(raw) { const s = String(raw).trim(); if (!s) return null; try { if (/^https?:\/\//i.test(s)) { return new URL(s).hostname.toLowerCase(); } } catch (_) { /* fall through */ } return s.split('/')[0].split(':')[0].toLowerCase() || null; } function bytesToBase64Url(bytes) { let binary = ''; for (let i = 0; i < bytes.length; i++) { binary += String.fromCharCode(bytes[i]); } const b64 = btoa(binary); return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); }