Skip to content

Commit

Permalink
Image set generator library migrated to class approach, Terminate uti…
Browse files Browse the repository at this point in the history
…l funtion added and replaced every error exits.
  • Loading branch information
darsan-in committed Dec 16, 2024
1 parent a07882f commit 38969f9
Show file tree
Hide file tree
Showing 13 changed files with 762 additions and 703 deletions.
6 changes: 4 additions & 2 deletions bin/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
minomax,
} from "../minomax";

import { terminate } from "lib/utils";
import iconAssociator from "./iconAssociator";
import initConfig from "./initConfig";

Expand Down Expand Up @@ -178,8 +179,9 @@ program

await iconAssociator();
} catch (err) {
console.error("⚠️ Error initializing icon associations:", err);
process.exit(1);
terminate({
reason: "⚠️ Error initializing icon associations:\t" + err,
});
}
});

Expand Down
4 changes: 2 additions & 2 deletions bin/iconAssociator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { readFile, writeFile } from "fs/promises";
import { terminate } from "lib/utils";
import { copyFileSync, mkdirSync } from "node:fs";
import { dirname, join } from "node:path";

Expand Down Expand Up @@ -95,7 +96,6 @@ function copyMinomaxIcon(): void {
mkdirSync(dirname(destPath), { recursive: true });
copyFileSync(source, destPath);
} catch (err) {
console.log("Error copying icon: ", err);
process.exit(1);
terminate({ reason: "Error copying icon: " + err });
}
}
4 changes: 2 additions & 2 deletions configLoader.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { terminate } from "lib/utils";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { ConfigurationOptions } from "./lib/types";
Expand All @@ -16,8 +17,7 @@ export default function loadConfig(): ConfigurationOptions {
try {
projectConfig = require(projectConfigFile).default;
} catch (err) {
console.log("Error while loading settings\n", err);
process.exit(1);
terminate({ reason: "Error while loading settings\n" + err });
}
}

Expand Down
27 changes: 13 additions & 14 deletions lib/core/image.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
SvgOptions,
WebpEncodeOptions,
} from "../types";
import { currentTime, logWriter, makeDirf } from "../utils";
import { currentTime, logWriter, makeDirf, terminate } from "../utils";

class _SVGWorker {
#cpuAllocation: number;
Expand Down Expand Up @@ -96,8 +96,7 @@ class _SVGWorker {
try {
await this.#_svgBatchHandler(outputPromises);
} catch (err: any) {
console.log("Error while batch processing\n", err);
process.exit(1);
terminate({ reason: "Error while batch processing\n" + err });
}
}
}
Expand Down Expand Up @@ -266,8 +265,9 @@ export default class ImageWorker {
destinationBasePath: string = this.#destPath,
): Promise<void> {
process.on("SIGINT", () => {
console.log("User interrupted encoding process. Shutting down....");
process.exit(1);
terminate({
reason: "User interrupted encoding process. Shutting down....",
});
});

console.log(`Number of images: ${imagePaths.length}`);
Expand All @@ -285,8 +285,7 @@ export default class ImageWorker {
`[${currentTime()}] ===> ✅ Images are optimised with SVG format.`,
);
} catch (err) {
console.log("❌ SVG optimization failed", err);
process.exit(1);
terminate({ reason: "❌ SVG optimization failed" + err });
}
} else {
const encodeOptions:
Expand All @@ -303,8 +302,9 @@ export default class ImageWorker {
: false;

if (!encodeOptions) {
console.error("❌ Provided image extension is unsupported");
process.exit(1);
terminate({
reason: "❌ Provided image extension is unsupported",
});
}

try {
Expand All @@ -317,11 +317,10 @@ export default class ImageWorker {
`[${currentTime()}] ===> ✅ Images are optimised with ${targetFormat.toUpperCase()} format.`,
);
} catch (error) {
console.error(
"❌ Something wrong occurred while encoding images\n",
error,
);
process.exit(1);
terminate({
reason:
"❌ Something wrong occurred while encoding images\n" + error,
});
}
}
}
Expand Down
148 changes: 72 additions & 76 deletions lib/core/imageset/imageset.lib/cssrender.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,58 @@
import puppeteer, { Browser } from "puppeteer";
import puppeteer, { type Browser, Page } from "puppeteer";
import { ImageSizeResponse } from "../../../types";

