@uxf/resizer 12.7.0 → 15.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/README.md CHANGED
@@ -26,7 +26,7 @@ The only runtime dependency is `sharp`. The standalone server additionally needs
26
26
  yarn add @uxf/resizer hono @hono/node-server yargs --dev
27
27
  ```
28
28
 
29
- Node `>= 24` is required (route matching uses the built-in `URLPattern`).
29
+ Node `>= 26` is required (route matching uses the built-in `URLPattern`).
30
30
 
31
31
  ## Quick start
32
32
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@uxf/resizer",
3
- "version": "12.7.0",
3
+ "version": "15.0.0",
4
4
  "main": "index.js",
5
5
  "description": "UXF Resizer",
6
6
  "author": "UXFans <dev@uxf.cz>",
@@ -19,14 +19,14 @@
19
19
  "sharp": "^0.35.5"
20
20
  },
21
21
  "devDependencies": {
22
- "@hono/node-server": "2.1.3",
23
- "@types/node": "24",
24
- "hono": "4.13.13",
22
+ "@hono/node-server": "2.1.5",
23
+ "@types/node": "26",
24
+ "hono": "4.13.14",
25
25
  "tsx": "4.23.15",
26
26
  "yargs": "18.2.0"
27
27
  },
28
28
  "engines": {
29
- "node": ">=24"
29
+ "node": ">=26"
30
30
  },
31
31
  "scripts": {
32
32
  "build": "tsc -P tsconfig.json",
package/src/handler.js CHANGED
@@ -1,9 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createResizerHandler = createResizerHandler;
4
+ const crypto_1 = require("crypto");
4
5
  const fs_1 = require("fs");
5
6
  const promises_1 = require("fs/promises");
6
7
  const path_1 = require("path");
8
+ const fetch_source_1 = require("./utils/fetch-source");
7
9
  const get_source_filename_1 = require("./utils/get-source-filename");
8
10
  const image_converter_1 = require("./utils/image-converter");
9
11
  const log_1 = require("./utils/log");
@@ -28,12 +30,20 @@ async function fileResponse(filename, contentType) {
28
30
  },
29
31
  });
30
32
  }
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}`);
33
+ /**
34
+ * Writes into a temporary file next to the target and renames it into place, so a reader sharing the cache
35
+ * directory (nginx `try_files`, another resizer instance) never sees a partially written file, and a failed
36
+ * write never leaves a broken file behind.
37
+ */
38
+ async function writeAtomically(filename, write) {
39
+ const tmpFilename = `${filename}.${(0, crypto_1.randomUUID)()}.tmp`;
40
+ try {
41
+ await write(tmpFilename);
42
+ await (0, promises_1.rename)(tmpFilename, filename);
43
+ }
44
+ finally {
45
+ await (0, promises_1.rm)(tmpFilename, { force: true });
35
46
  }
36
- return response.arrayBuffer();
37
47
  }
38
48
  /**
39
49
  * Builds a framework-agnostic request handler for the configured routes: the same `Request -> Response`
@@ -71,15 +81,16 @@ function createResizerHandler(config) {
71
81
  const isRemote = /^https?:\/\//.test(sourceFilename);
72
82
  if (params.toFormat === "svg") {
73
83
  if (isRemote) {
74
- await (0, promises_1.writeFile)(generatedFilename, Buffer.from(await fetchSource(sourceFilename)));
84
+ const svg = Buffer.from(await (0, fetch_source_1.fetchSource)(sourceFilename));
85
+ await writeAtomically(generatedFilename, (tmpFilename) => (0, promises_1.writeFile)(tmpFilename, svg));
75
86
  }
76
87
  else {
77
- await (0, promises_1.copyFile)(sourceFilename, generatedFilename);
88
+ await writeAtomically(generatedFilename, (tmpFilename) => (0, promises_1.copyFile)(sourceFilename, tmpFilename));
78
89
  }
79
90
  return await fileResponse(generatedFilename, contentType);
80
91
  }
81
- const sourceFile = isRemote ? await fetchSource(sourceFilename) : sourceFilename;
82
- await (0, image_converter_1.convertImage)(sourceFile, generatedFilename, params);
92
+ const sourceFile = isRemote ? await (0, fetch_source_1.fetchSource)(sourceFilename) : sourceFilename;
93
+ await writeAtomically(generatedFilename, (tmpFilename) => (0, image_converter_1.convertImage)(sourceFile, tmpFilename, params));
83
94
  return await fileResponse(generatedFilename, contentType);
84
95
  }
85
96
  catch (e) {
@@ -17,6 +17,7 @@ let sourceDir;
17
17
  let generatePath;
18
18
  let handler;
19
19
  let logSpy;
20
+ const tmpFilesIn = (dir) => (0, fs_1.existsSync)(dir) ? (0, fs_1.readdirSync)(dir, { recursive: true }).filter((f) => String(f).endsWith(".tmp")) : [];
20
21
  beforeAll(async () => {
21
22
  workDir = (0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.tmpdir)(), "uxf-resizer-"));
22
23
  sourceDir = (0, path_1.join)(workDir, "source");
@@ -42,6 +43,7 @@ test("generates, caches and serves a resized image", async () => {
42
43
  expect(response.headers.get("Content-Type")).toBe("image/webp");
43
44
  expect(response.headers.get("Last-Modified")).toBeTruthy();
44
45
  expect((0, fs_1.existsSync)(generatePath + path)).toBe(true);
46
+ expect(tmpFilesIn(generatePath)).toEqual([]);
45
47
  const body = await response.arrayBuffer();
46
48
  expect(response.headers.get("Content-Length")).toBe(String(body.byteLength));
47
49
  const metadata = await (0, sharp_1.default)(Buffer.from(body)).metadata();
@@ -61,5 +63,6 @@ test("responds 404 when the source file is missing", async () => {
61
63
  const response = await handler(new Request("http://localhost/generated/static/20_x_cv_c_FFF_nt_x/1/missing.png.webp"));
62
64
  expect(response.status).toBe(404);
63
65
  expect(errorSpy).toHaveBeenCalled();
66
+ expect(tmpFilesIn(generatePath)).toEqual([]);
64
67
  errorSpy.mockRestore();
65
68
  });
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * @jest-environment node
3
3
  */
