siteEncoded

tcmts.cli.sync.siteEncoded · #kwuzsne7 · term · runs on the server

uses node:zlib

data (a file of a site, digest its SHA-256) as encoding ("br" or "gzip"): compressed once, then remembered. Undefined for what isn't worth it: not text, too small, or no smaller compressed.

import { SITE_COMPRESSED_LIMIT, siteCompressed } from "#codebase/tcmts/cli/sync";
import { COMPRESSIBLE } from "#codebase/tcmts/cli/web";
import zlib from "node:zlib";

export function siteEncoded(
  ext: string,
  data: Buffer,
  digest: string,
  encoding: "br" | "gzip",
): Buffer | undefined {
  if (!COMPRESSIBLE.has(ext) || data.length < 128) return undefined;
  const key = `${digest} ${encoding}`;
  let packed = siteCompressed.get(key);
  if (!packed) {
    packed =
      encoding === "br"
        ? zlib.brotliCompressSync(data, {
            params: {
              [zlib.constants.BROTLI_PARAM_QUALITY]: 6,
              [zlib.constants.BROTLI_PARAM_SIZE_HINT]: data.length,
            },
          })
        : zlib.gzipSync(data, { level: 6 });
    siteCompressed.set(key, packed);
    let total = 0;
    for (const v of siteCompressed.values()) total += v.length;
    for (const [k, v] of siteCompressed) {
      if (total <= SITE_COMPRESSED_LIMIT) break;
      siteCompressed.delete(k);
      total -= v.length;
    }
  }
  return packed.length < data.length ? packed : undefined;
}

uses

used by