1 | "use strict";
|
2 | Object.defineProperty(exports, "__esModule", { value: true });
|
3 | const zlib_1 = require("zlib");
|
4 | const stream_1 = require("stream");
|
5 | const fs_1 = require("fs");
|
6 | const util_1 = require("util");
|
7 | const duplexer = require('duplexer');
|
8 | const readFilePromise = util_1.promisify(fs_1.readFile);
|
9 | const bufferFormatter = (incoming) => typeof incoming === 'string' ? Buffer.from(incoming, 'utf8') : incoming;
|
10 | const optionFormatter = (passed, toEncode) => ({
|
11 | params: {
|
12 | [zlib_1.constants.BROTLI_PARAM_MODE]: passed && 'mode' in passed && passed.mode || zlib_1.constants.BROTLI_DEFAULT_MODE,
|
13 | [zlib_1.constants.BROTLI_PARAM_QUALITY]: passed && 'quality' in passed && passed.quality || zlib_1.constants.BROTLI_MAX_QUALITY,
|
14 | [zlib_1.constants.BROTLI_PARAM_SIZE_HINT]: toEncode ? toEncode.byteLength : 0,
|
15 | }
|
16 | });
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 | async function size(incoming, options) {
|
23 | const buffer = bufferFormatter(incoming);
|
24 | return new Promise(function (resolve, reject) {
|
25 | zlib_1.brotliCompress(buffer, optionFormatter(options, buffer), (error, result) => {
|
26 | if (error !== null) {
|
27 | reject(error);
|
28 | }
|
29 | resolve(result.byteLength);
|
30 | });
|
31 | });
|
32 | }
|
33 | exports.default = size;
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | function sync(incoming, options) {
|
40 | const buffer = bufferFormatter(incoming);
|
41 | return zlib_1.brotliCompressSync(buffer, optionFormatter(options, buffer)).byteLength;
|
42 | }
|
43 | exports.sync = sync;
|
44 |
|
45 |
|
46 |
|
47 |
|
48 | function stream(options) {
|
49 | const input = new stream_1.PassThrough();
|
50 | const output = new stream_1.PassThrough();
|
51 | const wrapper = duplexer(input, output);
|
52 | let size = 0;
|
53 | const brotli = zlib_1.createBrotliCompress(optionFormatter(options))
|
54 | .on('data', buf => {
|
55 | size += buf.length;
|
56 | })
|
57 | .on('error', () => {
|
58 | wrapper.brotliSize = 0;
|
59 | })
|
60 | .on('end', () => {
|
61 | wrapper.brotliSize = size;
|
62 | wrapper.emit('brotli-size', size);
|
63 | output.end();
|
64 | });
|
65 | input.pipe(brotli);
|
66 | input.pipe(output, { end: false });
|
67 | return wrapper;
|
68 | }
|
69 | exports.stream = stream;
|
70 |
|
71 |
|
72 |
|
73 |
|
74 |
|
75 | async function file(path, options) {
|
76 | const file = await readFilePromise(path);
|
77 | return (await size(file, options));
|
78 | }
|
79 | exports.file = file;
|
80 |
|
81 |
|
82 |
|
83 |
|
84 |
|
85 | function fileSync(path, options) {
|
86 | const file = fs_1.readFileSync(path);
|
87 | return sync(file, options);
|
88 | }
|
89 | exports.fileSync = fileSync;
|
90 |
|
\ | No newline at end of file |