@zokki/astro-brotli
Version:
brotli compression for astro static sites
78 lines (76 loc) • 3.26 kB
JavaScript
;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
brotli: () => brotli
});
module.exports = __toCommonJS(src_exports);
var import_integration_utils = require("@zokki/integration-utils");
var import_glob = require("glob");
var import_node_fs = require("fs");
var import_node_stream = require("stream");
var import_node_url = require("url");
var import_node_zlib = require("zlib");
var defaultExtension = ["css", "js", "html", "xml", "cjs", "mjs", "svg", "txt"];
var brotli = (config) => ({
name: "@zokki/brotli",
hooks: {
"astro:build:done": async ({ dir, logger }) => {
const outDir = (0, import_node_url.fileURLToPath)(dir);
const extensionsToCompress = config?.extensions ?? defaultExtension;
const brotliOptions = {
...config?.brotliOptions,
params: { [import_node_zlib.constants.BROTLI_PARAM_QUALITY]: 11, ...config?.brotliOptions?.params }
};
let originalSizeSum = 0;
let compressedSizeSum = 0;
await (0, import_glob.glob)(`${outDir}**/*.{${extensionsToCompress.join(",")}}`).then(
(files) => Promise.all(
files.map(async (file) => {
const brotliFile = `${file}.br`;
const read = (0, import_node_fs.createReadStream)(file);
const write = (0, import_node_fs.createWriteStream)(brotliFile);
const brotli2 = (0, import_node_zlib.createBrotliCompress)(brotliOptions);
await import_node_stream.promises.pipeline(read, brotli2, write);
const originalSize = read.bytesRead;
const compressedSize = write.bytesWritten;
originalSizeSum += originalSize;
compressedSizeSum += compressedSize;
if (config?.logAllFiles !== false) {
const relativePath = brotliFile.replace(outDir, "/").padEnd(45);
const reductionStr = (0, import_integration_utils.reductionMessage)(originalSize, compressedSize);
logger.info(`${relativePath} ${reductionStr}`);
}
})
)
);
if (originalSizeSum) {
const reduction = (0, import_integration_utils.reductionMessage)(originalSizeSum, compressedSizeSum);
logger.info(`Brotli completed successfully! (total reduction: ${reduction})`);
} else {
logger.info("Nothing were compressed with brotli.");
}
}
}
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
brotli
});