From e67dd99261dba45c2f8598ad042ab72bf6b7782f Mon Sep 17 00:00:00 2001
From: Cheng Shao <terrorjack@type.dance>
Date: Tue, 25 Mar 2025 10:39:08 +0000
Subject: [PATCH] wasm: add brotli compression for ghci browser mode

This commit adds brotli compression for wasm shared libraries for ghci
browser mode. With BROTLI_MIN_QUALITY, the overhead is negligible, and
it helps reducing amount of transferred data when the browser connects
to the server over a slow connection.

(cherry picked from commit 731217ce68a1093b5f9e26a07d5bd2cdade2b352)
---
 utils/jsffi/dyld.mjs | 15 +++++++++++++--
 1 file changed, 13 insertions(+), 2 deletions(-)

diff --git a/utils/jsffi/dyld.mjs b/utils/jsffi/dyld.mjs
index e068f54239a..7c6f7688d4f 100755
--- a/utils/jsffi/dyld.mjs
+++ b/utils/jsffi/dyld.mjs
@@ -277,7 +277,7 @@ const isNode = Boolean(globalThis?.process?.versions?.node);
 // factor out browser-only/node-only logic into different modules. For
 // now, just make these global let bindings optionally initialized if
 // isNode and be careful to not use them in browser-only logic.
-let fs, http, path, require, stream, wasi, ws;
+let fs, http, path, require, stream, util, wasi, ws, zlib;
 
 if (isNode) {
   require = (await import("node:module")).createRequire(import.meta.url);
@@ -286,7 +286,9 @@ if (isNode) {
   http = require("http");
   path = require("path");
   stream = require("stream");
+  util = require("util");
   wasi = require("wasi");
+  zlib = require("zlib");
 
   // Optional npm dependencies loaded via NODE_PATH
   try {
@@ -558,8 +560,17 @@ args.rpc.opened.then(() => main(args));
           return;
         }
 
+        res.setHeader("Content-Encoding", "br");
+
         res.writeHead(200);
-        res.end(buf);
+        res.end(
+          await util.promisify(zlib.brotliCompress)(buf, {
+            params: {
+              [zlib.constants.BROTLI_PARAM_QUALITY]:
+                zlib.constants.BROTLI_MIN_QUALITY,
+            },
+          })
+        );
         return;
       }
 
-- 
GitLab