4
- import { existsSync, mkdirSync, mkdtempSync, rmSync } from "fs";
4
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from "fs";
5
5
  import { tmpdir } from "os";
6
6
  import { join } from "path";
7
7
  import sharp from "sharp";
@@ -16,6 +16,9 @@ let generatePath: string;
16
16
  let handler: (request: Request) => Promise<Response>;
17
17
  let logSpy: jest.SpyInstance;
18
18
 
19
+ const tmpFilesIn = (dir: string) =>
20
+ existsSync(dir) ? readdirSync(dir, { recursive: true }).filter((f) => String(f).endsWith(".tmp")) : [];
21
+
19
22
  beforeAll(async () => {
20
23
  workDir = mkdtempSync(join(tmpdir(), "uxf-resizer-"));
21
24
  sourceDir = join(workDir, "source");
@@ -47,6 +50,7 @@ test("generates, caches and serves a resized image", async () => {
47
50
  expect(response.headers.get("Content-Type")).toBe("image/webp");
48
51
  expect(response.headers.get("Last-Modified")).toBeTruthy();
49
52
  expect(existsSync(generatePath + path)).toBe(true);
53
+ expect(tmpFilesIn(generatePath)).toEqual([]);
50
54
 
51
55
  const body = await response.arrayBuffer();
52
56
  expect(response.headers.get("Content-Length")).toBe(String(body.byteLength));
@@ -75,5 +79,6 @@ test("responds 404 when the source file is missing", async () => {
75
79
 
76
80
  expect(response.status).toBe(404);
77
81
  expect(errorSpy).toHaveBeenCalled();
82
+ expect(tmpFilesIn(generatePath)).toEqual([]);
78
83
  errorSpy.mockRestore();
79
84
  });
package/src/handler.ts CHANGED
@@ -1,6 +1,8 @@
1
+ import { randomUUID } from "crypto";
1
2
  import { existsSync } from "fs";
2
- import { copyFile, mkdir, readFile, stat, writeFile } from "fs/promises";
3
+ import { copyFile, mkdir, readFile, rename, rm, stat, writeFile } from "fs/promises";
3
4
  import { dirname } from "path";
5
+ import { fetchSource } from "./utils/fetch-source";
4
6
  import { getSourceFilename } from "./utils/get-source-filename";
5
7
  import { convertImage } from "./utils/image-converter";
6
8
  import { log } from "./utils/log";
@@ -45,13 +47,20 @@ async function fileResponse(filename: string, contentType: string): Promise<Resp
45
47
  });
46
48
  }
47
49
 
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}`);
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 });
52
63
  }
53
-
54
- return response.arrayBuffer();
55
64
  }
56
65
 
57
66
  /**
@@ -101,16 +110,17 @@ export function createResizerHandler(config: Config): (request: Request) => Prom
101
110
 
102
111
  if (params.toFormat === "svg") {
103
112
  if (isRemote) {
104
- await writeFile(generatedFilename, Buffer.from(await fetchSource(sourceFilename)));
113
+ const svg = Buffer.from(await fetchSource(sourceFilename));
114
+ await writeAtomically(generatedFilename, (tmpFilename) => writeFile(tmpFilename, svg));
105
115
  } else {
106
- await copyFile(sourceFilename, generatedFilename);
116
+ await writeAtomically(generatedFilename, (tmpFilename) => copyFile(sourceFilename, tmpFilename));
107
117
  }
108
118
 
109
119
  return await fileResponse(generatedFilename, contentType);
110
120
  }
111
121
 
112
122
  const sourceFile = isRemote ? await fetchSource(sourceFilename) : sourceFilename;
113
- await convertImage(sourceFile, generatedFilename, params);
123
+ await writeAtomically(generatedFilename, (tmpFilename) => convertImage(sourceFile, tmpFilename, params));
114
124
 
115
125
  return await fileResponse(generatedFilename, contentType);
116
126
  } catch (e) {
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
+ }