metalsmith-optimize-images 0.10.3 → 1.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/lib/index.js DELETED
@@ -1,1543 +0,0 @@
1
- import path from 'path';
2
- import fs from 'fs';
3
- import * as mkdirp from 'mkdirp';
4
- import sharp from 'sharp';
5
- import * as cheerio from 'cheerio';
6
- import crypto from 'crypto';
7
-
8
- /**
9
- * Configuration utility for the plugin
10
- * Handles merging user options with sensible defaults
11
- */
12
-
13
- /**
14
- * Deep merge for objects
15
- * @param {Object} target - Target object
16
- * @param {Object} source - Source object
17
- * @return {Object} - Merged result
18
- */
19
- /*
20
- function deepMerge( target, source ) {
21
- const result = { ...target };
22
-
23
- for ( const key in source ) {
24
- if ( source[key] instanceof Object && key in target && target[key] instanceof Object ) {
25
- result[key] = deepMerge( target[key], source[key] );
26
- } else {
27
- result[key] = source[key];
28
- }
29
- }
30
-
31
- return result;
32
- }
33
- */
34
-
35
- // Modern functional approach to deep merge - handles nested objects properly
36
- // This is needed for formatOptions and placeholder options which are nested objects
37
- const deepMerge = (target, source) => Object.keys(source).reduce((acc, key) => {
38
- var _source$key;
39
- return {
40
- ...acc,
41
- [key]: ((_source$key = source[key]) == null ? void 0 : _source$key.constructor) === Object ? deepMerge(target[key] || {}, source[key]) : source[key]
42
- };
43
- }, {
44
- ...target
45
- });
46
-
47
- /**
48
- * Builds configuration with sensible defaults
49
- * @param {Object} options - User provided plugin options
50
- * @return {Object} - Complete config with defaults
51
- */
52
- function buildConfig(options = {}) {
53
- // Default configuration with sensible defaults
54
- const defaults = {
55
- // Responsive breakpoints to generate
56
- widths: [320, 640, 960, 1280, 1920],
57
- // Formats to generate in order of preference (first is most preferred)
58
- formats: ['avif', 'webp', 'original'],
59
- // Format-specific compression settings
60
- formatOptions: {
61
- avif: {
62
- quality: 65,
63
- speed: 5
64
- },
65
- // Better compression but slower
66
- webp: {
67
- quality: 80,
68
- lossless: false
69
- },
70
- jpeg: {
71
- quality: 85,
72
- progressive: true
73
- },
74
- png: {
75
- compressionLevel: 8,
76
- palette: true
77
- }
78
- },
79
- // Which HTML files to process
80
- htmlPattern: '**/*.html',
81
- // CSS selector for images to process
82
- imgSelector: 'img:not([data-no-responsive])',
83
- // Output directory for processed images (relative to Metalsmith destination)
84
- outputDir: 'assets/images/responsive',
85
- // Output naming pattern
86
- // Available tokens: [filename], [width], [format], [hash]
87
- outputPattern: '[filename]-[width]w-[hash].[format]',
88
- // Whether to skip generating sizes larger than original
89
- skipLarger: true,
90
- // Add loading="lazy" to images
91
- lazy: true,
92
- // Add width and height attributes to prevent layout shift
93
- dimensionAttributes: true,
94
- // Default sizes attribute value for responsive images
95
- sizes: '(max-width: 768px) 100vw, 75vw',
96
- // Maximum number of images to process in parallel
97
- concurrency: 5,
98
- // Whether to generate a metadata JSON file
99
- generateMetadata: false,
100
- // Progressive loading options
101
- isProgressive: false,
102
- // TODO: Debug timeout issue in tests
103
-
104
- // Placeholder image settings for progressive loading
105
- placeholder: {
106
- width: 50,
107
- quality: 30,
108
- blur: 10
109
- },
110
- // Background image processing settings
111
- processUnusedImages: true,
112
- // Process images not found in HTML for background use
113
- imagePattern: '**/*.{jpg,jpeg,png,gif,webp,avif}' // Pattern to find images for background processing
114
- };
115
-
116
- // Special handling for formatOptions to ensure deep merging
117
- // This allows users to override specific format settings without losing defaults
118
- // e.g., { formatOptions: { jpeg: { quality: 90 } } } only changes JPEG quality
119
- if (options && options.formatOptions) {
120
- options = {
121
- ...options,
122
- formatOptions: deepMerge(defaults.formatOptions, options.formatOptions)
123
- };
124
- }
125
-
126
- // Special handling for placeholder options to ensure deep merging
127
- // Allows partial placeholder config like { placeholder: { width: 100 } }
128
- if (options && options.placeholder) {
129
- options = {
130
- ...options,
131
- placeholder: deepMerge(defaults.placeholder, options.placeholder)
132
- };
133
- }
134
-
135
- // Merge the defaults with user options
136
- return {
137
- ...defaults,
138
- ...(options || {})
139
- };
140
- }
141
-
142
- /**
143
- * Utility for generating content hashes
144
- * Used for cache-busting - ensures filenames change when image content changes
145
- */
146
-
147
- /**
148
- * Generates a short hash based on image content
149
- * Creates an 8-character hash for cache-busting in filenames
150
- * @param {Buffer} buffer - The image buffer
151
- * @return {string} - A short hash string (8 characters)
152
- */
153
- function generateHash(buffer) {
154
- // SHA-256 for cache-busting - using secure algorithm to satisfy security scanners
155
- // Only use first 8 characters to keep filenames manageable
156
- return crypto.createHash('sha256').update(buffer).digest('hex').slice(0, 8);
157
- }
158
-
159
- /**
160
- * Path utilities for image variants
161
- * Handles the filename pattern system with token replacement
162
- */
163
-
164
- /**
165
- * Generate variant filename using pattern
166
- * Applies token replacement to create output filenames
167
- * Tokens: [filename], [width], [format], [hash]
168
- * @param {string} originalPath - Original image path
169
- * @param {number} width - Target width
170
- * @param {string} format - Target format ('original' means keep source format)
171
- * @param {string} hash - Content hash for cache busting
172
- * @param {object} config - Plugin config options
173
- * @return {string} - Generated path relative to Metalsmith destination
174
- */
175
- function generateVariantPath(originalPath, width, format, hash, config) {
176
- const parsedPath = path.parse(originalPath);
177
- const originalFormat = parsedPath.ext.slice(1).toLowerCase();
178
-
179
- // If format is 'original', use the source format (e.g., 'jpeg' for image.jpg)
180
- const outputFormat = format === 'original' ? originalFormat : format;
181
-
182
- // Apply pattern replacements using the tokens system
183
- // Default pattern: '[filename]-[width]w-[hash].[format]'
184
- // Results in: 'image-320w-abc12345.webp'
185
- const outputName = config.outputPattern.replace('[filename]', parsedPath.name).replace('[width]', width).replace('[format]', outputFormat).replace('[hash]', hash || '');
186
- return path.join(config.outputDir, outputName);
187
- }
188
-
189
- /**
190
- * Image processing utilities for creating responsive image variants
191
- * Handles the core Sharp.js operations for resizing and format conversion
192
- */
193
-
194
- /**
195
- * Process an image into multiple responsive variants and formats
196
- * @param {Buffer} buffer - Original image buffer
197
- * @param {string} originalPath - Original image path
198
- * @param {Function} debugFn - Debug function for logging
199
- * @param {Object} config - Plugin configuration
200
- * @return {Promise<Array<Object>>} - Array of generated variants
201
- */
202
- async function processImageToVariants(buffer, originalPath, debugFn, config) {
203
- const image = sharp(buffer);
204
- const metadata = await image.metadata();
205
- const variants = [];
206
- const hash = generateHash(buffer);
207
-
208
- // Determine which widths to generate based on skipLarger setting
209
- // If skipLarger is true (default), don't generate sizes larger than original
210
- const targetWidths = config.skipLarger ? config.widths.filter(w => w <= metadata.width) : config.widths;
211
- if (targetWidths.length === 0) {
212
- debugFn(`Skipping ${originalPath} - no valid target widths`);
213
- return [];
214
- }
215
-
216
- // Process all widths in parallel for better performance
217
- const widthPromises = targetWidths.map(async width => {
218
- // Create a Sharp instance for this width - clone to avoid conflicts
219
- const resized = image.clone().resize({
220
- width,
221
- withoutEnlargement: config.skipLarger // Prevents upscaling small images
222
- });
223
-
224
- // Get actual dimensions after resize (may be smaller than requested width)
225
- const resizedMeta = await resized.metadata();
226
-
227
- // Process each format in parallel for this width
228
- const formatPromises = config.formats.map(async format => {
229
- try {
230
- // Skip problematic format combinations (e.g., webp -> original doesn't make sense)
231
- if (format === 'original' && metadata.format.toLowerCase() === 'webp') {
232
- return null;
233
- }
234
- let formatted;
235
- const outputPath = generateVariantPath(originalPath, width, format, hash, config);
236
-
237
- // Apply format-specific processing with quality/compression settings
238
- if (format === 'original') {
239
- // For 'original' format, use the source image format
240
- const originalFormat = metadata.format.toLowerCase();
241
- const formatOptions = config.formatOptions[originalFormat] || {};
242
- formatted = resized.clone().toFormat(originalFormat, formatOptions);
243
- } else {
244
- // For specific formats (avif, webp, etc.), apply format-specific options
245
- const formatOptions = config.formatOptions[format] || {};
246
- if (format === 'avif') {
247
- formatted = resized.clone().avif(formatOptions);
248
- } else if (format === 'webp') {
249
- formatted = resized.clone().webp(formatOptions);
250
- } else if (format === 'jpeg') {
251
- formatted = resized.clone().jpeg(formatOptions);
252
- } else if (format === 'png') {
253
- formatted = resized.clone().png(formatOptions);
254
- } else {
255
- formatted = resized.clone()[format](formatOptions);
256
- }
257
- }
258
-
259
- // Generate the actual image buffer - this is where compression happens
260
- const formatBuffer = await formatted.toBuffer();
261
- return {
262
- path: outputPath,
263
- buffer: formatBuffer,
264
- width,
265
- format: format === 'original' ? metadata.format.toLowerCase() : format,
266
- originalFormat: metadata.format.toLowerCase(),
267
- size: formatBuffer.length,
268
- height: resizedMeta.height
269
- };
270
- } catch (err) {
271
- debugFn(`Error generating ${format} variant for ${originalPath} at width ${width}: ${err.message}`);
272
- return null;
273
- }
274
- });
275
-
276
- // Wait for all formats at this width to complete
277
- const formatResults = await Promise.all(formatPromises);
278
- return formatResults.filter(v => v !== null);
279
- });
280
-
281
- // Wait for all widths to complete and flatten the results
282
- const widthResults = await Promise.all(widthPromises);
283
- variants.push(...widthResults.flat());
284
- return variants;
285
- }
286
-
287
- /**
288
- * Process a single image
289
- * @param {Object} context - Processing context
290
- * @param {Object} context.$ - Cheerio instance
291
- * @param {Object} context.img - Image DOM element
292
- * @param {Object} context.files - Metalsmith files object
293
- * @param {Object} context.metalsmith - Metalsmith instance
294
- * @param {Map} context.processedImages - Cache of processed images
295
- * @param {Function} context.debug - Debug function
296
- * @param {Object} context.config - Plugin configuration
297
- * @param {Function} context.replacePictureElement - Function to replace img with picture
298
- * @return {Promise<void>} - Promise that resolves when the image is processed
299
- */
300
- async function processImage({
301
- $,
302
- img,
303
- files,
304
- metalsmith,
305
- processedImages,
306
- debug,
307
- config,
308
- replacePictureElement
309
- }) {
310
- const $img = $(img);
311
- const src = $img.attr('src');
312
- if (!src || src.startsWith('http') || src.startsWith('data:')) {
313
- debug(`Skipping external or data URL: ${src}`);
314
- return;
315
- }
316
-
317
- // Skip SVG files - they are vector graphics that don't need responsive raster variants
318
- if (src.toLowerCase().endsWith('.svg')) {
319
- debug(`Skipping SVG file (vector graphics don't need responsive variants): ${src}`);
320
- return;
321
- }
322
-
323
- // Normalize src path to match Metalsmith files object keys
324
- // Remove leading slash if present (HTML paths vs Metalsmith file keys)
325
- const normalizedSrc = src.startsWith('/') ? src.slice(1) : src;
326
-
327
- // Image not in Metalsmith files object - try to load it from the build directory
328
- // This handles cases where images were copied by other plugins (like assets)
329
- if (!files[normalizedSrc]) {
330
- try {
331
- const destination = metalsmith.destination();
332
- const imagePath = path.join(destination, normalizedSrc);
333
- if (fs.existsSync(imagePath)) {
334
- // Load the image contents from the build directory
335
- const imageBuffer = fs.readFileSync(imagePath);
336
-
337
- // Get modification time for cache busting - this helps with incremental builds
338
- const mtime = fs.statSync(imagePath).mtimeMs;
339
-
340
- // Add it to Metalsmith files so the plugin can process it
341
- files[normalizedSrc] = {
342
- contents: imageBuffer,
343
- mtime
344
- };
345
- } else {
346
- debug(`Image not found in build: ${normalizedSrc}`);
347
- return;
348
- }
349
- } catch (err) {
350
- debug(`Error processing image from build directory: ${err.message}`);
351
- return;
352
- }
353
- }
354
-
355
- // Create a cache key that includes the file path and modification time
356
- // This prevents reprocessing the same image multiple times in a single build
357
- const fileMtime = files[normalizedSrc].mtime || Date.now();
358
- const cacheKey = `${normalizedSrc}:${fileMtime}`;
359
-
360
- // Check if we've already processed this exact image (same file + mtime)
361
- if (processedImages.has(cacheKey)) {
362
- debug(`Using cached variants for ${normalizedSrc}`);
363
- const variants = processedImages.get(cacheKey);
364
- replacePictureElement($, $img, variants, config);
365
- return;
366
- }
367
- debug(`Processing image: ${normalizedSrc}`);
368
- try {
369
- // Process image to generate all variants (different sizes and formats)
370
- const variants = await processImageToVariants(files[normalizedSrc].contents, normalizedSrc, debug, config);
371
-
372
- // Save all generated variants to Metalsmith files object
373
- // This makes them available in the final build output
374
- variants.forEach(variant => {
375
- files[variant.path] = {
376
- contents: variant.buffer
377
- };
378
- });
379
-
380
- // Cache variants for this image to avoid reprocessing
381
- processedImages.set(cacheKey, variants);
382
-
383
- // Replace the original <img> tag with a responsive <picture> element
384
- replacePictureElement($, $img, variants, config);
385
- } catch (err) {
386
- debug(`Error processing image: ${err.message}`);
387
- }
388
- }
389
-
390
- /**
391
- * Progressive image loading processor
392
- * Handles placeholder generation and smooth loading transitions
393
- */
394
-
395
- /**
396
- * Generate placeholder image for progressive loading
397
- * Creates a small, blurred, low-quality version for instant display
398
- * @param {string} imagePath - Original image path
399
- * @param {Buffer} imageBuffer - Original image buffer
400
- * @param {Object} placeholderConfig - Placeholder configuration (width, quality, blur)
401
- * @param {Object} metalsmith - Metalsmith instance
402
- * @return {Promise<Object>} Placeholder data with path and contents
403
- */
404
- async function generatePlaceholder(imagePath, imageBuffer, placeholderConfig, metalsmith) {
405
- const {
406
- width,
407
- quality,
408
- blur
409
- } = placeholderConfig;
410
- try {
411
- // Get original image dimensions for aspect ratio calculation
412
- const image = sharp(imageBuffer);
413
- const metadata = await image.metadata();
414
-
415
- // Process image: resize to small width, blur heavily, compress heavily
416
- const processed = await image.resize(width) // Default: 50px wide
417
- .blur(blur) // Default: 10px blur
418
- .jpeg({
419
- quality
420
- }) // Default: 30% quality
421
- .toBuffer();
422
- const fileName = `${path.basename(imagePath, path.extname(imagePath))}-placeholder.jpg`;
423
- const outputPath = path.join('assets/images/responsive', fileName);
424
- return {
425
- path: outputPath,
426
- contents: processed,
427
- fileName,
428
- originalWidth: metadata.width,
429
- originalHeight: metadata.height
430
- };
431
- } catch (error) {
432
- metalsmith.debug('metalsmith-optimize-images')(`Error generating placeholder for ${imagePath}: ${error.message}`);
433
- throw error;
434
- }
435
- }
436
-
437
- /**
438
- * Create progressive wrapper HTML structure
439
- * Creates a container with both placeholder and high-res images for smooth transitions
440
- * @param {Object} $ - Cheerio instance
441
- * @param {Object} $img - Original img element
442
- * @param {Array} variants - Generated image variants
443
- * @param {Object} placeholderData - Placeholder image data
444
- * @param {Object} config - Plugin configuration
445
- * @return {Object} Cheerio element for progressive wrapper
446
- */
447
- function createProgressiveWrapper($, $img, variants, placeholderData, _config) {
448
- // Get original attributes
449
- const alt = $img.attr('alt') || '';
450
- const className = $img.attr('class') || '';
451
-
452
- // Group variants by format - use only original format for progressive mode
453
- // Progressive mode focuses on smooth loading rather than format optimization
454
- const variantsByFormat = {};
455
- variants.forEach(v => {
456
- if (!variantsByFormat[v.format]) {
457
- variantsByFormat[v.format] = [];
458
- }
459
- variantsByFormat[v.format].push(v);
460
- });
461
-
462
- // Get original format variants (skip AVIF/WebP for progressive mode)
463
- // JavaScript will handle format detection dynamically
464
- const originalFormat = Object.keys(variantsByFormat).find(f => f !== 'avif' && f !== 'webp');
465
- const originalVariants = originalFormat ? variantsByFormat[originalFormat] : [];
466
- if (originalVariants.length === 0) {
467
- return $img.clone(); // Fallback if no variants
468
- }
469
-
470
- // Calculate aspect ratio using original image dimensions to prevent layout shift
471
- // Fallback to variant dimensions if placeholderData doesn't have original dimensions
472
- let aspectRatio;
473
- if (placeholderData.originalWidth && placeholderData.originalHeight) {
474
- aspectRatio = `${placeholderData.originalWidth}/${placeholderData.originalHeight}`;
475
- } else {
476
- // Fallback: use the largest variant for most accurate aspect ratio
477
- const largestVariant = [...originalVariants].sort((a, b) => b.width - a.width)[0];
478
- aspectRatio = `${largestVariant.width}/${largestVariant.height}`;
479
- }
480
-
481
- // Find middle-sized variant for high-res image (good balance of quality/size)
482
- const highResVariant = originalVariants[Math.floor(originalVariants.length / 2)];
483
-
484
- // Create wrapper div with modern CSS aspect-ratio
485
- const $wrapper = $('<div>').addClass('responsive-wrapper js-progressive-image-wrapper').attr('style', `aspect-ratio: ${aspectRatio}`);
486
-
487
- // Add class from original image if present
488
- if (className) {
489
- $wrapper.addClass(className);
490
- }
491
-
492
- // Create low-res image (placeholder) - shown immediately
493
- const $lowRes = $('<img>').addClass('low-res').attr('src', `/${placeholderData.path}`).attr('alt', alt);
494
-
495
- // Create high-res image (empty with data source) - loaded by JavaScript
496
- const $highRes = $('<img>').addClass('high-res').attr('src', '').attr('alt', alt).attr('data-source', `/${highResVariant.path}`);
497
-
498
- // Assemble the progressive wrapper
499
- $lowRes.appendTo($wrapper);
500
- $highRes.appendTo($wrapper);
501
- return $wrapper;
502
- }
503
-
504
- /**
505
- * Create standard picture element HTML
506
- * Fallback function for when progressive loading fails
507
- * @param {Object} $ - Cheerio instance
508
- * @param {Object} $img - Original img element
509
- * @param {Array} variants - Generated image variants
510
- * @param {Object} config - Plugin configuration
511
- * @return {Object} Cheerio element for picture
512
- */
513
- function createStandardPicture($, $img, variants, config) {
514
- // Get original attributes
515
- const src = $img.attr('src');
516
- const alt = $img.attr('alt') || '';
517
- const className = $img.attr('class') || '';
518
- const sizesAttr = $img.attr('sizes') || config.sizes;
519
-
520
- // Group variants by format
521
- const variantsByFormat = {};
522
- variants.forEach(v => {
523
- if (!variantsByFormat[v.format]) {
524
- variantsByFormat[v.format] = [];
525
- }
526
- variantsByFormat[v.format].push(v);
527
- });
528
-
529
- // Create picture element with all formats (standard mode)
530
- const $picture = $('<picture>');
531
-
532
- // Add format-specific source elements in preference order
533
- ['avif', 'webp'].forEach(format => {
534
- const formatVariants = variantsByFormat[format];
535
- if (!formatVariants || formatVariants.length === 0) {
536
- return;
537
- }
538
-
539
- // Sort variants by width
540
- formatVariants.sort((a, b) => a.width - b.width);
541
-
542
- // Create srcset string
543
- const srcset = formatVariants.map(v => `/${v.path} ${v.width}w`).join(', ');
544
-
545
- // Create source element
546
- $('<source>').attr('type', `image/${format}`).attr('srcset', srcset).attr('sizes', sizesAttr).appendTo($picture);
547
- });
548
-
549
- // Add original format as img element
550
- const originalFormat = Object.keys(variantsByFormat).find(f => f !== 'avif' && f !== 'webp');
551
- if (originalFormat && variantsByFormat[originalFormat]) {
552
- var _formatVariants$Math$;
553
- const formatVariants = variantsByFormat[originalFormat];
554
- formatVariants.sort((a, b) => a.width - b.width);
555
- const srcset = formatVariants.map(v => `/${v.path} ${v.width}w`).join(', ');
556
- const defaultSrc = (_formatVariants$Math$ = formatVariants[Math.floor(formatVariants.length / 2)]) == null ? void 0 : _formatVariants$Math$.path;
557
-
558
- // Create new img element
559
- const $newImg = $('<img>').attr('src', defaultSrc ? `/${defaultSrc}` : src).attr('srcset', srcset).attr('sizes', sizesAttr).attr('alt', alt).attr('loading', 'lazy');
560
-
561
- // Add class if present
562
- if (className) {
563
- $newImg.attr('class', className);
564
- }
565
-
566
- // Add width/height attributes if configured and available
567
- if (config.dimensionAttributes && variants.length > 0) {
568
- const largestVariant = [...variants].sort((a, b) => b.width - a.width)[0];
569
- $newImg.attr('width', largestVariant.width);
570
- $newImg.attr('height', largestVariant.height);
571
- }
572
- $newImg.appendTo($picture);
573
- }
574
- return $picture;
575
- }
576
-
577
- /**
578
- * Progressive image loader JavaScript
579
- * Handles intersection observer, format detection, and smooth loading transitions
580
- */
581
- const progressiveImageLoader = `
582
- (function() {
583
- 'use strict';
584
-
585
- // Cache for detected format support
586
- let bestFormat = null;
587
-
588
- // Main function called when images enter the viewport
589
- const loadImage = function(entries, observer) {
590
- for (let entry of entries) {
591
- if (entry.isIntersecting) {
592
- const thisWrapper = entry.target;
593
-
594
- // Find the high res image in the wrapper
595
- const thisImage = thisWrapper.querySelector('.high-res');
596
- const thisImageSource = thisImage.dataset.source;
597
-
598
- if (!thisImageSource) {
599
- console.warn('No data-source found for high-res image');
600
- return;
601
- }
602
-
603
- // Apply format based on detected support
604
- let finalImageSource = thisImageSource;
605
-
606
- if (bestFormat === 'avif') {
607
- finalImageSource = thisImageSource.replace(/\.(jpg|jpeg|png)$/i, '.avif');
608
- } else if (bestFormat === 'webp') {
609
- finalImageSource = thisImageSource.replace(/\.(jpg|jpeg|png)$/i, '.webp');
610
- }
611
- // If 'original' or null, use original (no change needed)
612
-
613
- thisImage.src = finalImageSource;
614
-
615
- // Take this image off the observe list to prevent duplicate loading
616
- observer.unobserve(thisWrapper);
617
-
618
- // Once the hi-res image has been loaded, add done class to trigger CSS transition
619
- thisImage.onload = function() {
620
- thisWrapper.classList.add('done');
621
- };
622
-
623
- // Handle loading errors gracefully
624
- thisImage.onerror = function() {
625
- thisWrapper.classList.add('error');
626
- };
627
- }
628
- }
629
- };
630
-
631
- const init = async function() {
632
- // Detect best supported format first
633
- bestFormat = await detectBestFormat();
634
-
635
- // Check for Intersection Observer support (not available in older browsers)
636
- if (!('IntersectionObserver' in window)) {
637
- // Fallback: load all images immediately for older browsers
638
- document.querySelectorAll('.js-progressive-image-wrapper').forEach(function(wrapper) {
639
- const img = wrapper.querySelector('.high-res');
640
- if (img && img.dataset.source) {
641
- let finalImageSource = img.dataset.source;
642
-
643
- // Apply detected format for fallback
644
- if (bestFormat === 'avif') {
645
- finalImageSource = img.dataset.source.replace(/\.(jpg|jpeg|png)$/i, '.avif');
646
- } else if (bestFormat === 'webp') {
647
- finalImageSource = img.dataset.source.replace(/\.(jpg|jpeg|png)$/i, '.webp');
648
- }
649
-
650
- img.src = finalImageSource;
651
- wrapper.classList.add('done');
652
- }
653
- });
654
- return;
655
- }
656
-
657
- // Create intersection observer with 50px margin (loads images slightly before they're visible)
658
- const observer = new IntersectionObserver(loadImage, {
659
- rootMargin: '50px'
660
- });
661
-
662
- // Loop over all image wrappers and add to intersection observer
663
- const allImageWrappers = document.querySelectorAll('.js-progressive-image-wrapper');
664
- for (let imageWrapper of allImageWrappers) {
665
- observer.observe(imageWrapper);
666
- }
667
- };
668
-
669
- // Format detection using createImageBitmap - more reliable than canvas encoding
670
- async function detectBestFormat() {
671
- const fallbackFormat = 'original';
672
-
673
- if (!window.createImageBitmap) return fallbackFormat;
674
-
675
- const avifData = 'data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUEAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAABYAAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAEAAAABAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgSAAAAAAABNjb2xybmNseAACAAIABoAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAAB5tZGF0EgAKBzgADlAgIGkyCR/wAABAAACvcA==';
676
- const webpData = 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoCAAEAAQAcJaQAA3AA/v3AgAA=';
677
-
678
- try {
679
- const avifBlob = await fetch(avifData).then(r => r.blob());
680
- await createImageBitmap(avifBlob);
681
- return 'avif';
682
- } catch {
683
- try {
684
- const webpBlob = await fetch(webpData).then(r => r.blob());
685
- await createImageBitmap(webpBlob);
686
- return 'webp';
687
- } catch {
688
- return fallbackFormat;
689
- }
690
- }
691
- }
692
-
693
- // Initialize when DOM is ready
694
- if (document.readyState === 'loading') {
695
- document.addEventListener('DOMContentLoaded', init);
696
- } else {
697
- init();
698
- }
699
-
700
- })();
701
- `;
702
-
703
- /**
704
- * Progressive image CSS styles
705
- * Handles aspect ratio, positioning, and smooth transitions between placeholder and high-res images
706
- */
707
- const progressiveImageCSS = `
708
- .responsive-wrapper {
709
- position: relative;
710
- overflow: hidden;
711
- background-color: #f0f0f0;
712
- }
713
-
714
- .responsive-wrapper .low-res {
715
- position: absolute;
716
- top: 0;
717
- left: 0;
718
- width: 100%;
719
- height: 100%;
720
- object-fit: cover;
721
- transition: opacity 0.4s ease;
722
- }
723
-
724
- .responsive-wrapper .high-res {
725
- position: absolute;
726
- top: 0;
727
- left: 0;
728
- width: 100%;
729
- height: 100%;
730
- object-fit: cover;
731
- opacity: 0;
732
- transition: opacity 0.4s ease;
733
- }
734
-
735
- .responsive-wrapper.done .high-res {
736
- opacity: 1;
737
- }
738
-
739
- .responsive-wrapper.done .low-res {
740
- opacity: 0;
741
- }
742
-
743
- .responsive-wrapper.error .low-res {
744
- filter: none;
745
- }
746
-
747
- /* Ensure images are responsive */
748
- .responsive-wrapper img {
749
- max-width: 100%;
750
- height: auto;
751
- }
752
- `;
753
-
754
- /**
755
- * HTML processing utilities for replacing img tags with responsive picture elements
756
- * Handles both standard and progressive loading modes
757
- */
758
-
759
- /**
760
- * Replace an img element with a responsive picture element
761
- * @param {Object} $ - Cheerio instance
762
- * @param {Object} $img - Cheerio image element
763
- * @param {Array<Object>} variants - Generated image variants
764
- * @param {Object} config - Plugin configuration
765
- */
766
- function replacePictureElement($, $img, variants, config) {
767
- if (variants.length === 0) {
768
- return;
769
- }
770
-
771
- // Get original img attributes
772
- const src = $img.attr('src');
773
- const alt = $img.attr('alt') || '';
774
- const className = $img.attr('class') || '';
775
- const sizesAttr = $img.attr('sizes') || config.sizes;
776
-
777
- // Group variants by format for creating <source> elements
778
- const variantsByFormat = {};
779
- variants.forEach(v => {
780
- if (!variantsByFormat[v.format]) {
781
- variantsByFormat[v.format] = [];
782
- }
783
- variantsByFormat[v.format].push(v);
784
- });
785
-
786
- // Create picture element that will contain all formats
787
- const $picture = $('<picture>');
788
-
789
- // Add format-specific source elements in preference order (avif, webp, then original)
790
- // Browser will use the first format it supports
791
- config.formats.forEach(format => {
792
- // Skip 'original' placeholder - it's handled separately
793
- if (format === 'original') {
794
- return;
795
- }
796
- const formatVariants = variantsByFormat[format];
797
- if (!formatVariants || formatVariants.length === 0) {
798
- return;
799
- }
800
-
801
- // Sort variants by width for proper srcset ordering
802
- formatVariants.sort((a, b) => a.width - b.width);
803
-
804
- // Create srcset string: "path 320w, path 640w, path 960w"
805
- const srcset = formatVariants.map(v => `/${v.path} ${v.width}w`).join(', ');
806
-
807
- // Create source element with format type and srcset
808
- $('<source>').attr('type', `image/${format}`).attr('srcset', srcset).attr('sizes', sizesAttr).appendTo($picture);
809
- });
810
-
811
- // Add original format as last source (fallback for browsers that don't support modern formats)
812
- const originalFormat = Object.keys(variantsByFormat).find(f => f !== 'avif' && f !== 'webp');
813
- if (originalFormat && variantsByFormat[originalFormat]) {
814
- const formatVariants = variantsByFormat[originalFormat];
815
- formatVariants.sort((a, b) => a.width - b.width);
816
- const srcset = formatVariants.map(v => `/${v.path} ${v.width}w`).join(', ');
817
- $('<source>').attr('type', `image/${originalFormat}`).attr('srcset', srcset).attr('sizes', sizesAttr).appendTo($picture);
818
- }
819
-
820
- // Create new img element that serves as the final fallback
821
- const $newImg = $('<img>').attr('src', src) // Keep original as fallback for very old browsers
822
- .attr('alt', alt);
823
-
824
- // Preserve original class attribute if present
825
- if (className) {
826
- $newImg.attr('class', className);
827
- }
828
-
829
- // Add native lazy loading if configured (improves performance)
830
- if (config.lazy) {
831
- $newImg.attr('loading', 'lazy');
832
- }
833
-
834
- // Add width/height attributes to prevent layout shift (CLS)
835
- if (config.dimensionAttributes && variants.length > 0) {
836
- // Use the largest variant as reference for dimensions
837
- const largestVariant = [...variants].sort((a, b) => b.width - a.width)[0];
838
- $newImg.attr('width', largestVariant.width);
839
- $newImg.attr('height', largestVariant.height);
840
- }
841
-
842
- // Copy any other attributes from original img (except ones we handle specially)
843
- for (const attrib in $img[0].attribs) {
844
- if (!['src', 'alt', 'class', 'width', 'height', 'sizes'].includes(attrib)) {
845
- $newImg.attr(attrib, $img.attr(attrib));
846
- }
847
- }
848
-
849
- // Add img to picture element
850
- $newImg.appendTo($picture);
851
-
852
- // Replace original img with picture element
853
- $img.replaceWith($picture);
854
- }
855
-
856
- /**
857
- * Process an HTML file to replace img tags with responsive picture elements
858
- * @param {string} htmlFile - Path to HTML file
859
- * @param {Object} fileData - File data object
860
- * @param {Object} files - Metalsmith files object
861
- * @param {Object} metalsmith - Metalsmith instance
862
- * @param {Map} processedImages - Cache of processed images
863
- * @param {Function} debug - Debug function
864
- * @param {Object} config - Plugin configuration
865
- * @return {Promise<void>} - Promise that resolves when the HTML file is processed
866
- */
867
- async function processHtmlFile(htmlFile, fileData, files, metalsmith, processedImages, debug, config) {
868
- debug(`Processing HTML file: ${htmlFile}`);
869
-
870
- // Validate file.contents before processing
871
- if (!fileData.contents || !Buffer.isBuffer(fileData.contents)) {
872
- debug(`Skipping ${htmlFile}: invalid or missing file contents`);
873
- return;
874
- }
875
- const content = fileData.contents.toString();
876
-
877
- // Parse HTML
878
- const $ = cheerio.load(content);
879
-
880
- // Find all images matching our selector (default: img:not([data-no-responsive]))
881
- const images = $(config.imgSelector);
882
- if (images.length === 0) {
883
- debug(`No images found in ${htmlFile}`);
884
- return;
885
- }
886
- debug(`Found ${images.length} images in ${htmlFile}`);
887
-
888
- // Process images in parallel with a concurrency limit to prevent overwhelming the system
889
- const imageChunks = [];
890
- for (let i = 0; i < images.length; i += config.concurrency) {
891
- imageChunks.push(Array.from(images).slice(i, i + config.concurrency));
892
- }
893
-
894
- // Process all chunks in parallel - each chunk processes its images in parallel
895
- await Promise.all(imageChunks.map(async imageChunk => {
896
- // Process images within each chunk in parallel
897
- await Promise.all(imageChunk.map(img => config.isProgressive ? processProgressiveImage({
898
- $,
899
- img,
900
- files,
901
- metalsmith,
902
- processedImages,
903
- debug,
904
- config
905
- }) : processImage({
906
- $,
907
- img,
908
- files,
909
- metalsmith,
910
- processedImages,
911
- debug,
912
- config,
913
- replacePictureElement
914
- })));
915
- }));
916
-
917
- // Inject progressive loading CSS and JavaScript if needed
918
- if (config.isProgressive) {
919
- injectProgressiveAssets($);
920
- }
921
-
922
- // Update file contents with modified HTML (converts back to Buffer)
923
- fileData.contents = Buffer.from($.html());
924
- }
925
-
926
- /**
927
- * Generate metadata file if configured
928
- * Creates a JSON manifest with information about all processed images
929
- * Useful for debugging or integration with other tools
930
- * @param {Map} processedImages - Cache of processed images
931
- * @param {Object} files - Metalsmith files object
932
- * @param {Object} config - Plugin configuration
933
- */
934
- function generateMetadata(processedImages, files, config) {
935
- const metadataObj = {};
936
- processedImages.forEach((value, key) => {
937
- // Extract the original path from the cache key (path:mtime)
938
- const [path] = key.split(':');
939
-
940
- // Handle both array format (from background processing) and object format (from HTML processing)
941
- const variants = Array.isArray(value) ? value : value.variants;
942
- metadataObj[path] = variants.map(v => ({
943
- path: v.path,
944
- width: v.width,
945
- height: v.height,
946
- format: v.format,
947
- size: v.size
948
- }));
949
- });
950
- const metadataPath = path.join(config.outputDir, 'responsive-images-manifest.json');
951
- files[metadataPath] = {
952
- contents: Buffer.from(JSON.stringify(metadataObj, null, 2))
953
- };
954
- }
955
-
956
- /**
957
- * Process a single image with progressive loading
958
- * Creates low-quality placeholders and high-resolution images with smooth transitions
959
- * @param {Object} context - Processing context
960
- * @return {Promise<void>} - Promise that resolves when the image is processed
961
- */
962
- async function processProgressiveImage({
963
- $,
964
- img,
965
- files,
966
- metalsmith,
967
- processedImages,
968
- debug,
969
- config
970
- }) {
971
- const $img = $(img);
972
- const src = $img.attr('src');
973
- debug(`Starting progressive processing for: ${src}`);
974
- if (!src || src.startsWith('http') || src.startsWith('data:')) {
975
- debug(`Skipping external or data URL: ${src}`);
976
- return;
977
- }
978
-
979
- // Skip SVG files - they are vector graphics that don't need responsive raster variants
980
- if (src.toLowerCase().endsWith('.svg')) {
981
- debug(`Skipping SVG file (vector graphics don't need responsive variants): ${src}`);
982
- return;
983
- }
984
-
985
- // Normalize src path to match Metalsmith files object keys
986
- const normalizedSrc = src.startsWith('/') ? src.slice(1) : src;
987
-
988
- // Image not in files, try to load it from the build directory (same logic as processImage)
989
- if (!files[normalizedSrc]) {
990
- try {
991
- const destination = metalsmith.destination();
992
- const imagePath = path.join(destination, normalizedSrc);
993
- if (fs.existsSync(imagePath)) {
994
- // Load the image contents from the build directory
995
- const imageBuffer = fs.readFileSync(imagePath);
996
-
997
- // Get modification time for cache busting
998
- const mtime = fs.statSync(imagePath).mtimeMs;
999
-
1000
- // Add it to files so the plugin can process it
1001
- files[normalizedSrc] = {
1002
- contents: imageBuffer,
1003
- mtime
1004
- };
1005
- } else {
1006
- debug(`Image not found in build: ${normalizedSrc}`);
1007
- return;
1008
- }
1009
- } catch (err) {
1010
- debug(`Error processing image from build directory: ${err.message}`);
1011
- return;
1012
- }
1013
- }
1014
-
1015
- // Create a cache key
1016
- const fileMtime = files[normalizedSrc].mtime || Date.now();
1017
- const cacheKey = `${normalizedSrc}:${fileMtime}`;
1018
-
1019
- // Check if we've already processed this image
1020
- if (processedImages.has(cacheKey)) {
1021
- debug(`Using cached variants for ${normalizedSrc}`);
1022
- const {
1023
- variants,
1024
- placeholderData
1025
- } = processedImages.get(cacheKey);
1026
- const $wrapper = createProgressiveWrapper($, $img, variants, placeholderData);
1027
- $img.replaceWith($wrapper);
1028
- return;
1029
- }
1030
- debug(`Processing progressive image: ${normalizedSrc}`);
1031
- try {
1032
- // Process image to generate all variants (sizes and formats)
1033
- const variants = await processImageToVariants(files[normalizedSrc].contents, normalizedSrc, debug, config);
1034
-
1035
- // Generate low-quality placeholder image for smooth loading transitions
1036
- const placeholderData = await generatePlaceholder(normalizedSrc, files[normalizedSrc].contents, config.placeholder, metalsmith);
1037
-
1038
- // Save all variants to Metalsmith files
1039
- variants.forEach(variant => {
1040
- files[variant.path] = {
1041
- contents: variant.buffer
1042
- };
1043
- });
1044
-
1045
- // Save placeholder to files
1046
- files[placeholderData.path] = {
1047
- contents: placeholderData.contents
1048
- };
1049
-
1050
- // Cache variants and placeholder for this image
1051
- processedImages.set(cacheKey, {
1052
- variants,
1053
- placeholderData
1054
- });
1055
-
1056
- // Create progressive wrapper with placeholder and high-res image
1057
- const $wrapper = createProgressiveWrapper($, $img, variants, placeholderData, config);
1058
- $img.replaceWith($wrapper);
1059
- } catch (err) {
1060
- debug(`Error processing progressive image: ${err.message}`);
1061
-
1062
- // Fallback to standard processing if progressive loading fails
1063
- try {
1064
- const variants = await processImageToVariants(files[normalizedSrc].contents, normalizedSrc, debug, config);
1065
- variants.forEach(variant => {
1066
- files[variant.path] = {
1067
- contents: variant.buffer
1068
- };
1069
- });
1070
- const $picture = createStandardPicture($, $img, variants, config);
1071
- $img.replaceWith($picture);
1072
- } catch (fallbackErr) {
1073
- debug(`Fallback processing also failed: ${fallbackErr.message}`);
1074
- }
1075
- }
1076
- }
1077
-
1078
- /**
1079
- * Inject progressive loading CSS and JavaScript assets
1080
- * Only injects if progressive images are actually present on the page
1081
- * @param {Object} $ - Cheerio instance
1082
- */
1083
- function injectProgressiveAssets($) {
1084
- // Check if progressive images exist on this page
1085
- const hasProgressiveImages = $('.js-progressive-image-wrapper').length > 0;
1086
- if (!hasProgressiveImages) {
1087
- return;
1088
- }
1089
-
1090
- // Inject CSS styles for progressive loading (only once per page)
1091
- if (!$('#progressive-image-styles').length) {
1092
- $('head').append(`<style id="progressive-image-styles">${progressiveImageCSS}</style>`);
1093
- }
1094
-
1095
- // Inject JavaScript for intersection observer and loading logic (only once per page)
1096
- if (!$('#progressive-image-loader').length) {
1097
- $('body').append(`<script id="progressive-image-loader">${progressiveImageLoader}</script>`);
1098
- }
1099
- }
1100
-
1101
- /**
1102
- * Metalsmith plugin for generating responsive images with optimal formats
1103
- * @module metalsmith-optimize-images
1104
- */
1105
-
1106
- /**
1107
- * Creates a responsive images plugin for Metalsmith
1108
- * Generates multiple sizes and formats of images and replaces img tags with picture elements
1109
- *
1110
- * @param {Options} [options={}] - Configuration options for the plugin
1111
- * @returns {import('metalsmith').Plugin} - Metalsmith plugin function
1112
- */
1113
- function optimizeImagesPlugin(options = {}) {
1114
- // Build configuration with defaults and user options
1115
- const config = buildConfig(options);
1116
-
1117
- /**
1118
- * The Metalsmith plugin function
1119
- * @param {Object} files - Metalsmith files object
1120
- * @param {Object} metalsmith - Metalsmith instance
1121
- * @param {Function} done - Callback function
1122
- * @return {void}
1123
- */
1124
- return async function optimizeImages(files, metalsmith, done) {
1125
- try {
1126
- const destination = metalsmith.destination();
1127
- const outputPath = path.join(destination, config.outputDir);
1128
-
1129
- // Set up debug function for logging (uses 'DEBUG=metalsmith-optimize-images*' env var)
1130
- const debug = metalsmith.debug('metalsmith-optimize-images');
1131
-
1132
- // Ensure the output directory exists where processed images will be saved
1133
- mkdirp.mkdirpSync(outputPath);
1134
-
1135
- // Find all HTML files that match the pattern (default: **/*.html)
1136
- // Also ensure they actually end with .html to avoid processing CSS/JS files
1137
- const htmlFiles = Object.keys(files).filter(file => {
1138
- // Must match the HTML pattern
1139
- if (!metalsmith.match(config.htmlPattern, file)) {
1140
- return false;
1141
- }
1142
-
1143
- // Must actually be an HTML file
1144
- if (!file.endsWith('.html')) {
1145
- return false;
1146
- }
1147
- return true;
1148
- });
1149
- if (htmlFiles.length === 0) {
1150
- debug('No HTML files found');
1151
- return done();
1152
- }
1153
-
1154
- // Cache to avoid re-processing identical images across different HTML files
1155
- // Key: "filepath:mtime", Value: array of processed image variants
1156
- const processedImages = new Map();
1157
-
1158
- // Chunk HTML files to respect concurrency limit (default: 5)
1159
- // This prevents overwhelming the system with too many parallel operations
1160
- const chunks = [];
1161
- for (let i = 0; i < htmlFiles.length; i += config.concurrency) {
1162
- chunks.push(htmlFiles.slice(i, i + config.concurrency));
1163
- }
1164
-
1165
- // Process all chunks in parallel - each chunk processes its files in parallel
1166
- // This creates a two-level parallelism: chunk-level and file-level within chunks
1167
- await Promise.all(chunks.map(async chunk => {
1168
- // Process files within each chunk in parallel
1169
- await Promise.all(chunk.map(async htmlFile => {
1170
- // This function parses HTML, finds images, processes them, and updates the HTML
1171
- await processHtmlFile(htmlFile, files[htmlFile], files, metalsmith, processedImages, debug, config);
1172
- }));
1173
- }));
1174
-
1175
- // Process unused images for background image support
1176
- // This finds images that weren't processed during HTML scanning and creates variants
1177
- // for use in CSS background-image with image-set()
1178
- if (config.processUnusedImages) {
1179
- await processUnusedImages(files, metalsmith, processedImages, debug, config);
1180
- }
1181
-
1182
- // Optional: Generate a JSON metadata file with information about all processed images
1183
- // Useful for debugging or integration with other tools
1184
- if (config.generateMetadata) {
1185
- generateMetadata(processedImages, files, config);
1186
- }
1187
- debug('Responsive images processing complete');
1188
- done();
1189
- } catch (err) {
1190
- // Use console.error for errors to ensure they're visible even if debug mode is not enabled
1191
- console.error(`Error in responsive images plugin: ${err.message}`);
1192
- done(err);
1193
- }
1194
- };
1195
- }
1196
-
1197
- /**
1198
- * Process unused images for background image support
1199
- * Finds images that weren't processed during HTML scanning and creates 1x/2x variants
1200
- * for use in CSS background-image with image-set()
1201
- * @param {Object} files - Metalsmith files object
1202
- * @param {Object} metalsmith - Metalsmith instance
1203
- * @param {Map} processedImages - Cache of already processed images
1204
- * @param {Function} debug - Debug function
1205
- * @param {Object} config - Plugin configuration
1206
- * @return {Promise<void>} - Promise that resolves when processing is complete
1207
- */
1208
- async function processUnusedImages(files, metalsmith, processedImages, debug, config) {
1209
- debug('Processing unused images for background image support');
1210
-
1211
- // Get all image paths that were already processed during HTML scanning
1212
- const processedImagePaths = new Set();
1213
- processedImages.forEach((_variants, cacheKey) => {
1214
- const [imagePath] = cacheKey.split(':');
1215
- processedImagePaths.add(imagePath);
1216
- });
1217
- debug(`Processed image paths from HTML: ${Array.from(processedImagePaths).join(', ')}`);
1218
-
1219
- // Find images that weren't processed during HTML scanning using hybrid approach
1220
- const allBackgroundImages = await findUnprocessedImages(files, metalsmith, config, processedImagePaths, debug);
1221
- debug(`Background images found to process: ${allBackgroundImages.map(img => img.path).join(', ')}`);
1222
- if (allBackgroundImages.length === 0) {
1223
- debug('No unused images found to process');
1224
- return;
1225
- }
1226
- debug(`Found ${allBackgroundImages.length} unused images to process for background use`);
1227
-
1228
- // Process background images in parallel for better performance
1229
- await Promise.all(allBackgroundImages.map(async imageObj => {
1230
- try {
1231
- debug(`Processing background image: ${imageObj.path} (source: ${imageObj.source})`);
1232
-
1233
- // Generate background variants with original size and half size
1234
- const variants = await processBackgroundImageVariants(imageObj.buffer, imageObj.path, debug, config);
1235
-
1236
- // Save all generated variants to Metalsmith files object
1237
- variants.forEach(variant => {
1238
- files[variant.path] = {
1239
- contents: variant.buffer
1240
- };
1241
- });
1242
-
1243
- // Cache the variants (using current timestamp as mtime for unused images)
1244
- const cacheKey = `${imageObj.path}:${Date.now()}`;
1245
- processedImages.set(cacheKey, variants);
1246
- debug(`Generated ${variants.length} background variants for ${imageObj.path}`);
1247
- } catch (err) {
1248
- debug(`Error processing background image ${imageObj.path}: ${err.message}`);
1249
- }
1250
- }));
1251
- debug('Background image processing complete');
1252
- }
1253
-
1254
- /**
1255
- * Find images that weren't processed during HTML scanning
1256
- * Uses a hybrid approach: scans filesystem first, then falls back to Metalsmith files object
1257
- * @param {Object} files - Metalsmith files object
1258
- * @param {Object} metalsmith - Metalsmith instance
1259
- * @param {Object} config - Plugin configuration
1260
- * @param {Set} processedImagePaths - Set of already processed image paths
1261
- * @param {Function} debug - Debug function
1262
- * @return {Promise<Array>} - Array of unprocessed image objects with {path, buffer}
1263
- */
1264
- async function findUnprocessedImages(files, metalsmith, config, processedImagePaths, debug) {
1265
- const unprocessedImages = [];
1266
- const sourceImagesDir = path.join(metalsmith.source(), 'lib/assets/images');
1267
- debug(`Looking for unprocessed images using hybrid approach`);
1268
-
1269
- // Method 1: Scan filesystem (for real testbed scenario)
1270
- try {
1271
- debug(`Attempting to scan source directory: ${sourceImagesDir}`);
1272
- debug(`Source directory exists: ${fs.existsSync(sourceImagesDir)}`);
1273
- debug(`Metalsmith source: ${metalsmith.source()}`);
1274
- debug(`Metalsmith destination: ${metalsmith.destination()}`);
1275
- if (fs.existsSync(sourceImagesDir)) {
1276
- debug(`Scanning source directory: ${sourceImagesDir}`);
1277
- const scanDirectory = (dir, relativePath = '') => {
1278
- const items = fs.readdirSync(dir);
1279
- debug(`Found ${items.length} items in ${dir}`);
1280
- for (const item of items) {
1281
- if (item === '.DS_Store') {
1282
- continue;
1283
- }
1284
- const fullPath = path.join(dir, item);
1285
- const itemRelativePath = path.join(relativePath, item);
1286
- if (fs.statSync(fullPath).isDirectory()) {
1287
- debug(`Scanning subdirectory: ${item}`);
1288
- scanDirectory(fullPath, itemRelativePath);
1289
- } else {
1290
- const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.avif'];
1291
- if (imageExtensions.some(ext => item.toLowerCase().endsWith(ext))) {
1292
- // Skip if this is in the responsive output directory
1293
- if (itemRelativePath.startsWith('responsive/') || itemRelativePath.includes('/responsive/') || fullPath.includes(config.outputDir)) {
1294
- debug(`Skipping responsive variant: ${itemRelativePath}`);
1295
- continue;
1296
- }
1297
- const buildPath = path.join('assets/images', itemRelativePath);
1298
- const normalizedBuildPath = buildPath.replace(/\\/g, '/');
1299
- debug(`Found filesystem image: ${item} -> ${normalizedBuildPath}`);
1300
- debug(`Already processed? ${processedImagePaths.has(normalizedBuildPath)}`);
1301
- if (!processedImagePaths.has(normalizedBuildPath)) {
1302
- debug(`Found unprocessed filesystem image: ${itemRelativePath}`);
1303
- const imageBuffer = fs.readFileSync(fullPath);
1304
- unprocessedImages.push({
1305
- path: itemRelativePath,
1306
- buffer: imageBuffer,
1307
- source: 'filesystem'
1308
- });
1309
- }
1310
- }
1311
- }
1312
- }
1313
- };
1314
- scanDirectory(sourceImagesDir);
1315
- } else {
1316
- debug(`Source directory does not exist, trying alternative paths...`);
1317
-
1318
- // Try alternative paths
1319
- const altPaths = [path.join(metalsmith.source(), 'assets/images'), path.join(metalsmith.source(), 'images'), path.join(metalsmith.destination(), 'assets/images'), path.join(process.cwd(), 'lib/assets/images'), path.join(process.cwd(), 'src/assets/images')];
1320
- for (const altPath of altPaths) {
1321
- debug(`Trying alternative path: ${altPath} - exists: ${fs.existsSync(altPath)}`);
1322
- if (fs.existsSync(altPath)) {
1323
- debug(`Found images at alternative path: ${altPath}`);
1324
-
1325
- // Scan the found alternative path
1326
- const scanAlternativeDirectory = (dir, relativePath = '') => {
1327
- const items = fs.readdirSync(dir);
1328
- debug(`Found ${items.length} items in alternative path ${dir}`);
1329
- for (const item of items) {
1330
- if (item === '.DS_Store') {
1331
- continue;
1332
- }
1333
- const fullPath = path.join(dir, item);
1334
- const itemRelativePath = path.join(relativePath, item);
1335
- if (fs.statSync(fullPath).isDirectory()) {
1336
- debug(`Scanning alternative subdirectory: ${item}`);
1337
- scanAlternativeDirectory(fullPath, itemRelativePath);
1338
- } else {
1339
- const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.avif'];
1340
- if (imageExtensions.some(ext => item.toLowerCase().endsWith(ext))) {
1341
- // Skip if this is in the responsive output directory
1342
- if (itemRelativePath.startsWith('responsive/') || itemRelativePath.includes('/responsive/') || fullPath.includes(config.outputDir)) {
1343
- debug(`Skipping responsive variant in alt scan: ${itemRelativePath}`);
1344
- continue;
1345
- }
1346
-
1347
- // For build directory, the path structure is already correct
1348
- const buildPath = altPath.includes('build') ? path.join('assets/images', itemRelativePath) : path.join('assets/images', itemRelativePath);
1349
- const normalizedBuildPath = buildPath.replace(/\\/g, '/');
1350
- debug(`Found alternative filesystem image: ${item} -> ${normalizedBuildPath}`);
1351
- debug(`Already processed? ${processedImagePaths.has(normalizedBuildPath)}`);
1352
- if (!processedImagePaths.has(normalizedBuildPath)) {
1353
- debug(`Found unprocessed alternative filesystem image: ${itemRelativePath}`);
1354
- const imageBuffer = fs.readFileSync(fullPath);
1355
- unprocessedImages.push({
1356
- path: itemRelativePath,
1357
- buffer: imageBuffer,
1358
- source: 'filesystem-alt'
1359
- });
1360
- }
1361
- }
1362
- }
1363
- }
1364
- };
1365
- scanAlternativeDirectory(altPath);
1366
- break; // Stop after finding and scanning the first valid path
1367
- }
1368
- }
1369
- }
1370
- } catch (err) {
1371
- debug(`Error scanning filesystem: ${err.message}`);
1372
- }
1373
-
1374
- // Method 2: Scan Metalsmith files object (for test scenarios and edge cases)
1375
- debug(`Scanning Metalsmith files object`);
1376
- const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.webp', '.avif'];
1377
- Object.keys(files).forEach(filePath => {
1378
- // Skip if not an image
1379
- if (!imageExtensions.some(ext => filePath.toLowerCase().endsWith(ext))) {
1380
- return;
1381
- }
1382
-
1383
- // Skip if it's already a responsive variant (comprehensive checks)
1384
- if (filePath.startsWith(`${config.outputDir}/`) || filePath.includes('/responsive/') || filePath.includes('responsive-images-manifest.json') || filePath.match(/-\d+w(-[a-f0-9]+)?\.(avif|webp|jpg|jpeg|png)$/i)) {
1385
- debug(`Skipping responsive variant in files object: ${filePath}`);
1386
- return;
1387
- }
1388
-
1389
- // Skip if already processed during HTML scanning
1390
- if (processedImagePaths.has(filePath)) {
1391
- debug(`Skipping already processed files object image: ${filePath}`);
1392
- return;
1393
- }
1394
-
1395
- // Check if we already found this image from filesystem scan
1396
- const isAlreadyFound = unprocessedImages.some(img => {
1397
- // For files object images starting with 'images/', check if filesystem found the same file
1398
- if (filePath.startsWith('images/')) {
1399
- const relativePath = filePath.replace('images/', '');
1400
- return img.path === relativePath;
1401
- }
1402
- return false;
1403
- });
1404
- if (!isAlreadyFound) {
1405
- debug(`Found unprocessed files object image: ${filePath}`);
1406
- unprocessedImages.push({
1407
- path: filePath,
1408
- buffer: files[filePath].contents,
1409
- source: 'files'
1410
- });
1411
- }
1412
- });
1413
- debug(`Found ${unprocessedImages.length} unprocessed images total`);
1414
- return unprocessedImages;
1415
- }
1416
-
1417
- /**
1418
- * Process a background image to create 1x (original) and 2x (half-size) variants
1419
- * for use with CSS image-set() for retina displays
1420
- * @param {Buffer} buffer - Original image buffer
1421
- * @param {string} originalPath - Original image path
1422
- * @param {Function} debugFn - Debug function for logging
1423
- * @param {Object} config - Plugin configuration
1424
- * @return {Promise<Array<Object>>} - Array of generated variants
1425
- */
1426
- async function processBackgroundImageVariants(buffer, originalPath, debugFn, config) {
1427
- const image = sharp(buffer);
1428
- const metadata = await image.metadata();
1429
- const variants = [];
1430
- debugFn(`Processing background image ${originalPath}: ${metadata.width}x${metadata.height}`);
1431
-
1432
- // Create 1x (original size) and 2x (half size) variants
1433
- const sizes = [{
1434
- width: metadata.width,
1435
- density: '1x'
1436
- }, {
1437
- width: Math.round(metadata.width / 2),
1438
- density: '2x'
1439
- }];
1440
-
1441
- // Process both sizes in parallel
1442
- const sizePromises = sizes.map(async size => {
1443
- // Create a Sharp instance for this size
1444
- const resized = image.clone().resize({
1445
- width: size.width,
1446
- withoutEnlargement: true // Don't upscale images
1447
- });
1448
-
1449
- // Get actual dimensions after resize
1450
- const resizedMeta = await resized.metadata();
1451
-
1452
- // Process each format in parallel for this size
1453
- const formatPromises = config.formats.map(async format => {
1454
- try {
1455
- // Skip problematic format combinations
1456
- if (format === 'original' && metadata.format.toLowerCase() === 'webp') {
1457
- return null;
1458
- }
1459
-
1460
- // Determine output format and Sharp method
1461
- let outputFormat = format;
1462
- let sharpMethod = format;
1463
- if (format === 'original') {
1464
- outputFormat = metadata.format.toLowerCase();
1465
- sharpMethod = outputFormat === 'jpeg' ? 'jpeg' : outputFormat;
1466
- }
1467
-
1468
- // Apply format-specific processing
1469
- let processedImage = resized.clone();
1470
- const formatOptions = config.formatOptions[format === 'original' ? outputFormat : format] || {};
1471
- if (sharpMethod === 'avif') {
1472
- processedImage = processedImage.avif(formatOptions);
1473
- } else if (sharpMethod === 'webp') {
1474
- processedImage = processedImage.webp(formatOptions);
1475
- } else if (sharpMethod === 'jpeg') {
1476
- processedImage = processedImage.jpeg(formatOptions);
1477
- } else if (sharpMethod === 'png') {
1478
- processedImage = processedImage.png(formatOptions);
1479
- }
1480
-
1481
- // Generate output buffer
1482
- const outputBuffer = await processedImage.toBuffer();
1483
-
1484
- // Generate variant path without hash for easier CSS usage
1485
- const variantPath = generateBackgroundVariantPath(originalPath, size.width, outputFormat, config);
1486
- debugFn(`Generated background variant: ${variantPath} (${size.density})`);
1487
- return {
1488
- path: variantPath,
1489
- buffer: outputBuffer,
1490
- width: resizedMeta.width,
1491
- height: resizedMeta.height,
1492
- format: outputFormat,
1493
- density: size.density
1494
- };
1495
- } catch (err) {
1496
- debugFn(`Error processing ${format} format for ${originalPath}: ${err.message}`);
1497
- return null;
1498
- }
1499
- });
1500
- const formatResults = await Promise.all(formatPromises);
1501
- return formatResults.filter(result => result !== null);
1502
- });
1503
- const sizeResults = await Promise.all(sizePromises);
1504
-
1505
- // Flatten the results
1506
- sizeResults.forEach(formatVariants => {
1507
- variants.push(...formatVariants);
1508
- });
1509
- debugFn(`Generated ${variants.length} background variants for ${originalPath}`);
1510
- return variants;
1511
- }
1512
-
1513
- /**
1514
- * Generate background image variant path without hash for easier CSS usage
1515
- * Creates predictable filenames that can be written in CSS without knowing the hash
1516
- * @param {string} originalPath - Original image path
1517
- * @param {number} width - Target width
1518
- * @param {string} format - Target format
1519
- * @param {Object} config - Plugin configuration
1520
- * @return {string} - Generated path without hash
1521
- */
1522
- function generateBackgroundVariantPath(originalPath, width, format, config) {
1523
- const parsedPath = path.parse(originalPath);
1524
- const originalFormat = parsedPath.ext.slice(1).toLowerCase();
1525
-
1526
- // If format is 'original', use the source format
1527
- const outputFormat = format === 'original' ? originalFormat : format;
1528
-
1529
- // Create background pattern without hash: '[filename]-[width]w.[format]'
1530
- // Results in: 'header1-1000w.webp' instead of 'header1-1000w-abc12345.webp'
1531
- const outputName = config.outputPattern.replace('[filename]', parsedPath.name).replace('[width]', width).replace('[format]', outputFormat).replace('-[hash]', '') // Remove hash placeholder and preceding dash
1532
- .replace('[hash]', ''); // Remove any remaining hash placeholder
1533
-
1534
- return path.join(config.outputDir, outputName);
1535
- }
1536
-
1537
- // Set function name for better debugging
1538
- Object.defineProperty(optimizeImagesPlugin, 'name', {
1539
- value: 'metalsmith-optimize-images'
1540
- });
1541
-
1542
- export { optimizeImagesPlugin as default };
1543
- //# sourceMappingURL=index.js.map