deno.land / x / lume@v2.1.4 / plugins / transform_images.ts

transform_images.ts
نووسراو ببینە
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
import { getPathAndExtension } from "../core/utils/path.ts";import { log } from "../core/utils/log.ts";import { merge } from "../core/utils/object.ts";import { concurrent } from "../core/utils/concurrent.ts";import binaryLoader from "../core/loaders/binary.ts";import sharp, { create } from "../deps/sharp.ts";import Cache from "../core/cache.ts";
import type Site from "../core/site.ts";import type { Page } from "../core/file.ts";
export interface Options { /** The list extensions this plugin applies to */ extensions: string[];
/** The key name for the transformations definitions */ name: string;
/** The cache folder */ cache: string | boolean;
/** Custom transform functions */ functions: Record<string, TransformationFunction>;}
export type TransformationFunction = ( image: sharp.Sharp, // deno-lint-ignore no-explicit-any ...args: any[]) => void;
// Default optionsexport const defaults: Options = { extensions: [".jpg", ".jpeg", ".png", ".webp"], name: "transformImages", cache: true, functions: { resize( image: sharp.Sharp, width: number, height?: number, options: sharp.ResizeOptions = { withoutEnlargement: true }, ): void { image.resize(width, height, options); }, blur(image: sharp.Sharp, sigma?: number | boolean): void { image.blur(sigma); }, rotate(image: sharp.Sharp, degrees: number): void { image.rotate(degrees); }, },};
export type Format = | "jpeg" | "jp2" | "jxl" | "png" | "webp" | "gif" | "avif" | "heif" | "tiff";export interface FormatOptions { format: Format; [key: string]: unknown;}
export interface Transformation { suffix?: string; format?: Format | Format[] | FormatOptions | FormatOptions[]; matches?: RegExp | string; // deno-lint-ignore no-explicit-any [key: string]: any;}interface SingleTransformation extends Transformation { format?: Format | FormatOptions;}
/** A plugin to transform images in Lume */export default function (userOptions?: Partial<Options>) { const options = merge(defaults, userOptions);
return (site: Site) => { site.loadAssets(options.extensions, binaryLoader); site.process(options.extensions, process);
// Configure the cache folder const cacheFolder = options.cache === true ? "_cache" : options.cache; const cache = cacheFolder ? new Cache({ folder: site.src(cacheFolder) }) : undefined;
if (cacheFolder) { site.ignore(cacheFolder); site.options.watcher.ignore.push(cacheFolder); }
async function process(pages: Page[], allPages: Page[]) { await concurrent( pages, (page) => processPage(page, allPages), ); } async function processPage(page: Page, allPages: Page[]) { const transData = page.data[options.name] as | Transformation | Transformation[] | undefined;
if (!transData) { return; }
const content = page.content as Uint8Array | string; const transformations = removeDuplicatedTransformations( getTransformations(transData), ); let transformed = false; let index = 0; for (const transformation of transformations) { if (transformation.matches) { const regex = new RegExp(transformation.matches); if (!regex.test(page.data.url as string)) { continue; } }
const output = page.duplicate(index++, { ...page.data, [options.name]: undefined, });
rename(output, transformation);
if (cache) { const result = await cache.get(content, transformation);
if (result) { output.content = result; } else { await transform(content, output, transformation, options); transformed = true; await cache.set(content, transformation, output.content!); } } else { await transform(content, output, transformation, options); transformed = true; }
if (output !== page) { allPages.push(output); } }
if (transformed) { log.info(`[transform_images plugin] Processed ${page.sourcePath}`); }
// Remove the original page allPages.splice(allPages.indexOf(page), 1); } };}
async function transform( content: Uint8Array | string, page: Page, transformation: Transformation, options: Options,): Promise<void> { const image = await create(content);
for (const [name, args] of Object.entries(transformation)) { switch (name) { case "suffix": case "matches": break;
case "format": if (typeof args === "string") { image.toFormat(args as Format); } else { const { format, ...options } = args as Record<string, unknown>; image.toFormat(format as Format, options); } break;
default: if (!options.functions[name]) { throw new Error(`Unknown transformation: ${name}`); }
if (Array.isArray(args)) { options.functions[name](image, ...args); } else { options.functions[name](image, args); } } }
page.content = new Uint8Array(await image.toBuffer());}
function rename(page: Page, transformation: SingleTransformation): void { const { format, suffix } = transformation; let [path, ext] = getPathAndExtension(page.data.url);
if (format) { ext = typeof format === "string" ? `.${format}` : `.${format.format}`; }
if (suffix) { path += suffix; }
page.data.url = path + ext;}
function getTransformations( input: Transformation | Transformation[],): SingleTransformation[] { if (Array.isArray(input)) { const singles: SingleTransformation[] = [];
for (const transformation of input) { if (Array.isArray(transformation.format)) { transformation.format.forEach((format) => { singles.push({ ...transformation, format }); }); } else { singles.push(transformation as SingleTransformation); } } return singles; }
if (Array.isArray(input.format)) { return input.format.map((format) => ({ ...input, format })); }
return [input as SingleTransformation];}
function removeDuplicatedTransformations( transformations: SingleTransformation[],): SingleTransformation[] { const result = new Map<string, SingleTransformation>();
for (const transformation of transformations) { const { format, suffix, matches } = transformation; const key = `${format}:${suffix ?? ""}${matches ?? ""}`; result.set(key, transformation); }
return [...result.values()];}
/** Extends Data interface */declare global { namespace Lume { export interface Data { /** * Image transformations * @see https://lume.land/plugins/transform_images/ */ transformImages?: Transformation | Transformation[]; } }}
lume

Version Info

Tagged at
7 months ago