summaryrefslogtreecommitdiff
path: root/packages/integrations/image/src/build/ssg.ts
blob: 2a6976d76adc6eee6d9af1aaed0f7878fd9dd70b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import { doWork } from '@altano/tiny-async-pool';
import type { AstroConfig } from 'astro';
import CachePolicy from 'http-cache-semantics';
import { bgGreen, black, cyan, dim, green } from 'kleur/colors';
import fs from 'node:fs/promises';
import OS from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { SSRImageService, TransformOptions } from '../loaders/index.js';
import { debug, info, warn, type LoggerLevel } from '../utils/logger.js';
import { isRemoteImage, prependForwardSlash } from '../utils/paths.js';
import { ImageCache } from './cache.js';

async function loadLocalImage(src: string | URL) {
	try {
		const data = await fs.readFile(src);

		// Vite's file hash will change if the file is changed at all,
		// we can safely cache local images here.
		const timeToLive = new Date();
		timeToLive.setFullYear(timeToLive.getFullYear() + 1);

		return {
			data,
			expires: timeToLive.getTime(),
		};
	} catch {
		return undefined;
	}
}

function webToCachePolicyRequest({ url, method, headers: _headers }: Request): CachePolicy.Request {
	let headers: CachePolicy.Headers = {};
	// Be defensive here due to a cookie header bug in node@18.14.1 + undici
	try {
		headers = Object.fromEntries(_headers.entries());
	} catch {}
	return {
		method,
		url,
		headers,
	};
}

function webToCachePolicyResponse({ status, headers: _headers }: Response): CachePolicy.Response {
	let headers: CachePolicy.Headers = {};
	// Be defensive here due to a cookie header bug in node@18.14.1 + undici
	try {
		headers = Object.fromEntries(_headers.entries());
	} catch {}
	return {
		status,
		headers,
	};
}

async function loadRemoteImage(src: string) {
	try {
		if (src.startsWith('//')) {
			src = `https:${src}`;
		}

		const req = new Request(src);
		const res = await fetch(req);

		if (!res.ok) {
			return undefined;
		}

		// calculate an expiration date based on the response's TTL
		const policy = new CachePolicy(webToCachePolicyRequest(req), webToCachePolicyResponse(res));
		const expires = policy.storable() ? policy.timeToLive() : 0;

		return {
			data: Buffer.from(await res.arrayBuffer()),
			expires: Date.now() + expires,
		};
	} catch (err: unknown) {
		console.error(err);
		return undefined;
	}
}

function getTimeStat(timeStart: number, timeEnd: number) {
	const buildTime = timeEnd - timeStart;
	return buildTime < 750 ? `${Math.round(buildTime)}ms` : `${(buildTime / 1000).toFixed(2)}s`;
}

export interface SSGBuildParams {
	loader: SSRImageService;
	staticImages: Map<string, Map<string, TransformOptions>>;
	config: AstroConfig;
	outDir: URL;
	logLevel: LoggerLevel;
	cacheDir?: URL;
}

export async function ssgBuild({
	loader,
	staticImages,
	config,
	outDir,
	logLevel,
	cacheDir,
}: SSGBuildParams) {
	let cache: ImageCache | undefined = undefined;

	if (cacheDir) {
		cache = new ImageCache(cacheDir, logLevel);
		await cache.init();
	}

	const timer = performance.now();
	const cpuCount = OS.cpus().length;

	info({
		level: logLevel,
		prefix: false,
		message: `${bgGreen(
			black(
				` optimizing ${staticImages.size} image${
					staticImages.size > 1 ? 's' : ''
				} in batches of ${cpuCount} `
			)
		)}`,
	});

	async function processStaticImage([src, transformsMap]: [
		string,
		Map<string, TransformOptions>
	]): Promise<void> {
		let inputFile: string | undefined = undefined;
		let inputBuffer: Buffer | undefined = undefined;

		// tracks the cache duration for the original source image
		let expires = 0;

		// Strip leading assetsPrefix or base added by addStaticImage
		if (config.build.assetsPrefix) {
			if (src.startsWith(config.build.assetsPrefix)) {
				src = prependForwardSlash(src.slice(config.build.assetsPrefix.length));
			}
		} else if (config.base) {
			if (src.startsWith(config.base)) {
				src = prependForwardSlash(src.slice(config.base.length));
			}
		}

		if (isRemoteImage(src)) {
			// try to load the remote image
			const res = await loadRemoteImage(src);

			inputBuffer = res?.data;
			expires = res?.expires || 0;
		} else {
			const inputFileURL = new URL(`.${src}`, outDir);
			inputFile = fileURLToPath(inputFileURL);

			const res = await loadLocalImage(inputFile);
			inputBuffer = res?.data;
			expires = res?.expires || 0;
		}

		if (!inputBuffer) {
			// eslint-disable-next-line no-console
			warn({ level: logLevel, message: `"${src}" image could not be fetched` });
			return;
		}

		const transforms = Array.from(transformsMap.entries());

		debug({ level: logLevel, prefix: false, message: `${green('▶')} transforming ${src}` });
		let timeStart = performance.now();

		// process each transformed version
		for (const [filename, transform] of transforms) {
			timeStart = performance.now();
			let outputFile: string;
			let outputFileURL: URL;

			if (isRemoteImage(src)) {
				outputFileURL = new URL(
					path.join(`./${config.build.assets}`, path.basename(filename)),
					outDir
				);
				outputFile = fileURLToPath(outputFileURL);
			} else {
				outputFileURL = new URL(path.join(`./${config.build.assets}`, filename), outDir);
				outputFile = fileURLToPath(outputFileURL);
			}

			const pathRelative = outputFile.replace(fileURLToPath(outDir), '');

			let data: Buffer | undefined;

			// try to load the transformed image from cache, if available
			if (cache?.has(pathRelative)) {
				data = await cache.get(pathRelative);
			}

			// a valid cache file wasn't found, transform the image and cache it
			if (!data) {
				const transformed = await loader.transform(inputBuffer, transform);
				data = transformed.data;

				// cache the image, if available
				if (cache) {
					await cache.set(pathRelative, data, { expires });
				}
			}

			const outputFolder = new URL('./', outputFileURL);
			await fs.mkdir(outputFolder, { recursive: true });
			await fs.writeFile(outputFile, data);

			const timeEnd = performance.now();
			const timeChange = getTimeStat(timeStart, timeEnd);
			const timeIncrease = `(+${timeChange})`;

			debug({
				level: logLevel,
				prefix: false,
				message: `  ${cyan('created')} ${dim(pathRelative)} ${dim(timeIncrease)}`,
			});
		}
	}

	// transform each original image file in batches
	await doWork(cpuCount, staticImages, processStaticImage);

	// saves the cache's JSON manifest to file
	if (cache) {
		await cache.finalize();
	}

	info({
		level: logLevel,
		prefix: false,
		message: dim(`Completed in ${getTimeStat(timer, performance.now())}.\n`),
	});
}