export function getImageSize(
async function _closeBrowser(browser: Browser) {
if (browser) {
try {
// Adding a slight delay before closing the browser
await new Promise((resolve) => setTimeout(resolve, 1000));
await browser.close();
} catch (err) {
console.error("Error closing browser:", err);
}
}
}

function _getImageSize({
page,
screenWidth,
selector,
}: {
page: Page;
screenWidth: number;
selector: string;
}): Promise<ImageSizeResponse> {
return new Promise(async (resolve, reject) => {
try {
await page.setViewport({
width: screenWidth,
height: 780,
});

const imageSize = await page.evaluate((selector: string) => {
const img: any = document.querySelector(selector);

return {
width: img?.width,
// height: img?.height,
};
}, selector);

resolve({ screenWidth: imageSize });
} catch (err) {
reject(`Error calculating image size, at ${selector}\n${err}`);
}
});
}

export function getImageSizes(
selectors: { id: string; classes: string[] },
htmlPath: string,
screenSizes: Record<string, number>,
): Promise<Record<string, number>> {
/* let prevsec: number = new Date().getTime(); */
): Promise<ImageSizeResponse> {
const selector: string = selectors?.id || selectors?.classes[0] || "img";

return new Promise(async (complete, incomplete) => {
return new Promise(async (resolve, reject) => {
let browser: Browser = {} as Browser;

try {
Expand All @@ -17,87 +62,38 @@ export function getImageSize(
args: ["--start-maximized"],
});

const imageSizes: Record<string, number> = {};

const promises: (() => Promise<void>)[] = Object.keys(
screenSizes,
).map((screenKey) => {
return (): Promise<void> => {
return new Promise(async (resolve, reject) => {
try {
const page = await browser.newPage();
const nativeScreenSize = await page.evaluate(() => ({
height: window.screen.availHeight,
}));

await page.setViewport({
width: screenSizes[screenKey],
height: nativeScreenSize.height,
});

await page.goto(htmlPath, { timeout: 60000 });

const selector: string =
selectors?.id || selectors?.classes[0] || "img";

const imageSize = await page.evaluate((selector: string) => {
const img: any = document.querySelector(selector);

return {
width: img?.width,
// height: img?.height,
};
}, selector);

imageSizes[screenKey] = imageSize as any;
await page.close();
resolve();
} catch (err) {
reject(err);
}
});
};
});

/* */
/* Batching promises */
const batchSize: number = 1;
const promiseBatches: (() => Promise<void>)[][] = [];
const page = await browser.newPage();

for (let i = 0; i < promises.length; i += batchSize) {
promiseBatches.push(promises.slice(i, i + batchSize));
}
await page.goto(htmlPath, { timeout: 60000 });

/* Activating batches */
for (const batch of promiseBatches) {
const activatedBatch: Promise<void>[] = batch.map((func) =>
func(),
);
const imageSizes: ImageSizeResponse = {};

const promises: (() => Promise<ImageSizeResponse>)[] = Object.keys(
screenSizes,
).map(
(screenKey: string) => (): Promise<ImageSizeResponse> =>
_getImageSize({
page: page,
screenWidth: screenSizes[screenKey],
selector: selector,
}),
);

/* Activating promise */
for (const promise of promises) {
try {
await Promise.all(activatedBatch);
const resolvedImageSize = await promise();
Object.assign(imageSizes, resolvedImageSize);
} catch (err) {
console.log(err);
}
}

/* const ctime = new Date().getTime();
console.log(Math.floor(ctime - prevsec));
prevsec = ctime; */

complete(imageSizes);
_closeBrowser(browser);
resolve(imageSizes);
} catch (err) {
incomplete(err);
} finally {
if (browser) {
try {
// Adding a slight delay before closing the browser
await new Promise((resolve) => setTimeout(resolve, 1000));
await browser.close();
} catch (err) {
console.error("Error closing browser:", err);
}
}
_closeBrowser(browser);
reject(err);
}
});
}
Loading

0 comments on commit 38969f9

Please sign in to comment.