@uxf/resizer 12.7.0 → 14.0.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uxf/resizer",
3
- "version": "12.7.0",
3
+ "version": "14.0.0",
4
4
  "main": "index.js",
5
5
  "description": "UXF Resizer",
6
6
  "author": "UXFans <dev@uxf.cz>",
package/src/handler.js CHANGED
@@ -4,6 +4,7 @@ exports.createResizerHandler = createResizerHandler;
4
4
  const fs_1 = require("fs");
5
5
  const promises_1 = require("fs/promises");
6
6
  const path_1 = require("path");
7
+ const fetch_source_1 = require("./utils/fetch-source");
7
8
  const get_source_filename_1 = require("./utils/get-source-filename");
8
9
  const image_converter_1 = require("./utils/image-converter");
9
10
  const log_1 = require("./utils/log");
@@ -28,13 +29,6 @@ async function fileResponse(filename, contentType) {
28
29
  },
29
30
  });
30
31
  }
31
- async function fetchSource(url) {
32
- const response = await fetch(url);
33
- if (!response.ok) {
34
- throw new Error(`Source ${url} responded with ${response.status}`);
35
- }
36
- return response.arrayBuffer();
37
- }
38
32
  /**
39
33
  * Builds a framework-agnostic request handler for the configured routes: the same `Request -> Response`
40
34
  * shape the Next.js route handlers use, so it can sit behind Hono, `@hono/node-server`, or any other
@@ -71,14 +65,14 @@ function createResizerHandler(config) {
71
65
  const isRemote = /^https?:\/\//.test(sourceFilename);
72
66
  if (params.toFormat === "svg") {
73
67
  if (isRemote) {
74
- await (0, promises_1.writeFile)(generatedFilename, Buffer.from(await fetchSource(sourceFilename)));
68
+ await (0, promises_1.writeFile)(generatedFilename, Buffer.from(await (0, fetch_source_1.fetchSource)(sourceFilename)));
75
69
  }
76
70
  else {
77
71
  await (0, promises_1.copyFile)(sourceFilename, generatedFilename);
78
72
  }
79
73
  return await fileResponse(generatedFilename, contentType);
80
74
  }
81
- const sourceFile = isRemote ? await fetchSource(sourceFilename) : sourceFilename;
75
+ const sourceFile = isRemote ? await (0, fetch_source_1.fetchSource)(sourceFilename) : sourceFilename;
82
76
  await (0, image_converter_1.convertImage)(sourceFile, generatedFilename, params);
83
77
  return await fileResponse(generatedFilename, contentType);
84
78
  }
package/src/handler.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "fs";
2
2
  import { copyFile, mkdir, readFile, stat, writeFile } from "fs/promises";
3
3
  import { dirname } from "path";
4
+ import { fetchSource } from "./utils/fetch-source";
4
5
  import { getSourceFilename } from "./utils/get-source-filename";
5
6
  import { convertImage } from "./utils/image-converter";
6
7
  import { log } from "./utils/log";
@@ -45,15 +46,6 @@ async function fileResponse(filename: string, contentType: string): Promise<Resp
45
46
  });
46
47
  }
47
48
 
48
- async function fetchSource(url: string): Promise<ArrayBuffer> {
49
- const response = await fetch(url);
50
- if (!response.ok) {
51
- throw new Error(`Source ${url} responded with ${response.status}`);
52
- }
53
-
54
- return response.arrayBuffer();
55
- }
56
-
57
49
  /**
58
50
  * Builds a framework-agnostic request handler for the configured routes: the same `Request -> Response`
59
51
  * shape the Next.js route handlers use, so it can sit behind Hono, `@hono/node-server`, or any other
package/src/next-route.js CHANGED
@@ -37,9 +37,16 @@ exports.StaticGET = StaticGET;
37
37
  exports.ProxyGET = ProxyGET;
38
38
  const fs_1 = __importStar(require("fs"));
39
39
  const path_1 = require("path");
40
+ const fetch_source_1 = require("./utils/fetch-source");
40
41
  const image_converter_1 = require("./utils/image-converter");
41
42
  const log_1 = require("./utils/log");
42
43
  const tools_1 = require("./utils/tools");
44
+ // A source that cannot be fetched (missing upload, error status, timeout) answers 404 like the Hono handler, not
45
+ // an unhandled 500.
46
+ function sourceNotFound(error) {
47
+ (0, log_1.log)(error, "error");
48
+ return new Response("Not Found", { status: 404 });
49
+ }
43
50
  const sendFile = (generatedFilename, contentType) => {
44
51
  const data = fs_1.default.readFileSync(generatedFilename);
45
52
  return new Response(data, {
@@ -71,9 +78,15 @@ async function StaticGET(request) {
71
78
  const staticUrl = `${process.env.NEXT_PUBLIC_FRONTEND_URL}/${params.filename}.${params.extension}`;
72
79
  // import usage: _next/static/media/example-logo-resizer.941ec59a => example-logo-resizer
73
80
  // import usage: /assetPrefix/_next/static/media/example-logo-resizer.941ec59a => example-logo-resizer
74
- const sourceFile = params.filename.includes("_next/static/media/")
75
- ? await fetch(staticUrl).then((response) => response.arrayBuffer())
76
- : process.cwd() + `/public/${params.filename}.${params.extension}`;
81
+ let sourceFile;
82
+ try {
83
+ sourceFile = params.filename.includes("_next/static/media/")
84
+ ? await (0, fetch_source_1.fetchSource)(staticUrl)
85
+ : process.cwd() + `/public/${params.filename}.${params.extension}`;
86
+ }
87
+ catch (e) {
88
+ return sourceNotFound(e);
89
+ }
77
90
  (0, log_1.log)(`Source filename: ${sourceFile instanceof ArrayBuffer ? staticUrl : sourceFile}`);
78
91
  if (params.toFormat === "svg") {
79
92
  fs_1.default.writeFileSync(generatedFilename, sourceFile instanceof ArrayBuffer ? Buffer.from(sourceFile) : sourceFile);
@@ -103,7 +116,13 @@ async function ProxyGET(request) {
103
116
  }
104
117
  const sourceUrl = `${process.env.NEXT_PUBLIC_API_URL}/upload/${params.namespace}/${params.p1}/${params.p2}/${params.filename}.${params.extension}`;
105
118
  (0, log_1.log)(`Generated: ${sourceUrl} => ${generatedFilename}`);
106
- const sourceFile = await fetch(sourceUrl).then((response) => response.arrayBuffer());
119
+ let sourceFile;
120
+ try {
121
+ sourceFile = await (0, fetch_source_1.fetchSource)(sourceUrl);
122
+ }
123
+ catch (e) {
124
+ return sourceNotFound(e);
125
+ }
107
126
  if (params.toFormat === "svg") {
108
127
  fs_1.default.writeFileSync(generatedFilename, Buffer.from(sourceFile));
109
128
  return sendFile(generatedFilename, "image/svg+xml");
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,25 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /** @jest-environment node */
4
+ const fs_1 = require("fs");
5
+ const os_1 = require("os");
6
+ const path_1 = require("path");
7
+ const next_route_1 = require("./next-route");
8
+ const originalCwd = process.cwd();
9
+ let workDir;
10
+ beforeEach(() => {
11
+ workDir = (0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.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
+ afterEach(() => {
17
+ process.chdir(originalCwd);
18
+ (0, fs_1.rmSync)(workDir, { recursive: true, force: true });
19
+ jest.restoreAllMocks();
20
+ });
21
+ test("a source the API does not have answers 404, not an unhandled error", async () => {
22
+ jest.spyOn(global, "fetch").mockResolvedValue(new Response("<html>Not found</html>", { status: 404 }));
23
+ const response = await (0, next_route_1.ProxyGET)(new Request("http://localhost/generated/upload/a/b/abc123_100_100_cover_center_ffffff_false_80_svg.svg"));
24
+ expect(response.status).toBe(404);
25
+ });
@@ -0,0 +1,31 @@
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 CHANGED
@@ -1,9 +1,18 @@
1
1
  import fs, { existsSync, mkdirSync } from "fs";
2
2
  import { dirname } from "path";
3
+ import { fetchSource } from "./utils/fetch-source";
3
4
  import { convertImage } from "./utils/image-converter";
4
5
  import { log } from "./utils/log";
5
6
  import { CONTENT_TYPES, Params } from "./utils/tools";
6
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
+
7
16
  const sendFile = (generatedFilename: string, contentType: string) => {
8
17
  const data = fs.readFileSync(generatedFilename);
9
18
  return new Response(data, {
@@ -44,9 +53,14 @@ export async function StaticGET(request: Request) {
44
53
 
45
54
  // import usage: _next/static/media/example-logo-resizer.941ec59a => example-logo-resizer
46
55
  // import usage: /assetPrefix/_next/static/media/example-logo-resizer.941ec59a => example-logo-resizer
47
- const sourceFile = params.filename.includes("_next/static/media/")
48
- ? await fetch(staticUrl).then((response) => response.arrayBuffer())
49
- : process.cwd() + `/public/${params.filename}.${params.extension}`;
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
+ }
50
64
 
51
65
  log(`Source filename: ${sourceFile instanceof ArrayBuffer ? staticUrl : sourceFile}`);
52
66
 
@@ -87,7 +101,12 @@ export async function ProxyGET(request: Request) {
87
101
  const sourceUrl = `${process.env.NEXT_PUBLIC_API_URL}/upload/${params.namespace}/${params.p1}/${params.p2}/${params.filename}.${params.extension}`;
88
102
  log(`Generated: ${sourceUrl} => ${generatedFilename}`);
89
103
 
90
- const sourceFile = await fetch(sourceUrl).then((response) => response.arrayBuffer());
104
+ let sourceFile: ArrayBuffer;
105
+ try {
106
+ sourceFile = await fetchSource(sourceUrl);
107
+ } catch (e) {
108
+ return sourceNotFound(e);
109
+ }
91
110
 
92
111
  if (params.toFormat === "svg") {
93
112
  fs.writeFileSync(generatedFilename, Buffer.from(sourceFile));
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Downloads a source image. An error response is rejected rather than returned: its body (an HTML error page)
3
+ * would otherwise reach the converter, and for SVG be cached to disk as the generated file.
4
+ */
5
+ export declare function fetchSource(url: string): Promise<ArrayBuffer>;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.fetchSource = fetchSource;
4
+ // Long enough for a large original over a slow link, short enough not to hold a request for the five
5
+ // minutes Node's fetch would otherwise wait.
6
+ const SOURCE_TIMEOUT_MS = 30000;
7
+ /**
8
+ * Downloads a source image. An error response is rejected rather than returned: its body (an HTML error page)
9
+ * would otherwise reach the converter, and for SVG be cached to disk as the generated file.
10
+ */
11
+ async function fetchSource(url) {
12
+ const response = await fetch(url, { signal: AbortSignal.timeout(SOURCE_TIMEOUT_MS) });
13
+ if (!response.ok) {
14
+ throw new Error(`Source ${url} responded with ${response.status}`);
15
+ }
16
+ return response.arrayBuffer();
17
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /** @jest-environment node */
4
+ const fetch_source_1 = require("./fetch-source");
5
+ afterEach(() => {
6
+ jest.restoreAllMocks();
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
+ await expect((0, fetch_source_1.fetchSource)("https://api.example/upload/a.svg")).rejects.toThrow("responded with 404");
11
+ });
12
+ test("returns the body of a successful response", async () => {
13
+ jest.spyOn(global, "fetch").mockResolvedValue(new Response("<svg/>", { status: 200 }));
14
+ expect(Buffer.from(await (0, fetch_source_1.fetchSource)("https://api.example/upload/a.svg")).toString()).toBe("<svg/>");
15
+ });
16
+ test("gives up on a source that does not answer within 30 s", async () => {
17
+ var _a, _b, _c;
18
+ const timeout = jest.spyOn(AbortSignal, "timeout");
19
+ const fetchMock = jest.spyOn(global, "fetch").mockResolvedValue(new Response("", { status: 200 }));
20
+ await (0, fetch_source_1.fetchSource)("https://api.example/upload/a.svg");
21
+ expect(timeout).toHaveBeenCalledWith(30000);
22
+ expect((_b = (_a = fetchMock.mock.calls.at(0)) === null || _a === void 0 ? void 0 : _a[1]) === null || _b === void 0 ? void 0 : _b.signal).toBe((_c = timeout.mock.results.at(0)) === null || _c === void 0 ? void 0 : _c.value);
23
+ });
@@ -0,0 +1,28 @@
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
+ });
@@ -0,0 +1,16 @@
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
+ }