Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
add compress to builder
  • Loading branch information
enBonnet committed Aug 4, 2022
commit ba07a7dac9185e71fb8a2943352ede899cd466cd
46 changes: 46 additions & 0 deletions packages/kit/src/core/adapt/builder.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import glob from 'tiny-glob';
import zlib from 'zlib';
import { existsSync, statSync, createReadStream, createWriteStream } from 'fs';
import { pipeline } from 'stream';
import { promisify } from 'util';
import { copy, rimraf, mkdirp } from '../../utils/filesystem.js';
import { generate_manifest } from '../generate_manifest/index.js';

Expand Down Expand Up @@ -25,6 +30,30 @@ export function create_builder({ config, build_data, prerendered, log }) {
return true;
}

const pipe = promisify(pipeline);

/**
* @param {string} file
* @param {'gz' | 'br'} format
*/
async function compress_file(file, format = 'gz') {
const compress =
format == 'br'
? zlib.createBrotliCompress({
params: {
[zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT,
[zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
[zlib.constants.BROTLI_PARAM_SIZE_HINT]: statSync(file).size
}
})
: zlib.createGzip({ level: zlib.constants.Z_BEST_COMPRESSION });

const source = createReadStream(file);
const destination = createWriteStream(`${file}.${format}`);

await pipe(source, compress, destination);
}

return {
log,
rimraf,
Expand Down Expand Up @@ -151,6 +180,23 @@ export function create_builder({ config, build_data, prerendered, log }) {
);
},

async compress(directory) {
if (!existsSync(directory)) {
return;
}

const files = await glob('**/*.{html,js,json,css,svg,xml,wasm}', {
cwd: directory,
dot: true,
absolute: true,
filesOnly: true
});

await Promise.all(
files.map((file) => Promise.all([compress_file(file, 'gz'), compress_file(file, 'br')]))
);
},

async prerender() {
throw new Error(
'builder.prerender() has been removed. Prerendering now takes place in the build phase — see builder.prerender and builder.writePrerendered'
Expand Down
5 changes: 5 additions & 0 deletions packages/kit/types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,11 @@ export interface Builder {
replace?: Record<string, string>;
}
): string[];

/**
* @param {string} directory A path to file that would be compress.
Comment thread
enBonnet marked this conversation as resolved.
Outdated
*/
compress(directory: string): void;
}

export interface Config {
Expand Down