-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
wordpress-worker.js
872 lines (702 loc) · 38 KB
/
wordpress-worker.js
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
/**
* Worker Name: CloudFlare Image Resizing
* Worker URI: https://github.com/Mecanik/cloudflare-image-resizing-worker
* Description: This worker will replace Image URL's so you can use the CloudFlare Image Resizing service.
* Version: 2.0.0
* Author: Mecanik
* Author URI: https://github.com/Mecanik/
*
* License: Apache License 2.0 (https://github.com/Mecanik/cloudflare-image-resizing-worker/blob/main/LICENSE)
* Copyright (c) 2023 Mecanik
**/
// Edit the below as needed
// START EDIT -----------------------------------------------------
/**
* Multi-site support using the same Worker.
* Define each domain you want to run through this Worker, each with their configurable options.
* Using constants because for some unexplainable reason, Worker Enviroment Variables are not loading "sometimes".
* If you want to remove an IMAGE option, simple set 'undefined'. For example: IMAGE_QUALITY: undefined.
*/
const SITES_CONFIG = [
/*
{
DOMAIN: '...',
REWRITE_LINK_TAGS: true, REWRITE_STYLE_TAGS: true, REWRITE_IMAGE_TAGS: true, REWRITE_HREF_TAGS: true, REWRITE_DIV_TAGS: true, REWRITE_SVG_TAGS: true,
IMAGE_LAZY_LOAD: true, IMAGE_QUALITY: 90, IMAGE_FIT: 'crop', IMAGE_GRAVITY: 'auto', IMAGE_SHARPEN: 1, IMAGE_METADATA: 'none',
},
*/
// Add more as needed
];
// END EDIT -------------------------------------------------------
// DO NOT EDIT BELOW THIS LINE. JUST STOP.
// IF YOU NEED ASSISTANCE, BOOK A CONSULTATION: https://mecanik.dev/en/consulting/
const DEFAULT_CONFIG = {
// Self explanatory.
REWRITE_LINK_TAGS: true,
REWRITE_STYLE_TAGS: true,
REWRITE_IMAGE_TAGS: true,
REWRITE_HREF_TAGS: true,
REWRITE_DIV_TAGS: true,
REWRITE_SVG_TAGS: true,
// Browser-level support for lazy loading images.
// Browsers that do not support the loading attribute simply ignore it without side effects.
IMAGE_LAZY_LOAD: true,
// Quality determines the trade-off between image file size and visual quality.
// Range 1-100
IMAGE_QUALITY: 90,
// Resize method determines how the image should be scaled or cropped.
// Only used when the width and height can be retrieved.
// Values: 'scale-down', 'contain', 'cover', 'crop', 'pad'.
IMAGE_FIT: 'crop',
// When cropping with fit: "cover" and fit: "crop", this parameter defines the side or point that should not be cropped.
// Mode 'auto' selects focal point based on saliency detection (using maximum symmetric surround algorithm)
IMAGE_GRAVITY: 'auto',
// Specifies strength of sharpening filter to apply to the image.
// The value is a floating-point number between 0 (no sharpening, default) and 10 (maximum).
// Note that 1 is a recommended value for downscaled images.
// Range: 0 - 10
IMAGE_SHARPEN: 1,
// Controls amount of invisible metadata (EXIF data) that should be preserved. Color profiles and EXIF rotation are applied to the image even if the metadata is discarded.
// Note that if the Polish feature is enabled, all metadata may have been removed already and this option will have no effect.
// Options: 'keep', 'copyright', 'none'
IMAGE_METADATA: 'none',
};
function getConfigForDomain(domain) {
console.debug(`getConfigForDomain -> ${domain}`);
return SITES_CONFIG.find(config => config.DOMAIN === domain) || DEFAULT_CONFIG;
}
const WidthAndHeight = '(?:-(\\d+)x(\\d)-\\d+?)|(?:-(\\d+)x(\\d+))';
const regexWidthAndHeight = new RegExp(`${WidthAndHeight}`, 'gi');
const WidthAndHeightInFilename = '-(\\d+)x(\\d+)(?=\\.\\w+$)';
const regexWidthAndHeightInFilename = new RegExp(`${WidthAndHeightInFilename}`);
const WidthDescriptor = '(\\d+)w$';
const regexWidthDescriptor = new RegExp(`${WidthDescriptor}`);
const Sizes = '(\\d+)x(\\d+)';
const regexSizes = new RegExp(`${Sizes}`, '');
const Src = '(https?:\\/\\/(?:www\\.|(?!www)).*?|\/\/.*?)(\\/wp-content\\/(?:uploads|plugins|themes)\\/.*?\\.(?:jpe?g|gif|png|webp|svg))(.*?)';
const rgxSrc = new RegExp(`${Src}`, 'g');
const SrcSet = '(https?:\\/\\/(?:www\\.|(?!www)).*?|\/\/.*?)(\\/wp-content\\/(?:uploads|plugins|themes)\\/.*?\\.(?:jpe?g|gif|png|webp|svg))(\\s(\\d+)w,?\\s?)';
const rgxSrcSet = new RegExp(`${SrcSet}`, 'g');
const Css = "url\\(['\"]?((?!\\/cdn-cgi\\/image\\/)(https?:\\/\\/(?:www\\.|(?!www))[^\\s]+?)?(\\/wp-content\\/(?:uploads|plugins|themes)\\/[^\\s]+?\\.(?:jpe?g|gif|png|webp|svg)))['\"]?\\)";
const rgxCss = new RegExp(`${Css}`, 'g');
const CssSpecial1 = '(?:url\\(\\"?\\\'?(\\/?images\\/.*?\\.(?:jpe?g|gif|png|webp|svg))(.*?)\\"?\\\'?\\))';
const rgxCssSpecial1 = new RegExp(`${CssSpecial1}`, 'g');
/**
* Rewrites the <img> tags, including source sets, plugins like Revolution Slider and more.
* @author Mecanik
* @version 2.0.0
*/
class ImageTagRewriter extends HTMLRewriter {
constructor(config) {
super();
this.config = config;
}
async element(element) {
// If skip flag is true, exit early.
if (this.config.REWRITE_IMAGE_TAGS === false) {
console.debug(`ImageTagRewriter -> ${this.config.REWRITE_IMAGE_TAGS} (skipping)`);
return;
}
// This is a responsive image set
if (element.hasAttribute("src") && element.hasAttribute("srcset")) {
// Process src
const src = element.getAttribute("src");
if (src && src.indexOf("base64") === -1 && src.indexOf(`/wp-content/`) !== -1 && src.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
let width = element.getAttribute("width");
let height = element.getAttribute("height");
let hasSizes = !!width && !!height;
// Check if image has sizes set and adjust CDN accordingly
CDN += hasSizes ? `width=${width},height=${height},fit=${this.config.IMAGE_FIT},` : '';
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = src.replace(rgxSrc, `$1${CDN}$2$3`);
// Remove the sizes from the filename, pointing original image to Cloudflare for cropping
if (hasSizes) {
result = result.replace(regexWidthAndHeight, `$1`);
}
element.setAttribute("src", result);
}
// Now the srcset... this is a bit more complicated.
const srcset = element.getAttribute("srcset");
if (srcset && srcset.indexOf(`/wp-content/`) !== -1 && srcset.indexOf('/cdn-cgi/image/') === -1) {
// Split the srcset value into an array of image descriptors, using regex to split by comma possibly followed by space(s)
let descriptors = srcset.split(/\s*,\s*/);
// Iterate through the descriptors and modify each URL
descriptors = descriptors.map(descriptor => {
// Split on whitespace
let parts = descriptor.trim().split(/\s+/);
// If unexpected format, return original descriptor
if (parts.length !== 2)
return descriptor;
// This should return us 2 parts: ["https://....Image-300x200.jpg", "300w"]
let url = parts[0];
let width = parts[1];
// Try to extract the width and height from the filename
// If we fail, just fall back to the width descriptor
let match;
match = url.match(regexWidthAndHeightInFilename);
if (match) {
let _width = match[1];
let _height = match[2];
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += `width=${_width},height=${_height},fit=${this.config.IMAGE_FIT},`;
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
// Remove the sizes from the filename, pointing original image to Cloudflare for cropping
url = url.replace(regexWidthAndHeightInFilename, '');
} else {
// Extract width descriptor at the end, if filename did not contain dimensions
match = width.match(regexWidthDescriptor);
if (match) {
let _width = match[1];
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += `width=${_width},`;
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
} else {
// Well, everything is fucked. But we still point the image to Cloudflare!!!
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
}
}
// Reconstruct the descriptor
return `${url} ${width}`;
});
// Join the modified descriptors back into a string
let modifiedSrcset = descriptors.join(', ');
element.setAttribute("srcset", modifiedSrcset);
}
}
// This is a normal image
else if (element.hasAttribute("src") && !element.hasAttribute("srcset")) {
const src = element.getAttribute("src");
if (src && src.indexOf("base64") === -1 && src.indexOf(`/wp-content/`) !== -1 && src.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
let width = element.getAttribute("width");
let height = element.getAttribute("height");
let hasSizes = !!width && !!height;
// Check if image has sizes set and adjust CDN accordingly
CDN += hasSizes ? `width=${width},height=${height},fit=${this.config.IMAGE_FIT},` : '';
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = src.replace(rgxSrc, `$1${CDN}$2$3`);
// Remove the sizes from the filename, pointing original image to Cloudflare for cropping
if (hasSizes) {
result = result.replace(regexWidthAndHeight, `$1`);
}
element.setAttribute("src", result);
}
}
// Extra
const datasrc = element.getAttribute("data-src");
if (datasrc && datasrc.indexOf("base64") === -1 && datasrc.indexOf(`/wp-content/`) !== -1 && datasrc.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
let width = element.getAttribute("width");
let height = element.getAttribute("height");
let hasSizes = !!width && !!height;
// Check if image has sizes set and adjust CDN accordingly
CDN += hasSizes ? `width=${width},height=${height},fit=${this.config.IMAGE_FIT},` : '';
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = datasrc.replace(rgxSrc, `$1${CDN}$2$3`);
// Remove the sizes from the filename, pointing original image to Cloudflare for cropping
if (hasSizes) {
result = result.replace(regexWidthAndHeight, `$1`);
}
element.setAttribute("data-src", result);
}
// Extra
const datasrcset = element.getAttribute("data-srcset");
if (datasrcset && datasrcset.indexOf(`/wp-content/`) !== -1 && datasrcset.indexOf('/cdn-cgi/image/') === -1) {
// Split the datasrcset value into an array of image descriptors, using regex to split by comma possibly followed by space(s)
let descriptors = datasrcset.split(/\s*,\s*/);
// Iterate through the descriptors and modify each URL
descriptors = descriptors.map(descriptor => {
// Split on whitespace
let parts = descriptor.trim().split(/\s+/);
// If unexpected format, return original descriptor
if (parts.length !== 2)
return descriptor;
// This should return us 2 parts: ["https://....Image-300x200.jpg", "300w"]
let url = parts[0];
let width = parts[1];
// Try to extract the width and height from the filename
// If we fail, just fall back to the width descriptor
let match;
match = url.match(regexWidthAndHeightInFilename);
if (match) {
let _width = match[1];
let _height = match[2];
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += `width=${_width},height=${_height},fit=${this.config.IMAGE_FIT},`;
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
// Remove the sizes from the filename, pointing original image to Cloudflare for cropping
url = url.replace(regexWidthAndHeightInFilename, '');
} else {
// Extract width descriptor at the end, if filename did not contain dimensions
match = width.match(regexWidthDescriptor);
if (match) {
let _width = match[1];
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += `width=${_width},`;
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
} else {
// Well, everything is fucked. But we still point the image to Cloudflare!!!
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
}
}
// Reconstruct the descriptor
return `${url} ${width}`;
});
// Join the modified descriptors back into a string
let modifiedSrcset = descriptors.join(', ');
element.setAttribute("data-srcset", modifiedSrcset);
}
// Extra - handle "smart" plugins like Revolution Slider and other bananas
const datalazyload = element.getAttribute("data-lazyload");
if (datalazyload && datalazyload.indexOf("base64") === -1 && datalazyload.indexOf(`/wp-content/`) !== -1 && datalazyload.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
let width = element.getAttribute("width");
let height = element.getAttribute("height");
let hasSizes = !!width && !!height;
// Check if image has sizes set and adjust CDN accordingly
CDN += hasSizes ? `width=${width},height=${height},fit=${this.config.IMAGE_FIT},` : '';
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = datalazyload.replace(rgxSrc, `$1${CDN}$2$3`);
element.setAttribute("data-lazyload", result);
}
// Extra - handle "smart" plugins like WP Rocket and other bananas
const datalazysrc = element.getAttribute("data-lazy-src");
if (datalazysrc && datalazysrc.indexOf("base64") === -1 && datalazysrc.indexOf(`/wp-content/`) !== -1 && datalazysrc.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
let width = element.getAttribute("width");
let height = element.getAttribute("height");
let hasSizes = !!width && !!height;
// Check if image has sizes set and adjust CDN accordingly
CDN += hasSizes ? `width=${width},height=${height},fit=${this.config.IMAGE_FIT},` : '';
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = datalazysrc.replace(rgxSrc, `$1${CDN}$2$3`);
element.setAttribute("data-lazy-src", result);
}
// Extra - handle "smart" plugins like WP Rocket and other bananas
const datalazysrcset = element.getAttribute("data-lazy-srcset");
if (datalazysrcset && datalazysrcset.indexOf(`/wp-content/`) !== -1 && datalazysrcset.indexOf('/cdn-cgi/image/') === -1) {
// Split the srcset value into an array of image descriptors, using regex to split by comma possibly followed by space(s)
let descriptors = datalazysrcset.split(/\s*,\s*/);
// Iterate through the descriptors and modify each URL
descriptors = descriptors.map(descriptor => {
// Split on whitespace
let parts = descriptor.trim().split(/\s+/);
// If unexpected format, return original descriptor
if (parts.length !== 2)
return descriptor;
// This should return us 2 parts: ["https://....Image-300x200.jpg", "300w"]
let url = parts[0];
let width = parts[1];
// Try to extract the width and height from the filename
// If we fail, just fall back to the width descriptor
let match;
match = url.match(regexWidthAndHeightInFilename);
if (match) {
let _width = match[1];
let _height = match[2];
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += `width=${_width},height=${_height},fit=${this.config.IMAGE_FIT},`;
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
// Remove the sizes from the filename, pointing original image to Cloudflare for cropping
url = url.replace(regexWidthAndHeightInFilename, '');
} else {
// Extract width descriptor at the end, if filename did not contain dimensions
match = width.match(regexWidthDescriptor);
if (match) {
let _width = match[1];
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += `width=${_width},`;
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
} else {
// Well, everything is fucked. But we still point the image to Cloudflare!!!
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
// Insert our CDN URL
url = url.replace(rgxSrc, `$1${CDN}$2$3`);
}
}
// Reconstruct the descriptor
return `${url} ${width}`;
});
// Join the modified descriptors back into a string
let modifiedSrcset = descriptors.join(', ');
element.setAttribute("data-lazy-srcset", modifiedSrcset);
}
// Lazy load
if (!element.hasAttribute("loading") && this.config.IMAGE_LAZY_LOAD === true) {
element.setAttribute("loading", "lazy");
}
}
}
/**
* Rewrites the <a> tags, mostly used by image viewers like lightbox
* @author Mecanik
* @version 2.0.0
*/
class HrefTagRewriter extends HTMLRewriter {
constructor(config) {
super();
this.config = config;
}
async element(element) {
// If skip flag is true, exit early.
if (this.config.REWRITE_HREF_TAGS === false) {
console.debug(`HrefTagRewriter -> ${this.config.REWRITE_HREF_TAGS} (skipping)`);
return;
}
if (element.hasAttribute("href")) {
const href = element.getAttribute("href");
if (href && href.indexOf("base64") === -1 && href.indexOf(`/wp-content/`) !== -1 && href.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = href.replace(rgxSrc, `$1${CDN}$2$3`);
element.setAttribute("href", result);
}
}
}
}
/**
* Rewrites the <svg> tags, used to remove the empty svg's wordpress adds for no reason
* @author Mecanik
* @version 2.0.0
*/
class SvgTagRewriter extends HTMLRewriter {
constructor(config) {
super();
this.config = config;
}
async element(element) {
// If skip flag is true, exit early.
if (this.config.REWRITE_SVG_TAGS === false) {
console.debug(`SvgTagRewriter -> ${this.config.REWRITE_SVG_TAGS} (skipping)`);
return;
}
const viewBox = element.getAttribute("viewBox");
const _class = element.getAttribute("class");
const style = element.getAttribute("style");
// Remove: https://github.com/WordPress/gutenberg/issues/38299
// GG WP :)
if (viewBox && viewBox === "0 0 0 0" && !_class && style && style === "visibility: hidden; position: absolute; left: -9999px; overflow: hidden;") {
element.remove();
}
}
}
/**
* Rewrites the <style> tags, used to replace image sources for inline CSS
* @author Mecanik
* @version 2.0.0
*/
class StyleTagRewriter extends HTMLRewriter {
constructor(config) {
super();
this.buffer = "";
this.transformedBuffer = "";
this.config = config;
}
async text(inlineCSS) {
// If skip flag is true, exit early.
if (this.config.REWRITE_STYLE_TAGS === false) {
console.debug(`StyleTagRewriter -> ${this.config.REWRITE_STYLE_TAGS} (skipping)`);
return;
}
if(inlineCSS.text.indexOf("#wpadminbar") !== -1)
{
console.debug(`StyleTagRewriter -> WP Admin Bar CSS (skipping)`);
return;
}
// Buffering the text content
this.buffer += inlineCSS.text;
// If this is the last chunk, process the buffered content
if (inlineCSS.lastInTextNode) {
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = this.buffer.replace(rgxCss, `url('$2${CDN}$3')`);
// Replace with the processed content
inlineCSS.replace(result, {
html: false
});
this.transformedBuffer = result.replace(/>/g, '>');
}
}
async element(element) {
if (this.transformedBuffer) {
element.setInnerContent(this.transformedBuffer, {
html: true
});
this.buffer = "";
this.transformedBuffer = "";
}
}
}
/**
* Rewrites the <div> tags, used to replace image sources for inline CSS, plugins and more
* @author Mecanik
* @version 2.0.0
*/
class DivTagRewriter extends HTMLRewriter {
constructor(config) {
super();
this.config = config;
}
async element(element) {
// If skip flag is true, exit early.
if (this.config.REWRITE_DIV_TAGS === false) {
console.debug(`DivTagRewriter -> ${this.config.REWRITE_DIV_TAGS} (skipping)`);
return;
}
const style = element.getAttribute("style");
if (style && style.indexOf("base64") === -1 && style.indexOf(`/wp-content/`) !== -1 && style.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = style.replace(rgxCss, `url('$2${CDN}$3')`);
element.setAttribute("style", result);
}
// Handle "smart" plugins like "Ultimate_VC_Addons"
const bg = element.getAttribute("data-ultimate-bg");
if (bg && bg.indexOf("base64") === -1 && bg.indexOf(`/wp-content/`) !== -1 && bg.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = bg.replace(rgxSrc, `$1${CDN}$2$3`);
element.setAttribute("data-ultimate-bg", result);
}
// Handle "smart" plugins like "Ultimate_VC_Addons"
const dataimageid = element.getAttribute("data-image-id");
if (dataimageid && dataimageid.indexOf("base64") === -1 && dataimageid.indexOf(`/wp-content/`) !== -1 && dataimageid.indexOf('/cdn-cgi/image/') === -1) {
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
let result = bg.replace(rgxSrc, `$1${CDN}$2$3`);
element.setAttribute("data-image-id", result);
}
}
}
/**
* Rewrites the <link> tags, used to replace image sources for icons
* @author Mecanik
* @version 2.0.0
*/
class LinkTagRewriter extends HTMLRewriter {
constructor(config) {
super();
this.config = config;
}
async element(element) {
// If skip flag is true, exit early.
if (this.config.REWRITE_LINK_TAGS === false) {
console.debug(`LinkTagRewriter -> ${this.config.REWRITE_LINK_TAGS} (skipping)`);
return;
}
if (element.hasAttribute("rel")) {
const rel = element.getAttribute("rel");
if (rel && rel === "shortcut icon"
|| rel === "icon"
|| rel === "apple-touch-icon"
|| rel === "apple-touch-icon-precomposed"
|| rel === "apple-touch-startup-image"
) {
// Base CDN
let CDN = "/cdn-cgi/image/";
let sizes = element.getAttribute("sizes");
let matches = regexSizes.exec(sizes);
let hasSizes = !!matches;
// Check if image has sizes set and adjust CDN accordingly
CDN += hasSizes ? `width=${matches[1]},height=${matches[2]},fit=${this.config.IMAGE_FIT},` : '';
CDN += this.config.IMAGE_QUALITY ? `quality=${this.config.IMAGE_QUALITY},` : '';
CDN += this.config.IMAGE_GRAVITY ? `gravity=${this.config.IMAGE_GRAVITY},` : '';
CDN += this.config.IMAGE_SHARPEN ? `sharpen=${this.config.IMAGE_SHARPEN},` : '';
CDN += this.config.IMAGE_METADATA ? `metadata=${this.config.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
const href = element.getAttribute("href");
if (href && href.indexOf(`/wp-content/`) !== -1 && href.indexOf('/cdn-cgi/image/') === -1 && href.indexOf('.ico') === -1) {
let result = href.replace(rgxSrc, `$1${CDN}$2$3`);
// Remove the sizes from the filename, pointing original image to Cloudflare for cropping
if (hasSizes) {
result = result.replace(regexWidthAndHeight, `$1`);
}
element.setAttribute("href", result);
}
}
}
}
}
/**
* Entry point for worker in module syntax
* @author Mecanik
* @version 2.0.0
*/
export default {
async fetch(request, env, ctx) {
// If an error occurs, do not break the site, just continue
ctx.passThroughOnException();
// We need to fetch the origin full response.
const originResponse = await fetch(request);
if (originResponse.status !== 200) {
console.error(`Invalid Origin HTTP Status: ${originResponse.status}`);
return originResponse;
}
const {
origin,
pathname,
hostname
} = new URL(request.url);
// Do not rewrite images inside these paths (save some cost?)
if (pathname.indexOf("/wp-admin/") !== -1 || pathname.indexOf("/wp-login/") !== -1) {
console.error(`Bypassing page by path: ${pathname}`);
return originResponse;
}
// If the content type is HTML, we will run the rewriter
// If running APO this is not returned once the page is cached on the Edge servers.
const contentType = originResponse.headers.get("content-type");
if (contentType === null) {
console.error(`Missing Content Type: ${contentType}`);
return originResponse;
}
if (contentType.startsWith("text/html")) {
const domain = hostname.toLowerCase();
const currentConfig = getConfigForDomain(domain);
let newResponse = new HTMLRewriter()
.on('link', new LinkTagRewriter(currentConfig))
.on('style', new StyleTagRewriter(currentConfig))
.on('img', new ImageTagRewriter(currentConfig))
.on('a', new HrefTagRewriter(currentConfig))
.on('svg', new SvgTagRewriter(currentConfig))
.on('div', new DivTagRewriter(currentConfig))
.transform(originResponse);
return newResponse;
}
// Trick or Treat? We replace images inside ALL CSS files you have :)
else if (contentType.startsWith("text/css")) {
const domain = hostname.toLowerCase();
const currentConfig = getConfigForDomain(domain);
// Base CDN
let CDN = "/cdn-cgi/image/";
CDN += currentConfig.IMAGE_QUALITY ? `quality=${currentConfig.IMAGE_QUALITY},` : '';
CDN += currentConfig.IMAGE_GRAVITY ? `gravity=${currentConfig.IMAGE_GRAVITY},` : '';
CDN += currentConfig.IMAGE_SHARPEN ? `sharpen=${currentConfig.IMAGE_SHARPEN},` : '';
CDN += currentConfig.IMAGE_METADATA ? `metadata=${currentConfig.IMAGE_METADATA},` : '';
CDN += `format=auto,onerror=redirect`;
const originalBody = await originResponse.text();
let result = originalBody.replace(rgxCss, `url('$2${CDN}$3')`);
const response = new Response(result, {
headers: originResponse.headers,
});
return response;
} else {
console.error(`Invalid Content Type: ${contentType}`);
return originResponse;
}
}
}