From 914cdea41db9a6e844d7f38c06445b43bcf22df0 Mon Sep 17 00:00:00 2001 From: ergunsh Date: Fri, 10 Sep 2021 14:45:20 +0200 Subject: [PATCH] Return encode result from `Image.encode` calls Before this, there were one way to use the API: call `await image.encode({ mozjpeg: {} })` then use `encodedWith` by asserting that `mozjpeg` property exists on it After adding return value to encode, people will be able to use it like `const { mozjpeg } = await image.encode({ mozjpeg: {} });` which provides better type safety --- libsquoosh/src/index.ts | 22 ++++++++++++---------- 1 file changed, 12 insertions(+), 10 deletions(-) diff --git a/libsquoosh/src/index.ts b/libsquoosh/src/index.ts index cc4fe1af..04792394 100644 --- a/libsquoosh/src/index.ts +++ b/libsquoosh/src/index.ts @@ -32,6 +32,14 @@ type EncodeResult = { extension: string; size: number; }; +type EncoderOptions = { + mozjpeg?: Partial; + webp?: Partial; + avif?: Partial; + jxl?: Partial; + wp2?: Partial; + oxipng?: Partial; +}; async function decodeFile({ file, @@ -221,19 +229,12 @@ class Image { * @param {object} encodeOptions - An object with encoders to use, and their settings. * @returns {Promise} - A promise that resolves when the image has been encoded with all the specified encoders. */ - async encode( + async encode( encodeOptions: { optimizerButteraugliTarget?: number; maxOptimizerRounds?: number; - } & { - mozjpeg?: Partial; - webp?: Partial; - avif?: Partial; - jxl?: Partial; - wp2?: Partial; - oxipng?: Partial; - } = {}, - ): Promise { + } & T, + ): Promise<{ [key in keyof T]: EncodeResult }> { const { bitmap } = await this.decoded; for (const [name, options] of Object.entries(encodeOptions)) { if (!Object.keys(encoders).includes(name)) { @@ -257,6 +258,7 @@ class Image { }); } await Promise.all(Object.values(this.encodedWith)); + return this.encodedWith as { [key in keyof T]: EncodeResult }; } }