page-bundle.mjs
16 lines · archify/explainer/page-bundle.mjs at a406594
1import { gzipSync, gunzipSync } from 'node:zlib';
3// The native Viewer HTML is needed only when a reader opens "Explore", so the page stores it
4// gzip-compressed and the reader inflates it on demand. Keys keep their order, so the prepared
5// bundle digest is computed and verified over the same unpacked JSON.
6const swap = (bundle, from, to, convert) => {
7 const diagrams = bundle?.preparedDiagrams?.diagrams;
8 if (!diagrams || typeof diagrams !== 'object') return bundle;
9 return { ...bundle, preparedDiagrams: { ...bundle.preparedDiagrams, diagrams: Object.fromEntries(Object.entries(diagrams).map(([id, child]) =>
10 [id, child && typeof child[from] === 'string' ? Object.fromEntries(Object.entries(child).map(([key, value]) => key === from ? [to, convert(value)] : [key, value])) : child])) } };
11};
13export const packPageBundle = bundle => swap(bundle, 'html', 'htmlGzip', html => gzipSync(html, { level: 9 }).toString('base64'));
15/** Accepts packed and older unpacked pages alike. */
16export const unpackPageBundle = bundle => swap(bundle, 'htmlGzip', 'html', data => gunzipSync(Buffer.from(data, 'base64')).toString('utf8'));