@uxf/resizer 15.0.0 → 16.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,68 +0,0 @@
1
- #!/usr/bin/env node
2
- import { serve } from "@hono/node-server";
3
- import * as fs from "fs";
4
- import { Hono } from "hono";
5
- import { argv, env } from "node:process";
6
- import cli from "yargs";
7
- import { Config, createResizerHandler } from "../src/handler";
8
-
9
- const PORT = 3000;
10
-
11
- const uxfResizer = async () => {
12
- cli()
13
- .command("$0", "UXF Resizer", (yargs) => {
14
- yargs.demandCommand(0, 0).usage(`
15
- Usage:
16
- uxf-resizer
17
-
18
- Environment variables:
19
- UXF_RESIZER_GENERATE_PATH - required`);
20
- })
21
- .option("h", { alias: "help", group: "Options" })
22
- .strict(false)
23
- .exitProcess(false);
24
-
25
- try {
26
- const { help } = cli().parse(argv.slice(2)) as any; // TODO
27
-
28
- if (help) {
29
- return 0;
30
- }
31
-
32
- const configFilename = process.cwd() + "/.resizer-config.json";
33
-
34
- const configString =
35
- env.UXF_RESIZER_CONFIG ??
36
- (fs.existsSync(configFilename) ? fs.readFileSync(configFilename).toString() : "[]");
37
-
38
- const config: Config = JSON.parse(configString);
39
-
40
- if (!Array.isArray(config) || config.length === 0) {
41
- throw new Error("Invalid or empty configuration");
42
- }
43
-
44
- const handler = createResizerHandler(config);
45
- const app = new Hono();
46
- app.get("*", (c) => handler(c.req.raw));
47
-
48
- return new Promise<number>((resolve) => {
49
- const server = serve({ fetch: app.fetch, port: PORT }, () => {
50
- // eslint-disable-next-line no-console
51
- console.log(`\nImage resizer app listening on port ${PORT}`);
52
- });
53
-
54
- const shutdown = () => {
55
- server.close(() => resolve(0));
56
- };
57
- process.once("SIGINT", shutdown);
58
- process.once("SIGTERM", shutdown);
59
- });
60
- } catch (e) {
61
- // eslint-disable-next-line no-console
62
- console.error(e);
63
- return 1;
64
- }
65
- };
66
-
67
- // eslint-disable-next-line no-console
68
- uxfResizer().catch(console.error);
package/index.ts DELETED
@@ -1,3 +0,0 @@
1
- import { ProxyGET, StaticGET } from "./src/next-route";
2
-
3
- export { ProxyGET, StaticGET };
@@ -1,84 +0,0 @@
1
- /**
2
- * @jest-environment node
3
- */
4
- import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from "fs";
5
- import { tmpdir } from "os";
6
- import { join } from "path";
7
- import sharp from "sharp";
8
- import { Config, createResizerHandler } from "./handler";
9
-
10
- const STATIC_ROUTE =
11
- "/generated/static/:width(\\d+|x)_:height(\\d+|x)_:fit([a-z]+)_:position([a-z]+)_:background([a-z0-9]+)_:trim([a-z0-9]+)_:quality(\\d+|x)/:version/:filename(.*).:extension.:toFormat";
12
-
13
- let workDir: string;
14
- let sourceDir: string;
15
- let generatePath: string;
16
- let handler: (request: Request) => Promise<Response>;
17
- let logSpy: jest.SpyInstance;
18
-
19
- const tmpFilesIn = (dir: string) =>
20
- existsSync(dir) ? readdirSync(dir, { recursive: true }).filter((f) => String(f).endsWith(".tmp")) : [];
21
-
22
- beforeAll(async () => {
23
- workDir = mkdtempSync(join(tmpdir(), "uxf-resizer-"));
24
- sourceDir = join(workDir, "source");
25
- generatePath = join(workDir, "generated");
26
- process.env.UXF_RESIZER_GENERATE_PATH = generatePath;
27
-
28
- mkdirSync(sourceDir, { recursive: true });
29
- await sharp({ create: { width: 40, height: 20, channels: 3, background: "#ff0000" } })
30
- .png()
31
- .toFile(join(sourceDir, "img.png"));
32
-
33
- const config: Config = [{ route: STATIC_ROUTE, source: `${sourceDir}/:filename+.:extension` }];
34
- logSpy = jest.spyOn(console, "log").mockImplementation(() => undefined);
35
- handler = createResizerHandler(config);
36
- });
37
-
38
- afterAll(() => {
39
- logSpy.mockRestore();
40
- delete process.env.UXF_RESIZER_GENERATE_PATH;
41
- rmSync(workDir, { recursive: true, force: true });
42
- });
43
-
44
- test("generates, caches and serves a resized image", async () => {
45
- const path = "/generated/static/20_x_cv_c_FFF_nt_x/1/img.png.webp";
46
-
47
- const response = await handler(new Request(`http://localhost${path}`));
48
-
49
- expect(response.status).toBe(200);
50
- expect(response.headers.get("Content-Type")).toBe("image/webp");
51
- expect(response.headers.get("Last-Modified")).toBeTruthy();
52
- expect(existsSync(generatePath + path)).toBe(true);
53
- expect(tmpFilesIn(generatePath)).toEqual([]);
54
-
55
- const body = await response.arrayBuffer();
56
- expect(response.headers.get("Content-Length")).toBe(String(body.byteLength));
57
-
58
- const metadata = await sharp(Buffer.from(body)).metadata();
59
- expect(metadata.format).toBe("webp");
60
- expect(metadata.width).toBe(20);
61
-
62
- // second request is served from the cache – same file, same headers
63
- const cached = await handler(new Request(`http://localhost${path}?ignored=1`));
64
- expect(cached.status).toBe(200);
65
- expect(cached.headers.get("Content-Length")).toBe(response.headers.get("Content-Length"));
66
- });
67
-
68
- test("responds 404 for an unmatched path", async () => {
69
- const response = await handler(new Request("http://localhost/generated/nonsense"));
70
-
71
- expect(response.status).toBe(404);
72
- });
73
-
74
- test("responds 404 when the source file is missing", async () => {
75
- const errorSpy = jest.spyOn(console, "error").mockImplementation(() => undefined);
76
- const response = await handler(
77
- new Request("http://localhost/generated/static/20_x_cv_c_FFF_nt_x/1/missing.png.webp"),
78
- );
79
-
80
- expect(response.status).toBe(404);
81
- expect(errorSpy).toHaveBeenCalled();
82
- expect(tmpFilesIn(generatePath)).toEqual([]);
83
- errorSpy.mockRestore();
84
- });
package/src/handler.ts DELETED
@@ -1,131 +0,0 @@
1
- import { randomUUID } from "crypto";
2
- import { existsSync } from "fs";
3
- import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "fs/promises";
4
- import { dirname } from "path";
5
- import { fetchSource } from "./utils/fetch-source";
6
- import { getSourceFilename } from "./utils/get-source-filename";
7
- import { convertImage } from "./utils/image-converter";
8
- import { log } from "./utils/log";
9
- import { createRouteMatcher } from "./utils/match-route";
10
- import { CONTENT_TYPES, Params } from "./utils/tools";
11
-
12
- export type Config = Array<{
13
- route: string;
14
- source: string;
15
- }>;
16
-
17
- interface CompiledRoute {
18
- match: (pathname: string) => Params | undefined;
19
- source: string;
20
- }
21
-
22
- interface MatchedRoute {
23
- params: Params;
24
- source: string;
25
- }
26
-
27
- function matchRoute(routes: CompiledRoute[], pathname: string): MatchedRoute | undefined {
28
- for (const route of routes) {
29
- const params = route.match(pathname);
30
- if (params !== undefined) {
31
- return { params, source: route.source };
32
- }
33
- }
34
-
35
- return undefined;
36
- }
37
-
38
- async function fileResponse(filename: string, contentType: string): Promise<Response> {
39
- const [data, stats] = await Promise.all([readFile(filename), stat(filename)]);
40
-
41
- return new Response(data, {
42
- headers: {
43
- "Content-Type": contentType,
44
- "Content-Length": String(stats.size),
45
- "Last-Modified": stats.mtime.toUTCString(),
46
- },
47
- });
48
- }
49
-
50
- /**
51
- * Writes into a temporary file next to the target and renames it into place, so a reader sharing the cache
52
- * directory (nginx `try_files`, another resizer instance) never sees a partially written file, and a failed
53
- * write never leaves a broken file behind.
54
- */
55
- async function writeAtomically(filename: string, write: (tmpFilename: string) => Promise<unknown>): Promise<void> {
56
- const tmpFilename = `${filename}.${randomUUID()}.tmp`;
57
-
58
- try {
59
- await write(tmpFilename);
60
- await rename(tmpFilename, filename);
61
- } finally {
62
- await rm(tmpFilename, { force: true });
63
- }
64
- }
65
-
66
- /**
67
- * Builds a framework-agnostic request handler for the configured routes: the same `Request -> Response`
68
- * shape the Next.js route handlers use, so it can sit behind Hono, `@hono/node-server`, or any other
69
- * WHATWG-fetch-compatible server.
70
- */
71
- export function createResizerHandler(config: Config): (request: Request) => Promise<Response> {
72
- const routes = config.map((c, i): CompiledRoute => {
73
- log(`Config #${i + 1}:`);
74
- log(` Route: ${c.route}`);
75
- log(` Source: ${c.source}`);
76
-
77
- return { match: createRouteMatcher(c.route), source: c.source };
78
- });
79
-
80
- return async (request) => {
81
- try {
82
- const { pathname } = new URL(request.url);
83
- log("----------------------------------------");
84
- log(`${request.method} ${pathname}`);
85
-
86
- const matched = matchRoute(routes, pathname);
87
- if (matched === undefined) {
88
- log("No route matched", "warn");
89
- return new Response("Not Found", { status: 404 });
90
- }
91
-
92
- const { params, source } = matched;
93
-
94
- const generatedFilename = (process.env.UXF_RESIZER_GENERATE_PATH ?? process.cwd()) + pathname;
95
- log(`Generated filename: ${generatedFilename}`);
96
-
97
- const contentType =
98
- params.toFormat === "svg" ? "image/svg+xml" : (CONTENT_TYPES[params.toFormat] ?? "image/jpeg");
99
-
100
- if (existsSync(generatedFilename)) {
101
- return await fileResponse(generatedFilename, contentType);
102
- }
103
-
104
- await mkdir(dirname(generatedFilename), { recursive: true });
105
-
106
- const sourceFilename = getSourceFilename(source, params);
107
- log(`Source filename: ${sourceFilename}`);
108
-
109
- const isRemote = /^https?:\/\//.test(sourceFilename);
110
-
111
- if (params.toFormat === "svg") {
112
- if (isRemote) {
113
- const svg = Buffer.from(await fetchSource(sourceFilename));
114
- await writeAtomically(generatedFilename, (tmpFilename) => writeFile(tmpFilename, svg));
115
- } else {
116
- await writeAtomically(generatedFilename, (tmpFilename) => copyFile(sourceFilename, tmpFilename));
117
- }
118
-
119
- return await fileResponse(generatedFilename, contentType);
120
- }
121
-
122
- const sourceFile = isRemote ? await fetchSource(sourceFilename) : sourceFilename;
123
- await writeAtomically(generatedFilename, (tmpFilename) => convertImage(sourceFile, tmpFilename, params));
124
-
125
- return await fileResponse(generatedFilename, contentType);
126
- } catch (e) {
127
- log(e, "error");
128
- return new Response("Not Found", { status: 404 });
129
- }
130
- };
131
- }
@@ -1,31 +0,0 @@
1
- /** @jest-environment node */
2
- import { mkdtempSync, rmSync } from "fs";
3
- import { tmpdir } from "os";
4
- import { join } from "path";
5
- import { ProxyGET } from "./next-route";
6
-
7
- const originalCwd = process.cwd();
8
- let workDir: string;
9
-
10
- beforeEach(() => {
11
- workDir = mkdtempSync(join(tmpdir(), "resizer-next-route-"));
12
- process.chdir(workDir);
13
- process.env.NEXT_PUBLIC_API_URL = "https://api.example";
14
- jest.spyOn(console, "error").mockImplementation(() => undefined);
15
- });
16
-
17
- afterEach(() => {
18
- process.chdir(originalCwd);
19
- rmSync(workDir, { recursive: true, force: true });
20
- jest.restoreAllMocks();
21
- });
22
-
23
- test("a source the API does not have answers 404, not an unhandled error", async () => {
24
- jest.spyOn(global, "fetch").mockResolvedValue(new Response("<html>Not found</html>", { status: 404 }));
25
-
26
- const response = await ProxyGET(
27
- new Request("http://localhost/generated/upload/a/b/abc123_100_100_cover_center_ffffff_false_80_svg.svg"),
28
- );
29
-
30
- expect(response.status).toBe(404);
31
- });
package/src/next-route.ts DELETED
@@ -1,119 +0,0 @@
1
- import fs, { existsSync, mkdirSync } from "fs";
2
- import { dirname } from "path";
3
- import { fetchSource } from "./utils/fetch-source";
4
- import { convertImage } from "./utils/image-converter";
5
- import { log } from "./utils/log";
6
- import { CONTENT_TYPES, Params } from "./utils/tools";
7
-
8
- // A source that cannot be fetched (missing upload, error status, timeout) answers 404 like the Hono handler, not
9
- // an unhandled 500.
10
- function sourceNotFound(error: unknown) {
11
- log(error, "error");
12
-
13
- return new Response("Not Found", { status: 404 });
14
- }
15
-
16
- const sendFile = (generatedFilename: string, contentType: string) => {
17
- const data = fs.readFileSync(generatedFilename);
18
- return new Response(data, {
19
- headers: {
20
- "Content-Type": contentType,
21
- },
22
- });
23
- };
24
-
25
- // lokalni zpracovani obrazku
26
- export async function StaticGET(request: Request) {
27
- const url = new URL(request.url);
28
- const path = url.pathname;
29
-
30
- const regex =
31
- /^\/generated\/static\/(?<width>\d+|x)_(?<height>\d+|x)_(?<fit>[a-z]+)_(?<position>[a-z]+)_(?<background>[0-9a-f]+)_(?<trim>[a-z]+)_(?<quality>\d+|x)\/(?<version>[a-z0-9]+)\/(?<filename>.+)\.(?<extension>[a-z]+)\.(?<toFormat>[a-z]+)/i;
32
-
33
- const params = path.match(regex)?.groups as Params | undefined;
34
- if (params === undefined) {
35
- return Response.error();
36
- }
37
-
38
- const generatedFilename = process.cwd() + path;
39
- log(`Generated filename: ${generatedFilename}`);
40
-
41
- const contentType = CONTENT_TYPES[params.toFormat] ?? "image/jpeg";
42
-
43
- if (existsSync(generatedFilename)) {
44
- return sendFile(generatedFilename, contentType);
45
- }
46
-
47
- const generatedDirectory = dirname(generatedFilename);
48
- if (!existsSync(generatedDirectory)) {
49
- mkdirSync(generatedDirectory, { recursive: true });
50
- }
51
-
52
- const staticUrl = `${process.env.NEXT_PUBLIC_FRONTEND_URL}/${params.filename}.${params.extension}`;
53
-
54
- // import usage: _next/static/media/example-logo-resizer.941ec59a => example-logo-resizer
55
- // import usage: /assetPrefix/_next/static/media/example-logo-resizer.941ec59a => example-logo-resizer
56
- let sourceFile: ArrayBuffer | string;
57
- try {
58
- sourceFile = params.filename.includes("_next/static/media/")
59
- ? await fetchSource(staticUrl)
60
- : process.cwd() + `/public/${params.filename}.${params.extension}`;
61
- } catch (e) {
62
- return sourceNotFound(e);
63
- }
64
-
65
- log(`Source filename: ${sourceFile instanceof ArrayBuffer ? staticUrl : sourceFile}`);
66
-
67
- if (params.toFormat === "svg") {
68
- fs.writeFileSync(generatedFilename, sourceFile instanceof ArrayBuffer ? Buffer.from(sourceFile) : sourceFile);
69
- return sendFile(generatedFilename, "image/svg+xml");
70
- }
71
-
72
- await convertImage(sourceFile, generatedFilename, params);
73
-
74
- return sendFile(generatedFilename, contentType);
75
- }
76
-
77
- // proxy na dev
78
- export async function ProxyGET(request: Request) {
79
- const url = new URL(request.url);
80
- const path = url.pathname;
81
-
82
- const regex =
83
- /^\/generated\/(?<namespace>[0-9a-z-_]+)\/(?<p1>[0-9a-f])\/(?<p2>[0-9a-f-])\/(?<filename>[0-9a-f-]+)_(?<width>\d+|x)_(?<height>\d+|x)_(?<fit>[a-z]+)_(?<position>[a-z]+)_(?<background>[0-9a-f]+)_(?<trim>[a-z]+)_(?<quality>\d+|x)_(?<extension>[a-z]+)\.(?<toFormat>[a-z]+)/i;
84
-
85
- const params = path.match(regex)?.groups as Params | undefined;
86
- if (params === undefined) {
87
- return Response.error();
88
- }
89
-
90
- const contentType = CONTENT_TYPES[params.toFormat] ?? "image/jpeg";
91
- const generatedFilename = process.cwd() + path;
92
- if (existsSync(generatedFilename)) {
93
- return sendFile(generatedFilename, contentType);
94
- }
95
-
96
- const generatedDirectory = dirname(generatedFilename);
97
- if (!existsSync(generatedDirectory)) {
98
- mkdirSync(generatedDirectory, { recursive: true });
99
- }
100
-
101
- const sourceUrl = `${process.env.NEXT_PUBLIC_API_URL}/upload/${params.namespace}/${params.p1}/${params.p2}/${params.filename}.${params.extension}`;
102
- log(`Generated: ${sourceUrl} => ${generatedFilename}`);
103
-
104
- let sourceFile: ArrayBuffer;
105
- try {
106
- sourceFile = await fetchSource(sourceUrl);
107
- } catch (e) {
108
- return sourceNotFound(e);
109
- }
110
-
111
- if (params.toFormat === "svg") {
112
- fs.writeFileSync(generatedFilename, Buffer.from(sourceFile));
113
- return sendFile(generatedFilename, "image/svg+xml");
114
- }
115
-
116
- await convertImage(sourceFile, generatedFilename, params);
117
-
118
- return sendFile(generatedFilename, contentType);
119
- }
@@ -1,28 +0,0 @@
1
- /** @jest-environment node */
2
- import { fetchSource } from "./fetch-source";
3
-
4
- afterEach(() => {
5
- jest.restoreAllMocks();
6
- });
7
-
8
- test("rejects an error response instead of returning its body as the image", async () => {
9
- jest.spyOn(global, "fetch").mockResolvedValue(new Response("<html>Not found</html>", { status: 404 }));
10
-
11
- await expect(fetchSource("https://api.example/upload/a.svg")).rejects.toThrow("responded with 404");
12
- });
13
-
14
- test("returns the body of a successful response", async () => {
15
- jest.spyOn(global, "fetch").mockResolvedValue(new Response("<svg/>", { status: 200 }));
16
-
17
- expect(Buffer.from(await fetchSource("https://api.example/upload/a.svg")).toString()).toBe("<svg/>");
18
- });
19
-
20
- test("gives up on a source that does not answer within 30 s", async () => {
21
- const timeout = jest.spyOn(AbortSignal, "timeout");
22
- const fetchMock = jest.spyOn(global, "fetch").mockResolvedValue(new Response("", { status: 200 }));
23
-
24
- await fetchSource("https://api.example/upload/a.svg");
25
-
26
- expect(timeout).toHaveBeenCalledWith(30_000);
27
- expect(fetchMock.mock.calls.at(0)?.[1]?.signal).toBe(timeout.mock.results.at(0)?.value);
28
- });
@@ -1,16 +0,0 @@
1
- // Long enough for a large original over a slow link, short enough not to hold a request for the five
2
- // minutes Node's fetch would otherwise wait.
3
- const SOURCE_TIMEOUT_MS = 30_000;
4
-
5
- /**
6
- * Downloads a source image. An error response is rejected rather than returned: its body (an HTML error page)
7
- * would otherwise reach the converter, and for SVG be cached to disk as the generated file.
8
- */
9
- export async function fetchSource(url: string): Promise<ArrayBuffer> {
10
- const response = await fetch(url, { signal: AbortSignal.timeout(SOURCE_TIMEOUT_MS) });
11
- if (!response.ok) {
12
- throw new Error(`Source ${url} responded with ${response.status}`);
13
- }
14
-
15
- return response.arrayBuffer();
16
- }
@@ -1,65 +0,0 @@
1
- import { getSourceFilename } from "./get-source-filename";
2
-
3
- test("get source filename", () => {
4
- expect(
5
- getSourceFilename("https://domain.uxf.dev/:filename+.:extension", {
6
- filename: ["path", "to", "file"],
7
- extension: "jpg",
8
- }),
9
- ).toStrictEqual("https://domain.uxf.dev/path/to/file.jpg");
10
-
11
- expect(
12
- getSourceFilename("http://localhost:3000/:filename+.:extension", {
13
- filename: ["path", "to", "file"],
14
- extension: "jpg",
15
- }),
16
- ).toStrictEqual("http://localhost:3000/path/to/file.jpg");
17
-
18
- expect(
19
- getSourceFilename("https://:url/:filename+.:extension", {
20
- url: "domain-as-parameter.uxf.dev",
21
- filename: ["path", "to", "file"],
22
- extension: "jpg",
23
- }),
24
- ).toStrictEqual("https://domain-as-parameter.uxf.dev/path/to/file.jpg");
25
-
26
- expect(
27
- getSourceFilename("/var/www/:filename+.:extension", {
28
- filename: ["path", "to", "file"],
29
- extension: "jpg",
30
- }),
31
- ).toStrictEqual("/var/www/path/to/file.jpg");
32
- });
33
-
34
- test("accepts a string value containing slashes (what URLPattern yields for :filename(.*))", () => {
35
- expect(
36
- getSourceFilename("https://static.example.dev/:filename+.:extension", {
37
- filename: "_next/static/media/logo.941ec59a",
38
- extension: "png",
39
- }),
40
- ).toStrictEqual("https://static.example.dev/_next/static/media/logo.941ec59a.png");
41
- });
42
-
43
- test("ignores the * and ? modifiers", () => {
44
- expect(getSourceFilename("/var/www/:dir*/:file?.:ext", { dir: "a/b", file: "c", ext: "png" })).toStrictEqual(
45
- "/var/www/a/b/c.png",
46
- );
47
- });
48
-
49
- test("keeps the uploaded-image source intact", () => {
50
- expect(
51
- getSourceFilename("https://s3.example.dev/:namespace/:p1/:p2/:filename.:extension", {
52
- namespace: "product",
53
- p1: "0",
54
- p2: "f",
55
- filename: "0f1e2d3c-1111-2222-3333-444455556666",
56
- extension: "jpg",
57
- }),
58
- ).toStrictEqual("https://s3.example.dev/product/0/f/0f1e2d3c-1111-2222-3333-444455556666.jpg");
59
- });
60
-
61
- test("throws when a parameter is missing", () => {
62
- expect(() => getSourceFilename("/var/www/:filename.:extension", { filename: "x" })).toThrow(
63
- 'Missing parameter "extension"',
64
- );
65
- });
@@ -1,21 +0,0 @@
1
- import { log } from "./log";
2
-
3
- /**
4
- * `:name`, optionally followed by a path-to-regexp v6 modifier (`+`, `*`, `?`) that is ignored here –
5
- * the matched value already contains any slashes. A name must start with a letter, so the port in
6
- * `http://localhost:3000/...` is never mistaken for a parameter.
7
- */
8
- const PARAM_PATTERN = /:([A-Za-z_]\w*)[+*?]?/g;
9
-
10
- export function getSourceFilename(source: string, params: Partial<Record<string, string | string[]>>): string {
11
- log(params);
12
-
13
- return source.replace(PARAM_PATTERN, (_match, key: string) => {
14
- const value = params[key];
15
- if (value === undefined) {
16
- throw new Error(`Missing parameter "${key}" for source "${source}"`);
17
- }
18
-
19
- return Array.isArray(value) ? value.join("/") : value;
20
- });
21
- }
@@ -1,56 +0,0 @@
1
- import sharp, { OutputInfo } from "sharp";
2
- import {
3
- getBackground,
4
- getFit,
5
- getHeight,
6
- getPosition,
7
- getQuality,
8
- getTrim,
9
- getWidth,
10
- getWithoutEnlargement,
11
- Params,
12
- } from "./tools";
13
-
14
- export function convertImage(
15
- sourceFile: string | ArrayBuffer,
16
- generatedFilename: string,
17
- params: Params,
18
- ): Promise<OutputInfo> {
19
- const pipeline = sharp(sourceFile)
20
- .rotate()
21
- .resize({
22
- width: getWidth(params),
23
- height: getHeight(params),
24
- background: getBackground(params),
25
- fastShrinkOnLoad: false,
26
- fit: getFit(params),
27
- position: getPosition(params),
28
- withoutEnlargement: getWithoutEnlargement(params),
29
- });
30
-
31
- const trim = getTrim(params);
32
- if (trim !== undefined) {
33
- pipeline.trim({
34
- threshold: trim,
35
- });
36
- }
37
-
38
- const quality = getQuality(params);
39
-
40
- switch (params.toFormat) {
41
- case "webp":
42
- pipeline.webp({ quality });
43
- break;
44
- case "png":
45
- pipeline.png({ progressive: true, quality });
46
- break;
47
- case "avif":
48
- pipeline.avif({ quality });
49
- break;
50
- default:
51
- pipeline.jpeg({ progressive: true, quality });
52
- break;
53
- }
54
-
55
- return pipeline.withMetadata({ density: 72 }).toColorspace("srgb").toFile(generatedFilename);
56
- }
package/src/utils/log.ts DELETED
@@ -1,4 +0,0 @@
1
- export function log(message: any, level: "log" | "warn" | "error" = "log") {
2
- // eslint-disable-next-line no-console
3
- console[level](message);
4
- }