BlueGit

timfa posprint

Files

posprint / lib / browser / posprint_url.js

posprint_url.js

posprint_url.js 1.6 KiB Download Raw
1/**
2 * Build a posprint:// URL from a .pos document (object or JSON string).
3 *
4 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
5 * Requires CompressionStream('deflate-raw') (modern browsers).
6 *
7 * @param {object|string} pos
8 * @param {{ noconfirm?: boolean, origin?: string }} [options]
9 * @returns {Promise<string>}
10 */
11export async function posprintUrl(pos, options = {}) {
12 const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
13 if (typeof CompressionStream === 'undefined') {
14 throw new Error("CompressionStream('deflate-raw') is not available in this browser");
15 }
16
17 const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
18 const buffer = await new Response(stream).arrayBuffer();
19 const b64 = bytesToBase64Url(new Uint8Array(buffer));
20 let url = `posprint://print?v=1&d=${b64}`;
21 if (options.noconfirm) {
22 url += '&noconfirm=1';
23 }
24 if (options.origin) {
25 const host = normalizeOrigin(options.origin);
26 if (host) {
27 url += `&origin=${encodeURIComponent(host)}`;
28 }
29 }
30 return url;
31}
32
33function normalizeOrigin(raw) {
34 const s = String(raw).trim();
35 if (!s) return null;
36 try {
37 if (/^https?:\/\//i.test(s)) {
38 return new URL(s).hostname.toLowerCase();
39 }
40 } catch (_) {
41 /* fall through */
42 }
43 return s.split('/')[0].split(':')[0].toLowerCase() || null;
44}
45
46function bytesToBase64Url(bytes) {
47 let binary = '';
48 for (let i = 0; i < bytes.length; i++) {
49 binary += String.fromCharCode(bytes[i]);
50 }
51 const b64 = btoa(binary);
52 return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
53}